feat(sounds): original Teams sounds with roaming settings
- Ringtones, notification and urgent sounds, call tones from the Teams CDN, cached at runtime - Ringtone read/write via MT useraggregatesettings and ringtonesettings, like Teams - Sound toggles and sound types in chatsvc userPersonalSettings - Settings: Sound rows with pickers and Preview, new Calls tab "Choose a ringtone" - Busy, call waiting (beep) and meeting start rules like Teams - Drop the synthesized ring tones Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -2,6 +2,6 @@
2
2
pub mod badge;
3
3
#[cfg_attr(not(windows), allow(dead_code))]
4
4
pub mod platform;
5
#[cfg_attr(not(windows), allow(dead_code))]
6
pub mod ring_tone;
7
5
pub mod sound_cache;
6
7
pub use chatsvc::sounds;
@@ -2,6 +2,6 @@2
pub mod badge;2
pub mod badge;3
#[cfg_attr(not(windows), allow(dead_code))]3
#[cfg_attr(not(windows), allow(dead_code))]4
pub mod platform;4
pub mod platform;5
#[cfg_attr(not(windows), allow(dead_code))]6
pub mod ring_tone;7
pub mod sound_cache;5
pub mod sound_cache;6
7
pub use chatsvc::sounds;@@ -1,10 +1,12 @@
1
use std::sync::Arc;
2
use std::sync::atomic::AtomicBool;
3
1
4
use gpui_kit::Window;
2
5
3
6
use calling::ShareKind;
4
7
5
8
use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};
6
9
use crate::notify::badge::Badge;
7
use crate::notify::ring_tone::Ringtone;
8
10
9
11
pub fn native_handle(_window: &Window) -> Option<NativeHandle> {
10
12
None
@@ -70,19 +72,7 @@ pub fn play_sound() {}
70
72
71
73
pub fn play_mp3(_bytes: Vec<u8>) {}
72
74
73
pub struct RingTone;
74
75
pub fn start_ring(_ringtone: Ringtone) -> Option<RingTone> {
76
None
77
}
78
79
pub fn start_ringback() -> Option<RingTone> {
80
None
81
}
82
83
pub fn play_preview(_ringtone: Ringtone) {}
84
85
pub fn play_meeting_chime() {}
75
pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}
86
76
87
77
pub struct Tray;
88
78
@@ -1,10 +1,12 @@1
use std::sync::Arc;2
use std::sync::atomic::AtomicBool;3
1
use gpui_kit::Window;4
use gpui_kit::Window;2
5
3
use calling::ShareKind;6
use calling::ShareKind;4
7
5
use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};8
use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};6
use crate::notify::badge::Badge;9
use crate::notify::badge::Badge;7
use crate::notify::ring_tone::Ringtone;8
10
9
pub fn native_handle(_window: &Window) -> Option<NativeHandle> {11
pub fn native_handle(_window: &Window) -> Option<NativeHandle> {10
None12
None@@ -70,19 +72,7 @@ pub fn play_sound() {}70
72
71
pub fn play_mp3(_bytes: Vec<u8>) {}73
pub fn play_mp3(_bytes: Vec<u8>) {}72
74
73
pub struct RingTone;75
pub fn play_mp3_until(_bytes: Vec<u8>, _looped: bool, _stop: Arc<AtomicBool>) {}74
75
pub fn start_ring(_ringtone: Ringtone) -> Option<RingTone> {76
None77
}78
79
pub fn start_ringback() -> Option<RingTone> {80
None81
}82
83
pub fn play_preview(_ringtone: Ringtone) {}84
85
pub fn play_meeting_chime() {}86
76
87
pub struct Tray;77
pub struct Tray;88
78
@@ -1,6 +1,5 @@
1
1
use std::ffi::c_void;
2
2
use std::io::Cursor;
3
use std::num::NonZero;
4
3
use std::sync::Arc;
5
4
use std::sync::atomic::{AtomicBool, Ordering};
6
5
use std::time::Duration;
@@ -43,7 +42,6 @@ use windows::core::{BOOL, PCWSTR, w};
43
42
use super::stack_plan::{StackPlan, stack_plan};
44
43
use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};
45
44
use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};
46
use crate::notify::ring_tone::{Ringtone, SAMPLE_RATE, meeting_chime, ringback_cycle};
47
45
48
46
const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");
49
47
const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../../app/assets/icon/teams-fast-256.png");
@@ -516,75 +514,28 @@ unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {
516
514
}
517
515
}
518
516
519
pub struct RingTone {
520
stop: Arc<AtomicBool>,
521
}
522
523
impl Drop for RingTone {
524
fn drop(&mut self) {
525
self.stop.store(true, Ordering::SeqCst);
526
}
527
}
528
529
pub fn start_ring(ringtone: Ringtone) -> Option<RingTone> {
530
start_cycle(ringtone.cycle(SAMPLE_RATE))
531
}
532
533
pub fn start_ringback() -> Option<RingTone> {
534
start_cycle(ringback_cycle(SAMPLE_RATE))
535
}
536
537
pub fn play_preview(ringtone: Ringtone) {
538
play_once(ringtone.cycle(SAMPLE_RATE));
539
}
540
541
pub fn play_meeting_chime() {
542
play_once(meeting_chime(SAMPLE_RATE));
543
}
544
545
fn play_once(cycle: Vec<f32>) {
517
pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {
546
518
std::thread::spawn(move || {
547
519
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
548
520
return;
549
521
};
550
522
sink.log_on_drop(false);
551
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
552
return;
553
};
554
let player = rodio::Player::connect_new(sink.mixer());
555
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle));
556
player.sleep_until_end();
557
});
558
}
559
560
fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {
561
let stop = Arc::new(AtomicBool::new(false));
562
let flag = stop.clone();
563
std::thread::spawn(move || {
564
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {
565
return;
566
};
567
sink.log_on_drop(false);
568
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {
569
return;
570
};
571
while !flag.load(Ordering::SeqCst) {
572
let player = rodio::Player::connect_new(sink.mixer());
573
player.append(rodio::buffer::SamplesBuffer::new(
574
channels,
575
rate,
576
cycle.clone(),
577
));
523
loop {
524
let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes.clone())) else {
525
return;
526
};
578
527
while !player.empty() {
579
if flag.load(Ordering::SeqCst) {
528
if stop.load(Ordering::SeqCst) {
580
529
player.stop();
581
530
return;
582
531
}
583
532
std::thread::sleep(RING_POLL);
584
533
}
534
if !looped || stop.load(Ordering::SeqCst) {
535
return;
536
}
585
537
}
586
538
});
587
Some(RingTone { stop })
588
539
}
589
540
590
541
pub fn play_mp3(bytes: Vec<u8>) {
@@ -1,6 +1,5 @@1
use std::ffi::c_void;1
use std::ffi::c_void;2
use std::io::Cursor;2
use std::io::Cursor;3
use std::num::NonZero;4
use std::sync::Arc;3
use std::sync::Arc;5
use std::sync::atomic::{AtomicBool, Ordering};4
use std::sync::atomic::{AtomicBool, Ordering};6
use std::time::Duration;5
use std::time::Duration;@@ -43,7 +42,6 @@ use windows::core::{BOOL, PCWSTR, w};43
use super::stack_plan::{StackPlan, stack_plan};42
use super::stack_plan::{StackPlan, stack_plan};44
use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};43
use super::{NativeHandle, ScreenRect, ShareGeometry, TrayCommand, WorkArea};45
use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};44
use crate::notify::badge::{BADGE_SIZE, Badge, render_badge};46
use crate::notify::ring_tone::{Ringtone, SAMPLE_RATE, meeting_chime, ringback_cycle};47
45
48
const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");46
const SOUND_BYTES: &[u8] = include_bytes!("../../../../app/assets/sounds/notification.mp3");49
const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../../app/assets/icon/teams-fast-256.png");47
const TRAY_ICON_PNG: &[u8] = include_bytes!("../../../../app/assets/icon/teams-fast-256.png");@@ -516,75 +514,28 @@ unsafe fn icon_from_badge(badge: &Badge) -> Option<HICON> {516
}514
}517
}515
}518
516
519
pub struct RingTone {517
pub fn play_mp3_until(bytes: Vec<u8>, looped: bool, stop: Arc<AtomicBool>) {520
stop: Arc<AtomicBool>,521
}522
523
impl Drop for RingTone {524
fn drop(&mut self) {525
self.stop.store(true, Ordering::SeqCst);526
}527
}528
529
pub fn start_ring(ringtone: Ringtone) -> Option<RingTone> {530
start_cycle(ringtone.cycle(SAMPLE_RATE))531
}532
533
pub fn start_ringback() -> Option<RingTone> {534
start_cycle(ringback_cycle(SAMPLE_RATE))535
}536
537
pub fn play_preview(ringtone: Ringtone) {538
play_once(ringtone.cycle(SAMPLE_RATE));539
}540
541
pub fn play_meeting_chime() {542
play_once(meeting_chime(SAMPLE_RATE));543
}544
545
fn play_once(cycle: Vec<f32>) {546
std::thread::spawn(move || {518
std::thread::spawn(move || {547
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {519
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {548
return;520
return;549
};521
};550
sink.log_on_drop(false);522
sink.log_on_drop(false);551
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {523
loop {552
return;524
let Ok(player) = rodio::play(sink.mixer(), Cursor::new(bytes.clone())) else {553
};525
return;554
let player = rodio::Player::connect_new(sink.mixer());526
};555
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle));556
player.sleep_until_end();557
});558
}559
560
fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {561
let stop = Arc::new(AtomicBool::new(false));562
let flag = stop.clone();563
std::thread::spawn(move || {564
let Ok(mut sink) = rodio::DeviceSinkBuilder::open_default_sink() else {565
return;566
};567
sink.log_on_drop(false);568
let (Some(channels), Some(rate)) = (NonZero::new(1u16), NonZero::new(SAMPLE_RATE)) else {569
return;570
};571
while !flag.load(Ordering::SeqCst) {572
let player = rodio::Player::connect_new(sink.mixer());573
player.append(rodio::buffer::SamplesBuffer::new(574
channels,575
rate,576
cycle.clone(),577
));578
while !player.empty() {527
while !player.empty() {579
if flag.load(Ordering::SeqCst) {528
if stop.load(Ordering::SeqCst) {580
player.stop();529
player.stop();581
return;530
return;582
}531
}583
std::thread::sleep(RING_POLL);532
std::thread::sleep(RING_POLL);584
}533
}534
if !looped || stop.load(Ordering::SeqCst) {535
return;536
}585
}537
}586
});538
});587
Some(RingTone { stop })588
}539
}589
540
590
pub fn play_mp3(bytes: Vec<u8>) {541
pub fn play_mp3(bytes: Vec<u8>) {@@ -1,211 +0,0 @@
1
use std::f32::consts::PI;
2
3
pub const SAMPLE_RATE: u32 = 44_100;
4
const FADE_SECONDS: f32 = 0.015;
5
const AMPLITUDE: f32 = 0.3;
6
const LOW_HZ: f32 = 784.;
7
const HIGH_HZ: f32 = 988.;
8
const BEEP_SECONDS: f32 = 0.18;
9
const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];
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 MEETING_NOTES: [f32; 3] = [659.25, 783.99, 1046.5];
18
const MEETING_NOTE_SECONDS: f32 = 0.26;
19
const RINGBACK_HZ: f32 = 425.;
20
const RINGBACK_ON_SECONDS: f32 = 1.;
21
const RINGBACK_CYCLE_SECONDS: f32 = 5.;
22
23
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
24
pub enum Ringtone {
25
#[default]
26
Default,
27
Chime,
28
Pulse,
29
}
30
31
impl Ringtone {
32
pub const ALL: [Ringtone; 3] = [Ringtone::Default, Ringtone::Chime, Ringtone::Pulse];
33
34
pub fn label(self) -> &'static str {
35
match self {
36
Ringtone::Default => "Default",
37
Ringtone::Chime => "Chime",
38
Ringtone::Pulse => "Pulse",
39
}
40
}
41
42
pub fn key(self) -> &'static str {
43
match self {
44
Ringtone::Default => "default",
45
Ringtone::Chime => "chime",
46
Ringtone::Pulse => "pulse",
47
}
48
}
49
50
pub fn from_key(key: &str) -> Option<Ringtone> {
51
Ringtone::ALL
52
.into_iter()
53
.find(|ringtone| ringtone.key() == key)
54
}
55
56
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {
57
match self {
58
Ringtone::Default => ring_cycle(sample_rate),
59
Ringtone::Chime => tone_cycle(
60
sample_rate,
61
&CHIME_NOTES,
62
CHIME_NOTE_SECONDS,
63
CHIME_CYCLE_SECONDS,
64
),
65
Ringtone::Pulse => tone_cycle(
66
sample_rate,
67
&PULSE_NOTES,
68
PULSE_NOTE_SECONDS,
69
PULSE_CYCLE_SECONDS,
70
),
71
}
72
}
73
}
74
75
pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {
76
tone_cycle(sample_rate, &BEEPS, BEEP_SECONDS, CYCLE_SECONDS)
77
}
78
79
pub fn meeting_chime(sample_rate: u32) -> Vec<f32> {
80
let seconds = MEETING_NOTE_SECONDS * MEETING_NOTES.len() as f32;
81
tone_cycle(sample_rate, &MEETING_NOTES, MEETING_NOTE_SECONDS, seconds)
82
}
83
84
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {
85
tone_cycle(
86
sample_rate,
87
&[RINGBACK_HZ],
88
RINGBACK_ON_SECONDS,
89
RINGBACK_CYCLE_SECONDS,
90
)
91
}
92
93
fn tone_cycle(
94
sample_rate: u32,
95
frequencies: &[f32],
96
tone_seconds: f32,
97
cycle_seconds: f32,
98
) -> Vec<f32> {
99
let total = (cycle_seconds * sample_rate as f32) as usize;
100
let tone = (tone_seconds * sample_rate as f32) as usize;
101
let fade = (FADE_SECONDS * sample_rate as f32) as usize;
102
let mut samples = vec![0.; total];
103
for (index, frequency) in frequencies.iter().enumerate() {
104
let start = index * tone;
105
for position in 0..tone {
106
let envelope = (position.min(tone - 1 - position) as f32 / fade as f32).min(1.);
107
let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;
108
samples[start + position] = AMPLITUDE * envelope * phase.sin();
109
}
110
}
111
samples
112
}
113
114
#[cfg(test)]
115
mod tests {
116
use super::*;
117
118
#[test]
119
fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {
120
let samples = ring_cycle(SAMPLE_RATE);
121
assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);
122
assert!(
123
samples
124
.iter()
125
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)
126
);
127
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
128
}
129
130
#[test]
131
fn beeps_fade_in_and_out_without_clicks() {
132
let samples = ring_cycle(SAMPLE_RATE);
133
assert_eq!(samples[0], 0.);
134
let beep = (BEEP_SECONDS * SAMPLE_RATE as f32) as usize;
135
assert!(samples[1].abs() < 0.05);
136
assert!(samples[beep - 1].abs() < 0.05);
137
}
138
139
#[test]
140
fn the_cycle_ends_in_silence_so_it_can_repeat() {
141
let samples = ring_cycle(SAMPLE_RATE);
142
let beeps_end = (BEEP_SECONDS * BEEPS.len() as f32 * SAMPLE_RATE as f32) as usize;
143
assert!(samples[beeps_end..].iter().all(|sample| *sample == 0.));
144
assert!(beeps_end < samples.len());
145
}
146
147
#[test]
148
fn the_cycle_is_the_same_every_time() {
149
assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));
150
}
151
152
#[test]
153
fn the_ringback_is_one_second_of_425_hz_then_four_seconds_of_silence() {
154
let samples = ringback_cycle(SAMPLE_RATE);
155
let rate = SAMPLE_RATE as usize;
156
assert_eq!(samples.len(), 5 * rate);
157
assert!(
158
samples[..rate]
159
.iter()
160
.any(|sample| sample.abs() > AMPLITUDE * 0.9)
161
);
162
assert!(samples[rate..].iter().all(|sample| *sample == 0.));
163
let crossings = samples[..rate]
164
.windows(2)
165
.filter(|pair| pair[0] < 0. && pair[1] >= 0.)
166
.count();
167
assert!((424..=426).contains(&crossings));
168
}
169
170
#[test]
171
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {
172
for ringtone in Ringtone::ALL {
173
let samples = ringtone.cycle(SAMPLE_RATE);
174
assert!(
175
samples
176
.iter()
177
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)
178
);
179
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
180
assert_eq!(samples.last().copied(), Some(0.));
181
}
182
assert_ne!(
183
Ringtone::Default.cycle(SAMPLE_RATE),
184
Ringtone::Chime.cycle(SAMPLE_RATE)
185
);
186
assert_ne!(
187
Ringtone::Chime.cycle(SAMPLE_RATE),
188
Ringtone::Pulse.cycle(SAMPLE_RATE)
189
);
190
}
191
192
#[test]
193
fn the_meeting_chime_is_short_quiet_and_audible() {
194
let samples = meeting_chime(SAMPLE_RATE);
195
assert!(samples.len() <= SAMPLE_RATE as usize);
196
assert!(
197
samples
198
.iter()
199
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)
200
);
201
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
202
}
203
204
#[test]
205
fn ringtone_keys_round_trip() {
206
for ringtone in Ringtone::ALL {
207
assert_eq!(Ringtone::from_key(ringtone.key()), Some(ringtone));
208
}
209
assert_eq!(Ringtone::from_key("nope"), None);
210
}
211
}
@@ -1,211 +0,0 @@1
use std::f32::consts::PI;2
3
pub const SAMPLE_RATE: u32 = 44_100;4
const FADE_SECONDS: f32 = 0.015;5
const AMPLITUDE: f32 = 0.3;6
const LOW_HZ: f32 = 784.;7
const HIGH_HZ: f32 = 988.;8
const BEEP_SECONDS: f32 = 0.18;9
const BEEPS: [f32; 4] = [LOW_HZ, HIGH_HZ, LOW_HZ, HIGH_HZ];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 MEETING_NOTES: [f32; 3] = [659.25, 783.99, 1046.5];18
const MEETING_NOTE_SECONDS: f32 = 0.26;19
const RINGBACK_HZ: f32 = 425.;20
const RINGBACK_ON_SECONDS: f32 = 1.;21
const RINGBACK_CYCLE_SECONDS: f32 = 5.;22
23
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]24
pub enum Ringtone {25
#[default]26
Default,27
Chime,28
Pulse,29
}30
31
impl Ringtone {32
pub const ALL: [Ringtone; 3] = [Ringtone::Default, Ringtone::Chime, Ringtone::Pulse];33
34
pub fn label(self) -> &'static str {35
match self {36
Ringtone::Default => "Default",37
Ringtone::Chime => "Chime",38
Ringtone::Pulse => "Pulse",39
}40
}41
42
pub fn key(self) -> &'static str {43
match self {44
Ringtone::Default => "default",45
Ringtone::Chime => "chime",46
Ringtone::Pulse => "pulse",47
}48
}49
50
pub fn from_key(key: &str) -> Option<Ringtone> {51
Ringtone::ALL52
.into_iter()53
.find(|ringtone| ringtone.key() == key)54
}55
56
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {57
match self {58
Ringtone::Default => ring_cycle(sample_rate),59
Ringtone::Chime => tone_cycle(60
sample_rate,61
&CHIME_NOTES,62
CHIME_NOTE_SECONDS,63
CHIME_CYCLE_SECONDS,64
),65
Ringtone::Pulse => tone_cycle(66
sample_rate,67
&PULSE_NOTES,68
PULSE_NOTE_SECONDS,69
PULSE_CYCLE_SECONDS,70
),71
}72
}73
}74
75
pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {76
tone_cycle(sample_rate, &BEEPS, BEEP_SECONDS, CYCLE_SECONDS)77
}78
79
pub fn meeting_chime(sample_rate: u32) -> Vec<f32> {80
let seconds = MEETING_NOTE_SECONDS * MEETING_NOTES.len() as f32;81
tone_cycle(sample_rate, &MEETING_NOTES, MEETING_NOTE_SECONDS, seconds)82
}83
84
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {85
tone_cycle(86
sample_rate,87
&[RINGBACK_HZ],88
RINGBACK_ON_SECONDS,89
RINGBACK_CYCLE_SECONDS,90
)91
}92
93
fn tone_cycle(94
sample_rate: u32,95
frequencies: &[f32],96
tone_seconds: f32,97
cycle_seconds: f32,98
) -> Vec<f32> {99
let total = (cycle_seconds * sample_rate as f32) as usize;100
let tone = (tone_seconds * sample_rate as f32) as usize;101
let fade = (FADE_SECONDS * sample_rate as f32) as usize;102
let mut samples = vec![0.; total];103
for (index, frequency) in frequencies.iter().enumerate() {104
let start = index * tone;105
for position in 0..tone {106
let envelope = (position.min(tone - 1 - position) as f32 / fade as f32).min(1.);107
let phase = 2. * PI * frequency * position as f32 / sample_rate as f32;108
samples[start + position] = AMPLITUDE * envelope * phase.sin();109
}110
}111
samples112
}113
114
#[cfg(test)]115
mod tests {116
use super::*;117
118
#[test]119
fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {120
let samples = ring_cycle(SAMPLE_RATE);121
assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);122
assert!(123
samples124
.iter()125
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)126
);127
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));128
}129
130
#[test]131
fn beeps_fade_in_and_out_without_clicks() {132
let samples = ring_cycle(SAMPLE_RATE);133
assert_eq!(samples[0], 0.);134
let beep = (BEEP_SECONDS * SAMPLE_RATE as f32) as usize;135
assert!(samples[1].abs() < 0.05);136
assert!(samples[beep - 1].abs() < 0.05);137
}138
139
#[test]140
fn the_cycle_ends_in_silence_so_it_can_repeat() {141
let samples = ring_cycle(SAMPLE_RATE);142
let beeps_end = (BEEP_SECONDS * BEEPS.len() as f32 * SAMPLE_RATE as f32) as usize;143
assert!(samples[beeps_end..].iter().all(|sample| *sample == 0.));144
assert!(beeps_end < samples.len());145
}146
147
#[test]148
fn the_cycle_is_the_same_every_time() {149
assert_eq!(ring_cycle(SAMPLE_RATE), ring_cycle(SAMPLE_RATE));150
}151
152
#[test]153
fn the_ringback_is_one_second_of_425_hz_then_four_seconds_of_silence() {154
let samples = ringback_cycle(SAMPLE_RATE);155
let rate = SAMPLE_RATE as usize;156
assert_eq!(samples.len(), 5 * rate);157
assert!(158
samples[..rate]159
.iter()160
.any(|sample| sample.abs() > AMPLITUDE * 0.9)161
);162
assert!(samples[rate..].iter().all(|sample| *sample == 0.));163
let crossings = samples[..rate]164
.windows(2)165
.filter(|pair| pair[0] < 0. && pair[1] >= 0.)166
.count();167
assert!((424..=426).contains(&crossings));168
}169
170
#[test]171
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {172
for ringtone in Ringtone::ALL {173
let samples = ringtone.cycle(SAMPLE_RATE);174
assert!(175
samples176
.iter()177
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)178
);179
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));180
assert_eq!(samples.last().copied(), Some(0.));181
}182
assert_ne!(183
Ringtone::Default.cycle(SAMPLE_RATE),184
Ringtone::Chime.cycle(SAMPLE_RATE)185
);186
assert_ne!(187
Ringtone::Chime.cycle(SAMPLE_RATE),188
Ringtone::Pulse.cycle(SAMPLE_RATE)189
);190
}191
192
#[test]193
fn the_meeting_chime_is_short_quiet_and_audible() {194
let samples = meeting_chime(SAMPLE_RATE);195
assert!(samples.len() <= SAMPLE_RATE as usize);196
assert!(197
samples198
.iter()199
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)200
);201
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));202
}203
204
#[test]205
fn ringtone_keys_round_trip() {206
for ringtone in Ringtone::ALL {207
assert_eq!(Ringtone::from_key(ringtone.key()), Some(ringtone));208
}209
assert_eq!(Ringtone::from_key("nope"), None);210
}211
}@@ -1,6 +1,8 @@
1
1
use std::fs;
2
2
use std::io;
3
3
use std::path::{Path, PathBuf};
4
use std::sync::Arc;
5
use std::sync::atomic::{AtomicBool, Ordering};
4
6
5
7
use gpui_kit::App;
6
8
@@ -66,14 +68,45 @@ pub fn prefetch(file_names: &[&'static str], cx: &App) {
66
68
}
67
69
68
70
pub fn play(file_name: &'static str, cx: &App) {
71
play_or(file_name, || {}, cx);
72
}
73
74
pub fn play_or(file_name: &'static str, fallback: fn(), cx: &App) {
75
let loading = load(file_name, cx);
76
cx.background_executor()
77
.spawn(async move {
78
match loading.await {
79
Some(bytes) => platform::play_mp3(bytes),
80
None => fallback(),
81
}
82
})
83
.detach();
84
}
85
86
pub struct SoundHandle {
87
stop: Arc<AtomicBool>,
88
}
89
90
impl Drop for SoundHandle {
91
fn drop(&mut self) {
92
self.stop.store(true, Ordering::SeqCst);
93
}
94
}
95
96
pub fn start(file_name: &'static str, looped: bool, cx: &App) -> SoundHandle {
97
let stop = Arc::new(AtomicBool::new(false));
98
let flag = stop.clone();
69
99
let loading = load(file_name, cx);
70
100
cx.background_executor()
71
101
.spawn(async move {
72
if let Some(bytes) = loading.await {
73
platform::play_mp3(bytes);
102
if let Some(bytes) = loading.await
103
&& !flag.load(Ordering::SeqCst)
104
{
105
platform::play_mp3_until(bytes, looped, flag);
74
106
}
75
107
})
76
108
.detach();
109
SoundHandle { stop }
77
110
}
78
111
79
112
#[cfg(test)]
@@ -1,6 +1,8 @@1
use std::fs;1
use std::fs;2
use std::io;2
use std::io;3
use std::path::{Path, PathBuf};3
use std::path::{Path, PathBuf};4
use std::sync::Arc;5
use std::sync::atomic::{AtomicBool, Ordering};4
6
5
use gpui_kit::App;7
use gpui_kit::App;6
8
@@ -66,14 +68,45 @@ pub fn prefetch(file_names: &[&'static str], cx: &App) {66
}68
}67
69
68
pub fn play(file_name: &'static str, cx: &App) {70
pub fn play(file_name: &'static str, cx: &App) {71
play_or(file_name, || {}, cx);72
}73
74
pub fn play_or(file_name: &'static str, fallback: fn(), cx: &App) {75
let loading = load(file_name, cx);76
cx.background_executor()77
.spawn(async move {78
match loading.await {79
Some(bytes) => platform::play_mp3(bytes),80
None => fallback(),81
}82
})83
.detach();84
}85
86
pub struct SoundHandle {87
stop: Arc<AtomicBool>,88
}89
90
impl Drop for SoundHandle {91
fn drop(&mut self) {92
self.stop.store(true, Ordering::SeqCst);93
}94
}95
96
pub fn start(file_name: &'static str, looped: bool, cx: &App) -> SoundHandle {97
let stop = Arc::new(AtomicBool::new(false));98
let flag = stop.clone();69
let loading = load(file_name, cx);99
let loading = load(file_name, cx);70
cx.background_executor()100
cx.background_executor()71
.spawn(async move {101
.spawn(async move {72
if let Some(bytes) = loading.await {102
if let Some(bytes) = loading.await73
platform::play_mp3(bytes);103
&& !flag.load(Ordering::SeqCst)104
{105
platform::play_mp3_until(bytes, looped, flag);74
}106
}75
})107
})76
.detach();108
.detach();109
SoundHandle { stop }77
}110
}78
111
79
#[cfg(test)]112
#[cfg(test)]@@ -1,37 +1,25 @@
1
1
use calling::{EndKind, EndReason, MeetingTarget};
2
use chatsvc::sounds::CallTone;
2
3
3
4
use super::model::{ActiveCall, CallKind};
4
5
5
6
const ORGID_PREFIX: &str = "8:orgid:";
6
7
pub const DISMISS_LABEL: &str = "Dismiss";
7
8
8
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9
pub enum EndTone {
10
CallEnded,
11
MeetingLeft,
12
}
13
14
impl EndTone {
15
pub const ALL: [EndTone; 2] = [EndTone::CallEnded, EndTone::MeetingLeft];
16
17
pub fn file_name(self) -> &'static str {
18
match self {
19
EndTone::CallEnded => "Teams_Call_Ended.mp3",
20
EndTone::MeetingLeft => "Teams_Meet_Up_Leave.mp3",
21
}
22
}
23
}
24
25
pub fn end_tone(kind: CallKind, moving_rooms: bool) -> Option<EndTone> {
9
pub fn end_tone(kind: CallKind, moving_rooms: bool) -> Option<CallTone> {
26
10
if moving_rooms {
27
11
return None;
28
12
}
29
13
Some(match kind {
30
CallKind::Meeting => EndTone::MeetingLeft,
31
CallKind::Test | CallKind::Direct | CallKind::Group => EndTone::CallEnded,
14
CallKind::Meeting => CallTone::MeetingLeft,
15
CallKind::Test | CallKind::Direct | CallKind::Group => CallTone::CallEnded,
32
16
})
33
17
}
34
18
19
pub fn join_tone(kind: CallKind) -> Option<CallTone> {
20
(kind == CallKind::Meeting).then_some(CallTone::MeetingJoined)
21
}
22
35
23
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36
24
pub enum EndCause {
37
25
Removed,
@@ -148,14 +136,21 @@ mod tests {
148
136
fn meetings_leave_with_the_meetup_tone_and_calls_with_the_call_tone() {
149
137
assert_eq!(
150
138
end_tone(CallKind::Meeting, false),
151
Some(EndTone::MeetingLeft)
139
Some(CallTone::MeetingLeft)
152
140
);
153
assert_eq!(end_tone(CallKind::Direct, false), Some(EndTone::CallEnded));
154
assert_eq!(end_tone(CallKind::Group, false), Some(EndTone::CallEnded));
155
assert_eq!(end_tone(CallKind::Test, false), Some(EndTone::CallEnded));
141
assert_eq!(end_tone(CallKind::Direct, false), Some(CallTone::CallEnded));
142
assert_eq!(end_tone(CallKind::Group, false), Some(CallTone::CallEnded));
143
assert_eq!(end_tone(CallKind::Test, false), Some(CallTone::CallEnded));
156
144
assert_eq!(end_tone(CallKind::Meeting, true), None);
157
145
}
158
146
147
#[test]
148
fn only_meetings_play_the_join_tone() {
149
assert_eq!(join_tone(CallKind::Meeting), Some(CallTone::MeetingJoined));
150
assert_eq!(join_tone(CallKind::Direct), None);
151
assert_eq!(join_tone(CallKind::Group), None);
152
}
153
159
154
#[test]
160
155
fn only_drops_and_removals_from_meetings_get_an_end_screen() {
161
156
let removed = EndReason::Remote(EndKind::Removed);
@@ -1,37 +1,25 @@1
use calling::{EndKind, EndReason, MeetingTarget};1
use calling::{EndKind, EndReason, MeetingTarget};2
use chatsvc::sounds::CallTone;2
3
3
use super::model::{ActiveCall, CallKind};4
use super::model::{ActiveCall, CallKind};4
5
5
const ORGID_PREFIX: &str = "8:orgid:";6
const ORGID_PREFIX: &str = "8:orgid:";6
pub const DISMISS_LABEL: &str = "Dismiss";7
pub const DISMISS_LABEL: &str = "Dismiss";7
8
8
#[derive(Debug, Clone, Copy, PartialEq, Eq)]9
pub fn end_tone(kind: CallKind, moving_rooms: bool) -> Option<CallTone> {9
pub enum EndTone {10
CallEnded,11
MeetingLeft,12
}13
14
impl EndTone {15
pub const ALL: [EndTone; 2] = [EndTone::CallEnded, EndTone::MeetingLeft];16
17
pub fn file_name(self) -> &'static str {18
match self {19
EndTone::CallEnded => "Teams_Call_Ended.mp3",20
EndTone::MeetingLeft => "Teams_Meet_Up_Leave.mp3",21
}22
}23
}24
25
pub fn end_tone(kind: CallKind, moving_rooms: bool) -> Option<EndTone> {26
if moving_rooms {10
if moving_rooms {27
return None;11
return None;28
}12
}29
Some(match kind {13
Some(match kind {30
CallKind::Meeting => EndTone::MeetingLeft,14
CallKind::Meeting => CallTone::MeetingLeft,31
CallKind::Test | CallKind::Direct | CallKind::Group => EndTone::CallEnded,15
CallKind::Test | CallKind::Direct | CallKind::Group => CallTone::CallEnded,32
})16
})33
}17
}34
18
19
pub fn join_tone(kind: CallKind) -> Option<CallTone> {20
(kind == CallKind::Meeting).then_some(CallTone::MeetingJoined)21
}22
35
#[derive(Debug, Clone, Copy, PartialEq, Eq)]23
#[derive(Debug, Clone, Copy, PartialEq, Eq)]36
pub enum EndCause {24
pub enum EndCause {37
Removed,25
Removed,@@ -148,14 +136,21 @@ mod tests {148
fn meetings_leave_with_the_meetup_tone_and_calls_with_the_call_tone() {136
fn meetings_leave_with_the_meetup_tone_and_calls_with_the_call_tone() {149
assert_eq!(137
assert_eq!(150
end_tone(CallKind::Meeting, false),138
end_tone(CallKind::Meeting, false),151
Some(EndTone::MeetingLeft)139
Some(CallTone::MeetingLeft)152
);140
);153
assert_eq!(end_tone(CallKind::Direct, false), Some(EndTone::CallEnded));141
assert_eq!(end_tone(CallKind::Direct, false), Some(CallTone::CallEnded));154
assert_eq!(end_tone(CallKind::Group, false), Some(EndTone::CallEnded));142
assert_eq!(end_tone(CallKind::Group, false), Some(CallTone::CallEnded));155
assert_eq!(end_tone(CallKind::Test, false), Some(EndTone::CallEnded));143
assert_eq!(end_tone(CallKind::Test, false), Some(CallTone::CallEnded));156
assert_eq!(end_tone(CallKind::Meeting, true), None);144
assert_eq!(end_tone(CallKind::Meeting, true), None);157
}145
}158
146
147
#[test]148
fn only_meetings_play_the_join_tone() {149
assert_eq!(join_tone(CallKind::Meeting), Some(CallTone::MeetingJoined));150
assert_eq!(join_tone(CallKind::Direct), None);151
assert_eq!(join_tone(CallKind::Group), None);152
}153
159
#[test]154
#[test]160
fn only_drops_and_removals_from_meetings_get_an_end_screen() {155
fn only_drops_and_removals_from_meetings_get_an_end_screen() {161
let removed = EndReason::Remote(EndKind::Removed);156
let removed = EndReason::Remote(EndKind::Removed);@@ -71,7 +71,8 @@ pub enum AppEvent {
71
71
MissedCall(MissedCall),
72
72
MeetingReminder,
73
73
MeetingChime,
74
CallEndTone(crate::call::end_screen::EndTone),
74
CallTone(chatsvc::sounds::CallTone),
75
SoundSettings,
75
76
}
76
77
77
78
#[derive(Debug, Clone, Copy, Default)]
@@ -134,6 +135,7 @@ pub struct AppState {
134
135
pub call_count: u64,
135
136
pub call_share_sound: bool,
136
137
pub recording_policy: teams_core::RecordingPolicy,
138
pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,
137
139
pub own_tenant: Option<String>,
138
140
pub call_share_motion: bool,
139
141
pub call_share_standout: bool,
@@ -282,6 +284,7 @@ impl AppState {
282
284
call_count: 0,
283
285
call_share_sound: false,
284
286
recording_policy: teams_core::RecordingPolicy::default(),
287
account_sounds: None,
285
288
own_tenant: None,
286
289
call_share_motion: false,
287
290
call_share_standout: false,
@@ -915,6 +918,7 @@ impl AppState {
915
918
self.refresh_scheduled(cx);
916
919
self.refresh_translation_settings(cx);
917
920
self.refresh_recording_policy(cx);
921
self.refresh_sound_settings(cx);
918
922
let waiting = self.directory.waiting_presence_ids();
919
923
self.request_presence(waiting, cx);
920
924
self.refresh_own_status(cx);
@@ -71,7 +71,8 @@ pub enum AppEvent {71
MissedCall(MissedCall),71
MissedCall(MissedCall),72
MeetingReminder,72
MeetingReminder,73
MeetingChime,73
MeetingChime,74
CallEndTone(crate::call::end_screen::EndTone),74
CallTone(chatsvc::sounds::CallTone),75
SoundSettings,75
}76
}76
77
77
#[derive(Debug, Clone, Copy, Default)]78
#[derive(Debug, Clone, Copy, Default)]@@ -134,6 +135,7 @@ pub struct AppState {134
pub call_count: u64,135
pub call_count: u64,135
pub call_share_sound: bool,136
pub call_share_sound: bool,136
pub recording_policy: teams_core::RecordingPolicy,137
pub recording_policy: teams_core::RecordingPolicy,138
pub account_sounds: Option<chatsvc::sound_settings::SoundSettings>,137
pub own_tenant: Option<String>,139
pub own_tenant: Option<String>,138
pub call_share_motion: bool,140
pub call_share_motion: bool,139
pub call_share_standout: bool,141
pub call_share_standout: bool,@@ -282,6 +284,7 @@ impl AppState {282
call_count: 0,284
call_count: 0,283
call_share_sound: false,285
call_share_sound: false,284
recording_policy: teams_core::RecordingPolicy::default(),286
recording_policy: teams_core::RecordingPolicy::default(),287
account_sounds: None,285
own_tenant: None,288
own_tenant: None,286
call_share_motion: false,289
call_share_motion: false,287
call_share_standout: false,290
call_share_standout: false,@@ -915,6 +918,7 @@ impl AppState {915
self.refresh_scheduled(cx);918
self.refresh_scheduled(cx);916
self.refresh_translation_settings(cx);919
self.refresh_translation_settings(cx);917
self.refresh_recording_policy(cx);920
self.refresh_recording_policy(cx);921
self.refresh_sound_settings(cx);918
let waiting = self.directory.waiting_presence_ids();922
let waiting = self.directory.waiting_presence_ids();919
self.request_presence(waiting, cx);923
self.request_presence(waiting, cx);920
self.refresh_own_status(cx);924
self.refresh_own_status(cx);@@ -554,7 +554,7 @@ impl AppState {
554
554
.take()
555
555
.or_else(|| room_closed_move(call, &reason));
556
556
if let Some(tone) = end_tone(call.model.kind, next_move.is_some()) {
557
cx.emit(AppEvent::CallEndTone(tone));
557
cx.emit(AppEvent::CallTone(tone));
558
558
}
559
559
let end_screen = (call.viewing && !back_to_held && next_move.is_none())
560
560
.then(|| CallEndScreen::for_call(call, &reason))
@@ -1372,7 +1372,7 @@ mod tests {
1372
1372
use crate::call::background::BackgroundPick;
1373
1373
use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};
1374
1374
use crate::call::demo::demo_ring;
1375
use crate::call::end_screen::EndTone;
1375
use chatsvc::sounds::CallTone;
1376
1376
use crate::call::features::room_closed_move;
1377
1377
use crate::call::model::BreakoutState;
1378
1378
use crate::data::Person;
@@ -2364,7 +2364,7 @@ mod tests {
2364
2364
let heard = tones.clone();
2365
2365
cx.update(|cx| {
2366
2366
cx.subscribe(&app, move |_, event: &AppEvent, _| {
2367
if let AppEvent::CallEndTone(tone) = event {
2367
if let AppEvent::CallTone(tone) = event {
2368
2368
heard.borrow_mut().push(*tone);
2369
2369
}
2370
2370
})
@@ -2380,7 +2380,7 @@ mod tests {
2380
2380
assert!(state.call_end.is_none());
2381
2381
})
2382
2382
});
2383
assert_eq!(*tones.borrow(), vec![EndTone::CallEnded]);
2383
assert_eq!(*tones.borrow(), vec![CallTone::CallEnded]);
2384
2384
}
2385
2385
2386
2386
#[gpui_kit::test]
@@ -554,7 +554,7 @@ impl AppState {554
.take()554
.take()555
.or_else(|| room_closed_move(call, &reason));555
.or_else(|| room_closed_move(call, &reason));556
if let Some(tone) = end_tone(call.model.kind, next_move.is_some()) {556
if let Some(tone) = end_tone(call.model.kind, next_move.is_some()) {557
cx.emit(AppEvent::CallEndTone(tone));557
cx.emit(AppEvent::CallTone(tone));558
}558
}559
let end_screen = (call.viewing && !back_to_held && next_move.is_none())559
let end_screen = (call.viewing && !back_to_held && next_move.is_none())560
.then(|| CallEndScreen::for_call(call, &reason))560
.then(|| CallEndScreen::for_call(call, &reason))@@ -1372,7 +1372,7 @@ mod tests {1372
use crate::call::background::BackgroundPick;1372
use crate::call::background::BackgroundPick;1373
use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};1373
use crate::call::{CaptionPosition, CaptionSize, RecordAction, ViewSettings};1374
use crate::call::demo::demo_ring;1374
use crate::call::demo::demo_ring;1375
use crate::call::end_screen::EndTone;1375
use chatsvc::sounds::CallTone;1376
use crate::call::features::room_closed_move;1376
use crate::call::features::room_closed_move;1377
use crate::call::model::BreakoutState;1377
use crate::call::model::BreakoutState;1378
use crate::data::Person;1378
use crate::data::Person;@@ -2364,7 +2364,7 @@ mod tests {2364
let heard = tones.clone();2364
let heard = tones.clone();2365
cx.update(|cx| {2365
cx.update(|cx| {2366
cx.subscribe(&app, move |_, event: &AppEvent, _| {2366
cx.subscribe(&app, move |_, event: &AppEvent, _| {2367
if let AppEvent::CallEndTone(tone) = event {2367
if let AppEvent::CallTone(tone) = event {2368
heard.borrow_mut().push(*tone);2368
heard.borrow_mut().push(*tone);2369
}2369
}2370
})2370
})@@ -2380,7 +2380,7 @@ mod tests {2380
assert!(state.call_end.is_none());2380
assert!(state.call_end.is_none());2381
})2381
})2382
});2382
});2383
assert_eq!(*tones.borrow(), vec![EndTone::CallEnded]);2383
assert_eq!(*tones.borrow(), vec![CallTone::CallEnded]);2384
}2384
}2385
2385
2386
#[gpui_kit::test]2386
#[gpui_kit::test]@@ -2,8 +2,9 @@ use calling::{CallCommand, CallSpec, MeetingTarget, MuteCommand};
2
2
use gpui_kit::Context;
3
3
4
4
use super::demo::{DemoCall, demo_guests};
5
use super::end_screen::join_tone;
5
6
use super::model::CallModel;
6
use crate::app_state::AppState;
7
use crate::app_state::{AppEvent, AppState};
7
8
8
9
const OPTIONS_META_KEY: &str = "prejoin_options";
9
10
@@ -157,6 +158,9 @@ impl AppState {
157
158
return;
158
159
};
159
160
let model = CallModel::meeting(&join.title, join.organizer);
161
if let Some(tone) = join_tone(model.kind) {
162
cx.emit(AppEvent::CallTone(tone));
163
}
160
164
self.begin_call(handle, model, join.conversation_id, cx);
161
165
if let Some(call) = self.call.as_mut() {
162
166
call.meeting_target = Some(join.target);
@@ -2,8 +2,9 @@ use calling::{CallCommand, CallSpec, MeetingTarget, MuteCommand};2
use gpui_kit::Context;2
use gpui_kit::Context;3
3
4
use super::demo::{DemoCall, demo_guests};4
use super::demo::{DemoCall, demo_guests};5
use super::end_screen::join_tone;5
use super::model::CallModel;6
use super::model::CallModel;6
use crate::app_state::AppState;7
use crate::app_state::{AppEvent, AppState};7
8
8
const OPTIONS_META_KEY: &str = "prejoin_options";9
const OPTIONS_META_KEY: &str = "prejoin_options";9
10
@@ -157,6 +158,9 @@ impl AppState {157
return;158
return;158
};159
};159
let model = CallModel::meeting(&join.title, join.organizer);160
let model = CallModel::meeting(&join.title, join.organizer);161
if let Some(tone) = join_tone(model.kind) {162
cx.emit(AppEvent::CallTone(tone));163
}160
self.begin_call(handle, model, join.conversation_id, cx);164
self.begin_call(handle, model, join.conversation_id, cx);161
if let Some(call) = self.call.as_mut() {165
if let Some(call) = self.call.as_mut() {162
call.meeting_target = Some(join.target);166
call.meeting_target = Some(join.target);@@ -33,6 +33,7 @@ pub mod scheduled;
33
33
pub mod scheduled_rows;
34
34
pub mod section_actions;
35
35
pub mod sidebar_model;
36
pub mod sound_actions;
36
37
pub mod stored_outgoing;
37
38
pub mod task_dialog;
38
39
pub mod translation_actions;
@@ -33,6 +33,7 @@ pub mod scheduled;33
pub mod scheduled_rows;33
pub mod scheduled_rows;34
pub mod section_actions;34
pub mod section_actions;35
pub mod sidebar_model;35
pub mod sidebar_model;36
pub mod sound_actions;36
pub mod stored_outgoing;37
pub mod stored_outgoing;37
pub mod task_dialog;38
pub mod task_dialog;38
pub mod translation_actions;39
pub mod translation_actions;@@ -5,7 +5,8 @@ pub mod settings;
5
5
pub mod stack;
6
6
pub mod text;
7
7
8
pub use app_base::notify::{badge, platform, ring_tone, sound_cache};
8
pub use app_base::notify::{badge, platform, sound_cache, sounds};
9
pub use chatsvc::sound_settings;
9
10
pub use incoming::{IncomingTracker, LateArrivals, preview_of};
10
11
#[cfg(windows)]
11
12
pub use platform::native_handle;
@@ -5,7 +5,8 @@ pub mod settings;5
pub mod stack;5
pub mod stack;6
pub mod text;6
pub mod text;7
7
8
pub use app_base::notify::{badge, platform, ring_tone, sound_cache};8
pub use app_base::notify::{badge, platform, sound_cache, sounds};9
pub use chatsvc::sound_settings;9
pub use incoming::{IncomingTracker, LateArrivals, preview_of};10
pub use incoming::{IncomingTracker, LateArrivals, preview_of};10
#[cfg(windows)]11
#[cfg(windows)]11
pub use platform::native_handle;12
pub use platform::native_handle;@@ -5,7 +5,8 @@ use calling::Progress;
5
5
use chrono::{DateTime, Utc};
6
6
use store::{ChannelNotificationLevel, ChannelNotifications};
7
7
8
use super::ring_tone::Ringtone;
8
use super::sound_settings::SoundSettings;
9
use super::sounds::Ringtone;
9
10
use crate::call::{CallKind, CallModel};
10
11
11
12
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);
@@ -68,7 +69,6 @@ impl Corner {
68
69
69
70
#[derive(Debug, Clone, PartialEq, Eq)]
70
71
pub struct Settings {
71
pub sound: bool,
72
72
pub mentions_only: bool,
73
73
pub preview: bool,
74
74
pub corner: Corner,
@@ -76,13 +76,12 @@ pub struct Settings {
76
76
pub close_to_tray: bool,
77
77
pub do_not_disturb: bool,
78
78
pub mute_in_calls: bool,
79
pub ringtone: Ringtone,
79
pub sounds: SoundSettings,
80
80
}
81
81
82
82
impl Default for Settings {
83
83
fn default() -> Self {
84
84
Settings {
85
sound: true,
86
85
mentions_only: false,
87
86
preview: true,
88
87
corner: Corner::BottomRight,
@@ -90,7 +89,7 @@ impl Default for Settings {
90
89
close_to_tray: true,
91
90
do_not_disturb: false,
92
91
mute_in_calls: false,
93
ringtone: Ringtone::Default,
92
sounds: SoundSettings::default(),
94
93
}
95
94
}
96
95
}
@@ -143,9 +142,16 @@ pub struct Environment {
143
142
pub chat_in_foreground: bool,
144
143
pub system_quiet: bool,
145
144
pub own_do_not_disturb: bool,
145
pub own_busy: bool,
146
146
pub in_call: bool,
147
147
}
148
148
149
impl Environment {
150
pub fn busy(&self) -> bool {
151
self.in_call || self.own_busy
152
}
153
}
154
149
155
pub fn in_call(server_in_call: bool, native_call: Option<&CallModel>) -> bool {
150
156
server_in_call || native_call.is_some_and(CallModel::is_active)
151
157
}
@@ -214,10 +220,28 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment
214
220
}
215
221
Decision {
216
222
toast: true,
217
sound: settings.sound && !environment.in_call,
223
sound: settings.sounds.notification_sound
224
&& (settings.sounds.sound_when_busy || !environment.busy()),
218
225
}
219
226
}
220
227
228
fn busy_allows_sound(settings: &Settings, busy: bool) -> bool {
229
!busy || settings.sounds.sound_when_busy
230
}
231
232
pub fn ringtone_for(settings: &Settings, in_call: bool, busy: bool) -> Option<Ringtone> {
233
let audible = settings.sounds.call_and_meeting_sound && busy_allows_sound(settings, busy);
234
audible.then_some(if in_call {
235
Ringtone::Beep
236
} else {
237
settings.sounds.ringtones.regular
238
})
239
}
240
241
pub fn meeting_start_sound(settings: &Settings, busy: bool) -> bool {
242
settings.sounds.call_and_meeting_sound && busy_allows_sound(settings, busy)
243
}
244
221
245
#[derive(Default)]
222
246
pub struct SoundThrottle {
223
247
last_played: HashMap<String, Instant>,
@@ -383,19 +407,58 @@ mod tests {
383
407
}
384
408
385
409
#[test]
386
fn call_keeps_toast_but_drops_sound() {
387
let environment = Environment {
388
in_call: true,
410
fn calls_and_busy_keep_the_sound_unless_the_busy_setting_is_off() {
411
let busy_environments = [
412
Environment {
413
in_call: true,
414
..Default::default()
415
},
416
Environment {
417
own_busy: true,
418
..Default::default()
419
},
420
];
421
let quiet_when_busy = Settings {
422
sounds: SoundSettings {
423
sound_when_busy: false,
424
..Default::default()
425
},
389
426
..Default::default()
390
427
};
391
let decision = decide(&Settings::default(), &group(), environment);
392
assert_eq!(
393
decision,
394
Decision {
395
toast: true,
396
sound: false
397
}
398
);
428
for environment in busy_environments {
429
assert!(decide(&Settings::default(), &group(), environment).sound);
430
assert_eq!(
431
decide(&quiet_when_busy, &group(), environment),
432
Decision {
433
toast: true,
434
sound: false
435
}
436
);
437
}
438
assert!(decide(&quiet_when_busy, &group(), Environment::default()).sound);
439
}
440
441
#[test]
442
fn incoming_calls_ring_the_chosen_tone_and_beep_during_a_call() {
443
let mut settings = Settings::default();
444
settings.sounds.ringtones.regular = Ringtone::Bop;
445
assert_eq!(ringtone_for(&settings, false, false), Some(Ringtone::Bop));
446
assert_eq!(ringtone_for(&settings, true, true), Some(Ringtone::Beep));
447
settings.sounds.sound_when_busy = false;
448
assert_eq!(ringtone_for(&settings, false, true), None);
449
assert_eq!(ringtone_for(&settings, false, false), Some(Ringtone::Bop));
450
settings.sounds.call_and_meeting_sound = false;
451
assert_eq!(ringtone_for(&settings, false, false), None);
452
assert!(!meeting_start_sound(&settings, false));
453
}
454
455
#[test]
456
fn meeting_start_sound_follows_the_call_and_busy_settings() {
457
let mut settings = Settings::default();
458
assert!(meeting_start_sound(&settings, false));
459
assert!(meeting_start_sound(&settings, true));
460
settings.sounds.sound_when_busy = false;
461
assert!(!meeting_start_sound(&settings, true));
399
462
}
400
463
401
464
#[test]
@@ -553,7 +616,10 @@ mod tests {
553
616
#[test]
554
617
fn sound_setting_off_keeps_toast() {
555
618
let settings = Settings {
556
sound: false,
619
sounds: SoundSettings {
620
notification_sound: false,
621
..Default::default()
622
},
557
623
..Default::default()
558
624
};
559
625
let decision = decide(&settings, &group(), Environment::default());
@@ -5,7 +5,8 @@ use calling::Progress;5
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};6
use store::{ChannelNotificationLevel, ChannelNotifications};6
use store::{ChannelNotificationLevel, ChannelNotifications};7
7
8
use super::ring_tone::Ringtone;8
use super::sound_settings::SoundSettings;9
use super::sounds::Ringtone;9
use crate::call::{CallKind, CallModel};10
use crate::call::{CallKind, CallModel};10
11
11
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);12
pub const SOUND_THROTTLE: Duration = Duration::from_secs(10);@@ -68,7 +69,6 @@ impl Corner {68
69
69
#[derive(Debug, Clone, PartialEq, Eq)]70
#[derive(Debug, Clone, PartialEq, Eq)]70
pub struct Settings {71
pub struct Settings {71
pub sound: bool,72
pub mentions_only: bool,72
pub mentions_only: bool,73
pub preview: bool,73
pub preview: bool,74
pub corner: Corner,74
pub corner: Corner,@@ -76,13 +76,12 @@ pub struct Settings {76
pub close_to_tray: bool,76
pub close_to_tray: bool,77
pub do_not_disturb: bool,77
pub do_not_disturb: bool,78
pub mute_in_calls: bool,78
pub mute_in_calls: bool,79
pub ringtone: Ringtone,79
pub sounds: SoundSettings,80
}80
}81
81
82
impl Default for Settings {82
impl Default for Settings {83
fn default() -> Self {83
fn default() -> Self {84
Settings {84
Settings {85
sound: true,86
mentions_only: false,85
mentions_only: false,87
preview: true,86
preview: true,88
corner: Corner::BottomRight,87
corner: Corner::BottomRight,@@ -90,7 +89,7 @@ impl Default for Settings {90
close_to_tray: true,89
close_to_tray: true,91
do_not_disturb: false,90
do_not_disturb: false,92
mute_in_calls: false,91
mute_in_calls: false,93
ringtone: Ringtone::Default,92
sounds: SoundSettings::default(),94
}93
}95
}94
}96
}95
}@@ -143,9 +142,16 @@ pub struct Environment {143
pub chat_in_foreground: bool,142
pub chat_in_foreground: bool,144
pub system_quiet: bool,143
pub system_quiet: bool,145
pub own_do_not_disturb: bool,144
pub own_do_not_disturb: bool,145
pub own_busy: bool,146
pub in_call: bool,146
pub in_call: bool,147
}147
}148
148
149
impl Environment {150
pub fn busy(&self) -> bool {151
self.in_call || self.own_busy152
}153
}154
149
pub fn in_call(server_in_call: bool, native_call: Option<&CallModel>) -> bool {155
pub fn in_call(server_in_call: bool, native_call: Option<&CallModel>) -> bool {150
server_in_call || native_call.is_some_and(CallModel::is_active)156
server_in_call || native_call.is_some_and(CallModel::is_active)151
}157
}@@ -214,10 +220,28 @@ pub fn decide(settings: &Settings, incoming: &Incoming, environment: Environment214
}220
}215
Decision {221
Decision {216
toast: true,222
toast: true,217
sound: settings.sound && !environment.in_call,223
sound: settings.sounds.notification_sound224
&& (settings.sounds.sound_when_busy || !environment.busy()),218
}225
}219
}226
}220
227
228
fn busy_allows_sound(settings: &Settings, busy: bool) -> bool {229
!busy || settings.sounds.sound_when_busy230
}231
232
pub fn ringtone_for(settings: &Settings, in_call: bool, busy: bool) -> Option<Ringtone> {233
let audible = settings.sounds.call_and_meeting_sound && busy_allows_sound(settings, busy);234
audible.then_some(if in_call {235
Ringtone::Beep236
} else {237
settings.sounds.ringtones.regular238
})239
}240
241
pub fn meeting_start_sound(settings: &Settings, busy: bool) -> bool {242
settings.sounds.call_and_meeting_sound && busy_allows_sound(settings, busy)243
}244
221
#[derive(Default)]245
#[derive(Default)]222
pub struct SoundThrottle {246
pub struct SoundThrottle {223
last_played: HashMap<String, Instant>,247
last_played: HashMap<String, Instant>,@@ -383,19 +407,58 @@ mod tests {383
}407
}384
408
385
#[test]409
#[test]386
fn call_keeps_toast_but_drops_sound() {410
fn calls_and_busy_keep_the_sound_unless_the_busy_setting_is_off() {387
let environment = Environment {411
let busy_environments = [388
in_call: true,412
Environment {413
in_call: true,414
..Default::default()415
},416
Environment {417
own_busy: true,418
..Default::default()419
},420
];421
let quiet_when_busy = Settings {422
sounds: SoundSettings {423
sound_when_busy: false,424
..Default::default()425
},389
..Default::default()426
..Default::default()390
};427
};391
let decision = decide(&Settings::default(), &group(), environment);428
for environment in busy_environments {392
assert_eq!(429
assert!(decide(&Settings::default(), &group(), environment).sound);393
decision,430
assert_eq!(394
Decision {431
decide(&quiet_when_busy, &group(), environment),395
toast: true,432
Decision {396
sound: false433
toast: true,397
}434
sound: false398
);435
}436
);437
}438
assert!(decide(&quiet_when_busy, &group(), Environment::default()).sound);439
}440
441
#[test]442
fn incoming_calls_ring_the_chosen_tone_and_beep_during_a_call() {443
let mut settings = Settings::default();444
settings.sounds.ringtones.regular = Ringtone::Bop;445
assert_eq!(ringtone_for(&settings, false, false), Some(Ringtone::Bop));446
assert_eq!(ringtone_for(&settings, true, true), Some(Ringtone::Beep));447
settings.sounds.sound_when_busy = false;448
assert_eq!(ringtone_for(&settings, false, true), None);449
assert_eq!(ringtone_for(&settings, false, false), Some(Ringtone::Bop));450
settings.sounds.call_and_meeting_sound = false;451
assert_eq!(ringtone_for(&settings, false, false), None);452
assert!(!meeting_start_sound(&settings, false));453
}454
455
#[test]456
fn meeting_start_sound_follows_the_call_and_busy_settings() {457
let mut settings = Settings::default();458
assert!(meeting_start_sound(&settings, false));459
assert!(meeting_start_sound(&settings, true));460
settings.sounds.sound_when_busy = false;461
assert!(!meeting_start_sound(&settings, true));399
}462
}400
463
401
#[test]464
#[test]@@ -553,7 +616,10 @@ mod tests {553
#[test]616
#[test]554
fn sound_setting_off_keeps_toast() {617
fn sound_setting_off_keeps_toast() {555
let settings = Settings {618
let settings = Settings {556
sound: false,619
sounds: SoundSettings {620
notification_sound: false,621
..Default::default()622
},557
..Default::default()623
..Default::default()558
};624
};559
let decision = decide(&settings, &group(), Environment::default());625
let decision = decide(&settings, &group(), Environment::default());@@ -1,9 +1,10 @@
1
1
use store::Store;
2
2
3
use super::ring_tone::Ringtone;
3
use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};
4
4
use super::rules::{Corner, Settings};
5
5
6
6
const META_KEY: &str = "notifications.settings";
7
const RINGTONE_PREFIX: &str = "ringtone.";
7
8
8
9
pub fn load(store: &Store) -> Settings {
9
10
store
@@ -19,18 +20,30 @@ pub fn save(store: &Store, settings: &Settings) {
19
20
}
20
21
21
22
fn serialize(settings: &Settings) -> String {
23
let sounds = &settings.sounds;
24
let ringtones = RingtoneCallType::ALL.map(|call_type| {
25
(
26
format!("{RINGTONE_PREFIX}{}", call_type.name()),
27
sounds.ringtones.get(call_type).name().to_owned(),
28
)
29
});
22
30
[
23
("sound", settings.sound.to_string()),
24
("mentions_only", settings.mentions_only.to_string()),
25
("preview", settings.preview.to_string()),
26
("corner", settings.corner.key().to_owned()),
27
("taskbar_flash", settings.flash.to_string()),
28
("close_to_tray", settings.close_to_tray.to_string()),
29
("do_not_disturb", settings.do_not_disturb.to_string()),
30
("mute_in_calls", settings.mute_in_calls.to_string()),
31
("ringtone", settings.ringtone.key().to_owned()),
31
("sound".to_owned(), sounds.notification_sound.to_string()),
32
("sound_type".to_owned(), sounds.notification_sound_type.name().to_owned()),
33
("urgent_sound".to_owned(), sounds.urgent_sound.to_string()),
34
("urgent_sound_type".to_owned(), sounds.urgent_sound_type.name().to_owned()),
35
("call_sound".to_owned(), sounds.call_and_meeting_sound.to_string()),
36
("sound_when_busy".to_owned(), sounds.sound_when_busy.to_string()),
37
("mentions_only".to_owned(), settings.mentions_only.to_string()),
38
("preview".to_owned(), settings.preview.to_string()),
39
("corner".to_owned(), settings.corner.key().to_owned()),
40
("taskbar_flash".to_owned(), settings.flash.to_string()),
41
("close_to_tray".to_owned(), settings.close_to_tray.to_string()),
42
("do_not_disturb".to_owned(), settings.do_not_disturb.to_string()),
43
("mute_in_calls".to_owned(), settings.mute_in_calls.to_string()),
32
44
]
33
.iter()
45
.into_iter()
46
.chain(ringtones)
34
47
.map(|(key, value)| format!("{key}={value}"))
35
48
.collect::<Vec<_>>()
36
49
.join("\n")
@@ -43,8 +56,14 @@ fn parse(text: &str) -> Settings {
43
56
continue;
44
57
};
45
58
let flag = value == "true";
59
let sounds = &mut settings.sounds;
46
60
match key {
47
"sound" => settings.sound = flag,
61
"sound" => sounds.notification_sound = flag,
62
"sound_type" => set_alert_sound(&mut sounds.notification_sound_type, value),
63
"urgent_sound" => sounds.urgent_sound = flag,
64
"urgent_sound_type" => set_alert_sound(&mut sounds.urgent_sound_type, value),
65
"call_sound" => sounds.call_and_meeting_sound = flag,
66
"sound_when_busy" => sounds.sound_when_busy = flag,
48
67
"mentions_only" => settings.mentions_only = flag,
49
68
"preview" => settings.preview = flag,
50
69
"corner" => settings.corner = Corner::from_key(value).unwrap_or_default(),
@@ -52,21 +71,35 @@ fn parse(text: &str) -> Settings {
52
71
"close_to_tray" => settings.close_to_tray = flag,
53
72
"do_not_disturb" => settings.do_not_disturb = flag,
54
73
"mute_in_calls" => settings.mute_in_calls = flag,
55
"ringtone" => settings.ringtone = Ringtone::from_key(value).unwrap_or_default(),
56
_ => {}
74
_ => set_ringtone(&mut sounds.ringtones, key, value),
57
75
}
58
76
}
59
77
settings
60
78
}
61
79
80
fn set_alert_sound(target: &mut AlertSound, value: &str) {
81
if let Some(sound) = AlertSound::from_name(value) {
82
*target = sound;
83
}
84
}
85
86
fn set_ringtone(ringtones: &mut RingtoneAssignments, key: &str, value: &str) {
87
let call_type = key
88
.strip_prefix(RINGTONE_PREFIX)
89
.and_then(RingtoneCallType::from_name);
90
if let (Some(call_type), Some(ringtone)) = (call_type, Ringtone::from_name(value)) {
91
ringtones.set(call_type, ringtone);
92
}
93
}
94
62
95
#[cfg(test)]
63
96
mod tests {
97
use super::super::sound_settings::SoundSettings;
64
98
use super::*;
65
99
66
100
#[test]
67
101
fn round_trips_every_field() {
68
102
let settings = Settings {
69
sound: false,
70
103
mentions_only: true,
71
104
preview: false,
72
105
corner: Corner::TopLeft,
@@ -74,7 +107,19 @@ mod tests {
74
107
close_to_tray: false,
75
108
do_not_disturb: true,
76
109
mute_in_calls: true,
77
ringtone: Ringtone::Chime,
110
sounds: SoundSettings {
111
notification_sound: false,
112
notification_sound_type: AlertSound::Ping,
113
urgent_sound: false,
114
urgent_sound_type: AlertSound::Alarm,
115
call_and_meeting_sound: false,
116
sound_when_busy: false,
117
ringtones: RingtoneAssignments {
118
regular: Ringtone::Bop,
119
delegate: Ringtone::WishGranted,
120
..Default::default()
121
},
122
},
78
123
};
79
124
assert_eq!(parse(&serialize(&settings)), settings);
80
125
}
@@ -85,6 +130,11 @@ mod tests {
85
130
assert!(!parse("taskbar_flash=false").flash);
86
131
}
87
132
133
#[test]
134
fn the_old_synthesized_ringtone_key_is_ignored() {
135
assert_eq!(parse("ringtone=chime"), Settings::default());
136
}
137
88
138
#[test]
89
139
fn empty_or_garbage_gives_defaults() {
90
140
assert_eq!(parse(""), Settings::default());
@@ -95,10 +145,8 @@ mod tests {
95
145
fn persists_in_store() {
96
146
let store = Store::open_in_memory().unwrap();
97
147
assert_eq!(load(&store), Settings::default());
98
let changed = Settings {
99
sound: false,
100
..Default::default()
101
};
148
let mut changed = Settings::default();
149
changed.sounds.notification_sound = false;
102
150
save(&store, &changed);
103
151
assert_eq!(load(&store), changed);
104
152
}
@@ -1,9 +1,10 @@1
use store::Store;1
use store::Store;2
2
3
use super::ring_tone::Ringtone;3
use super::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};4
use super::rules::{Corner, Settings};4
use super::rules::{Corner, Settings};5
5
6
const META_KEY: &str = "notifications.settings";6
const META_KEY: &str = "notifications.settings";7
const RINGTONE_PREFIX: &str = "ringtone.";7
8
8
pub fn load(store: &Store) -> Settings {9
pub fn load(store: &Store) -> Settings {9
store10
store@@ -19,18 +20,30 @@ pub fn save(store: &Store, settings: &Settings) {19
}20
}20
21
21
fn serialize(settings: &Settings) -> String {22
fn serialize(settings: &Settings) -> String {23
let sounds = &settings.sounds;24
let ringtones = RingtoneCallType::ALL.map(|call_type| {25
(26
format!("{RINGTONE_PREFIX}{}", call_type.name()),27
sounds.ringtones.get(call_type).name().to_owned(),28
)29
});22
[30
[23
("sound", settings.sound.to_string()),31
("sound".to_owned(), sounds.notification_sound.to_string()),24
("mentions_only", settings.mentions_only.to_string()),32
("sound_type".to_owned(), sounds.notification_sound_type.name().to_owned()),25
("preview", settings.preview.to_string()),33
("urgent_sound".to_owned(), sounds.urgent_sound.to_string()),26
("corner", settings.corner.key().to_owned()),34
("urgent_sound_type".to_owned(), sounds.urgent_sound_type.name().to_owned()),27
("taskbar_flash", settings.flash.to_string()),35
("call_sound".to_owned(), sounds.call_and_meeting_sound.to_string()),28
("close_to_tray", settings.close_to_tray.to_string()),36
("sound_when_busy".to_owned(), sounds.sound_when_busy.to_string()),29
("do_not_disturb", settings.do_not_disturb.to_string()),37
("mentions_only".to_owned(), settings.mentions_only.to_string()),30
("mute_in_calls", settings.mute_in_calls.to_string()),38
("preview".to_owned(), settings.preview.to_string()),31
("ringtone", settings.ringtone.key().to_owned()),39
("corner".to_owned(), settings.corner.key().to_owned()),40
("taskbar_flash".to_owned(), settings.flash.to_string()),41
("close_to_tray".to_owned(), settings.close_to_tray.to_string()),42
("do_not_disturb".to_owned(), settings.do_not_disturb.to_string()),43
("mute_in_calls".to_owned(), settings.mute_in_calls.to_string()),32
]44
]33
.iter()45
.into_iter()46
.chain(ringtones)34
.map(|(key, value)| format!("{key}={value}"))47
.map(|(key, value)| format!("{key}={value}"))35
.collect::<Vec<_>>()48
.collect::<Vec<_>>()36
.join("\n")49
.join("\n")@@ -43,8 +56,14 @@ fn parse(text: &str) -> Settings {43
continue;56
continue;44
};57
};45
let flag = value == "true";58
let flag = value == "true";59
let sounds = &mut settings.sounds;46
match key {60
match key {47
"sound" => settings.sound = flag,61
"sound" => sounds.notification_sound = flag,62
"sound_type" => set_alert_sound(&mut sounds.notification_sound_type, value),63
"urgent_sound" => sounds.urgent_sound = flag,64
"urgent_sound_type" => set_alert_sound(&mut sounds.urgent_sound_type, value),65
"call_sound" => sounds.call_and_meeting_sound = flag,66
"sound_when_busy" => sounds.sound_when_busy = flag,48
"mentions_only" => settings.mentions_only = flag,67
"mentions_only" => settings.mentions_only = flag,49
"preview" => settings.preview = flag,68
"preview" => settings.preview = flag,50
"corner" => settings.corner = Corner::from_key(value).unwrap_or_default(),69
"corner" => settings.corner = Corner::from_key(value).unwrap_or_default(),@@ -52,21 +71,35 @@ fn parse(text: &str) -> Settings {52
"close_to_tray" => settings.close_to_tray = flag,71
"close_to_tray" => settings.close_to_tray = flag,53
"do_not_disturb" => settings.do_not_disturb = flag,72
"do_not_disturb" => settings.do_not_disturb = flag,54
"mute_in_calls" => settings.mute_in_calls = flag,73
"mute_in_calls" => settings.mute_in_calls = flag,55
"ringtone" => settings.ringtone = Ringtone::from_key(value).unwrap_or_default(),74
_ => set_ringtone(&mut sounds.ringtones, key, value),56
_ => {}57
}75
}58
}76
}59
settings77
settings60
}78
}61
79
80
fn set_alert_sound(target: &mut AlertSound, value: &str) {81
if let Some(sound) = AlertSound::from_name(value) {82
*target = sound;83
}84
}85
86
fn set_ringtone(ringtones: &mut RingtoneAssignments, key: &str, value: &str) {87
let call_type = key88
.strip_prefix(RINGTONE_PREFIX)89
.and_then(RingtoneCallType::from_name);90
if let (Some(call_type), Some(ringtone)) = (call_type, Ringtone::from_name(value)) {91
ringtones.set(call_type, ringtone);92
}93
}94
62
#[cfg(test)]95
#[cfg(test)]63
mod tests {96
mod tests {97
use super::super::sound_settings::SoundSettings;64
use super::*;98
use super::*;65
99
66
#[test]100
#[test]67
fn round_trips_every_field() {101
fn round_trips_every_field() {68
let settings = Settings {102
let settings = Settings {69
sound: false,70
mentions_only: true,103
mentions_only: true,71
preview: false,104
preview: false,72
corner: Corner::TopLeft,105
corner: Corner::TopLeft,@@ -74,7 +107,19 @@ mod tests {74
close_to_tray: false,107
close_to_tray: false,75
do_not_disturb: true,108
do_not_disturb: true,76
mute_in_calls: true,109
mute_in_calls: true,77
ringtone: Ringtone::Chime,110
sounds: SoundSettings {111
notification_sound: false,112
notification_sound_type: AlertSound::Ping,113
urgent_sound: false,114
urgent_sound_type: AlertSound::Alarm,115
call_and_meeting_sound: false,116
sound_when_busy: false,117
ringtones: RingtoneAssignments {118
regular: Ringtone::Bop,119
delegate: Ringtone::WishGranted,120
..Default::default()121
},122
},78
};123
};79
assert_eq!(parse(&serialize(&settings)), settings);124
assert_eq!(parse(&serialize(&settings)), settings);80
}125
}@@ -85,6 +130,11 @@ mod tests {85
assert!(!parse("taskbar_flash=false").flash);130
assert!(!parse("taskbar_flash=false").flash);86
}131
}87
132
133
#[test]134
fn the_old_synthesized_ringtone_key_is_ignored() {135
assert_eq!(parse("ringtone=chime"), Settings::default());136
}137
88
#[test]138
#[test]89
fn empty_or_garbage_gives_defaults() {139
fn empty_or_garbage_gives_defaults() {90
assert_eq!(parse(""), Settings::default());140
assert_eq!(parse(""), Settings::default());@@ -95,10 +145,8 @@ mod tests {95
fn persists_in_store() {145
fn persists_in_store() {96
let store = Store::open_in_memory().unwrap();146
let store = Store::open_in_memory().unwrap();97
assert_eq!(load(&store), Settings::default());147
assert_eq!(load(&store), Settings::default());98
let changed = Settings {148
let mut changed = Settings::default();99
sound: false,149
changed.sounds.notification_sound = false;100
..Default::default()101
};102
save(&store, &changed);150
save(&store, &changed);103
assert_eq!(load(&store), changed);151
assert_eq!(load(&store), changed);104
}152
}@@ -0,0 +1,86 @@
1
use chatsvc::sound_settings::SoundSettings;
2
use gpui_kit::Context;
3
4
use crate::app_state::{AppEvent, AppState};
5
use crate::runtime;
6
7
const ORGID_PREFIX: &str = "8:orgid:";
8
9
pub fn user_mri(user_id: &str) -> String {
10
if user_id.starts_with("8:") {
11
user_id.to_owned()
12
} else {
13
format!("{ORGID_PREFIX}{user_id}")
14
}
15
}
16
17
impl AppState {
18
pub fn refresh_sound_settings(&mut self, cx: &mut Context<Self>) {
19
let Some(engine) = self.engine.clone() else {
20
return;
21
};
22
let read = runtime::spawn(async move { engine.sound_settings().await });
23
cx.spawn(async move |this, cx| {
24
let settings = match read.await {
25
Ok(Ok(settings)) => settings,
26
Ok(Err(error)) => {
27
log::warn!("sound settings not read: {error}");
28
return;
29
}
30
Err(_) => return,
31
};
32
this.update(cx, |state, cx| state.apply_account_sounds(settings, cx))
33
.ok();
34
})
35
.detach();
36
}
37
38
pub fn save_sound_settings(
39
&mut self,
40
previous: SoundSettings,
41
updated: SoundSettings,
42
cx: &mut Context<Self>,
43
) {
44
let Some(engine_or_demo) = self.chat_action_engine(cx) else {
45
self.apply_account_sounds(previous, cx);
46
return;
47
};
48
let Some(engine) = engine_or_demo else {
49
self.account_sounds = Some(updated);
50
return;
51
};
52
let Some(user_mri) = self.directory.me.as_ref().map(|me| user_mri(&me.user_id)) else {
53
self.apply_account_sounds(previous, cx);
54
return;
55
};
56
self.account_sounds = Some(updated.clone());
57
let restore = previous.clone();
58
self.run_chat_action(
59
"Sound setting",
60
async move {
61
engine
62
.save_sound_settings(&user_mri, &previous, &updated)
63
.await
64
},
65
move |state, cx| state.apply_account_sounds(restore, cx),
66
|_, _| {},
67
cx,
68
);
69
}
70
71
fn apply_account_sounds(&mut self, settings: SoundSettings, cx: &mut Context<Self>) {
72
self.account_sounds = Some(settings);
73
cx.emit(AppEvent::SoundSettings);
74
}
75
}
76
77
#[cfg(test)]
78
mod tests {
79
use super::*;
80
81
#[test]
82
fn the_ringtone_endpoint_gets_a_skype_mri() {
83
assert_eq!(user_mri("f74e540a"), "8:orgid:f74e540a");
84
assert_eq!(user_mri("8:orgid:f74e540a"), "8:orgid:f74e540a");
85
}
86
}
@@ -0,0 +1,86 @@1
use chatsvc::sound_settings::SoundSettings;2
use gpui_kit::Context;3
4
use crate::app_state::{AppEvent, AppState};5
use crate::runtime;6
7
const ORGID_PREFIX: &str = "8:orgid:";8
9
pub fn user_mri(user_id: &str) -> String {10
if user_id.starts_with("8:") {11
user_id.to_owned()12
} else {13
format!("{ORGID_PREFIX}{user_id}")14
}15
}16
17
impl AppState {18
pub fn refresh_sound_settings(&mut self, cx: &mut Context<Self>) {19
let Some(engine) = self.engine.clone() else {20
return;21
};22
let read = runtime::spawn(async move { engine.sound_settings().await });23
cx.spawn(async move |this, cx| {24
let settings = match read.await {25
Ok(Ok(settings)) => settings,26
Ok(Err(error)) => {27
log::warn!("sound settings not read: {error}");28
return;29
}30
Err(_) => return,31
};32
this.update(cx, |state, cx| state.apply_account_sounds(settings, cx))33
.ok();34
})35
.detach();36
}37
38
pub fn save_sound_settings(39
&mut self,40
previous: SoundSettings,41
updated: SoundSettings,42
cx: &mut Context<Self>,43
) {44
let Some(engine_or_demo) = self.chat_action_engine(cx) else {45
self.apply_account_sounds(previous, cx);46
return;47
};48
let Some(engine) = engine_or_demo else {49
self.account_sounds = Some(updated);50
return;51
};52
let Some(user_mri) = self.directory.me.as_ref().map(|me| user_mri(&me.user_id)) else {53
self.apply_account_sounds(previous, cx);54
return;55
};56
self.account_sounds = Some(updated.clone());57
let restore = previous.clone();58
self.run_chat_action(59
"Sound setting",60
async move {61
engine62
.save_sound_settings(&user_mri, &previous, &updated)63
.await64
},65
move |state, cx| state.apply_account_sounds(restore, cx),66
|_, _| {},67
cx,68
);69
}70
71
fn apply_account_sounds(&mut self, settings: SoundSettings, cx: &mut Context<Self>) {72
self.account_sounds = Some(settings);73
cx.emit(AppEvent::SoundSettings);74
}75
}76
77
#[cfg(test)]78
mod tests {79
use super::*;80
81
#[test]82
fn the_ringtone_endpoint_gets_a_skype_mri() {83
assert_eq!(user_mri("f74e540a"), "8:orgid:f74e540a");84
assert_eq!(user_mri("8:orgid:f74e540a"), "8:orgid:f74e540a");85
}86
}@@ -13,10 +13,11 @@ use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
13
13
use super::ring_view::RingView;
14
14
use super::rules::{
15
15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
16
should_flash, should_ringback,
16
meeting_start_sound, ringtone_for, should_flash, should_ringback,
17
17
};
18
18
use super::settings;
19
use super::sound_cache;
19
use super::sound_cache::{self, SoundHandle};
20
use super::sounds::{CallTone, Ringtone};
20
21
use super::settings_view::{Section, SettingsView};
21
22
use super::stack::{
22
23
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
@@ -26,7 +27,6 @@ use super::toast::{PillView, ToastView};
26
27
use crate::agents::{AgentRun, AgentRunsEvent, RunState};
27
28
use crate::app_state::{AppEvent, AppState, selection_for};
28
29
use crate::call::DemoScene;
29
use crate::call::end_screen::EndTone;
30
30
use crate::data::{self, Directory, PresenceKind};
31
31
use crate::runtime;
32
32
use crate::single_instance;
@@ -75,8 +75,10 @@ pub struct NotificationCenter {
75
75
opening: HashSet<u64>,
76
76
call_windows: HashMap<CallToast, OpenWindow>,
77
77
call_opening: HashSet<CallToast>,
78
ring_tone: Option<platform::RingTone>,
79
ringback: Option<platform::RingTone>,
78
ring_tone: Option<SoundHandle>,
79
ringback: Option<SoundHandle>,
80
reconnecting: Option<SoundHandle>,
81
preview: Option<SoundHandle>,
80
82
demo_mode: bool,
81
83
pill: Option<OpenWindow>,
82
84
pill_opening: bool,
@@ -97,7 +99,7 @@ impl NotificationCenter {
97
99
let tray = if app.read(cx).mode.demo {
98
100
None
99
101
} else {
100
Tray::new(settings.sound, settings.do_not_disturb)
102
Tray::new(settings.sounds.notification_sound, settings.do_not_disturb)
101
103
};
102
104
let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
103
105
this.on_app_event(event, cx);
@@ -124,6 +126,8 @@ impl NotificationCenter {
124
126
call_opening: HashSet::new(),
125
127
ring_tone: None,
126
128
ringback: None,
129
reconnecting: None,
130
preview: None,
127
131
demo_mode: app.read(cx).mode.demo,
128
132
pill: None,
129
133
pill_opening: false,
@@ -148,8 +152,7 @@ impl NotificationCenter {
148
152
})
149
153
.detach();
150
154
if !center.demo_mode {
151
let end_tones = EndTone::ALL.map(EndTone::file_name);
152
sound_cache::prefetch(&end_tones, cx);
155
center.prefetch_sounds(cx);
153
156
}
154
157
if center.app.read(cx).mode.demo {
155
158
if demo_scene().is_none() {
@@ -240,12 +243,57 @@ impl NotificationCenter {
240
243
}
241
244
242
245
pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {
246
let previous = self.settings.sounds.clone();
243
247
change(&mut self.settings);
244
248
settings::save(&self.app.read(cx).store, &self.settings);
245
249
self.sync_tray();
250
if self.settings.sounds != previous {
251
let updated = self.settings.sounds.clone();
252
self.app
253
.update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));
254
self.prefetch_sounds(cx);
255
}
256
cx.notify();
257
}
258
259
fn on_account_sounds(&mut self, cx: &mut Context<Self>) {
260
let Some(account) = self.app.read(cx).account_sounds.clone() else {
261
return;
262
};
263
if account == self.settings.sounds {
264
return;
265
}
266
self.settings.sounds = account;
267
settings::save(&self.app.read(cx).store, &self.settings);
268
self.sync_tray();
269
if !self.demo_mode {
270
self.prefetch_sounds(cx);
271
}
246
272
cx.notify();
247
273
}
248
274
275
fn prefetch_sounds(&self, cx: &App) {
276
let sounds = &self.settings.sounds;
277
let chosen = [
278
sounds.notification_sound_type.file_name(),
279
sounds.urgent_sound_type.file_name(),
280
sounds.ringtones.regular.file_name(),
281
Ringtone::Beep.file_name(),
282
];
283
let call_tones = CallTone::ALL.map(CallTone::file_name);
284
sound_cache::prefetch(&chosen, cx);
285
sound_cache::prefetch(&call_tones, cx);
286
}
287
288
pub fn preview_sound(&mut self, file_name: &'static str, cx: &mut Context<Self>) {
289
self.preview = Some(sound_cache::start(file_name, false, cx));
290
}
291
292
fn play_notification_sound(&self, cx: &App) {
293
let file_name = self.settings.sounds.notification_sound_type.file_name();
294
sound_cache::play_or(file_name, platform::play_sound, cx);
295
}
296
249
297
fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {
250
298
match event {
251
299
AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),
@@ -254,8 +302,9 @@ impl NotificationCenter {
254
302
AppEvent::Ring => self.on_rings_changed(cx),
255
303
AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
256
304
AppEvent::MeetingChime => self.on_meeting_chime(cx),
257
AppEvent::CallEndTone(tone) => self.on_call_end_tone(*tone, cx),
258
AppEvent::Call => self.sync_ringback(cx),
305
AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),
306
AppEvent::Call => self.sync_call_sounds(cx),
307
AppEvent::SoundSettings => self.on_account_sounds(cx),
259
308
_ => {}
260
309
}
261
310
}
@@ -297,6 +346,7 @@ impl NotificationCenter {
297
346
.as_ref()
298
347
.is_some_and(|selection| selection.conversation_id() == conversation_id);
299
348
let own_do_not_disturb = own_do_not_disturb(state);
349
let own_busy = own_presence(state) == PresenceKind::Busy;
300
350
let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
301
351
(Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
302
352
_ => false,
@@ -306,6 +356,7 @@ impl NotificationCenter {
306
356
chat_in_foreground: selected && self.main_window_active(cx),
307
357
system_quiet: platform::system_quiet(),
308
358
own_do_not_disturb,
359
own_busy,
309
360
in_call,
310
361
}
311
362
}
@@ -356,7 +407,7 @@ impl NotificationCenter {
356
407
}
357
408
let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);
358
409
if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {
359
platform::play_sound();
410
self.play_notification_sound(cx);
360
411
}
361
412
if let Some(user_id) = incoming.sender_id.clone() {
362
413
self.app
@@ -401,8 +452,8 @@ impl NotificationCenter {
401
452
model.time = chrono::Local::now().format("%H:%M").to_string();
402
453
}
403
454
let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;
404
if self.settings.sound && !quiet {
405
platform::play_sound();
455
if self.settings.sounds.notification_sound && !quiet {
456
self.play_notification_sound(cx);
406
457
}
407
458
self.sync_windows(cx);
408
459
}
@@ -575,12 +626,14 @@ impl NotificationCenter {
575
626
}
576
627
577
628
fn on_meeting_chime(&mut self, cx: &mut Context<Self>) {
578
if self.settings.sound && !self.reminders_quiet(cx) && !self.demo_mode {
579
platform::play_meeting_chime();
629
let busy = self.environment("", cx).busy();
630
if meeting_start_sound(&self.settings, busy) && !self.reminders_quiet(cx) && !self.demo_mode
631
{
632
sound_cache::play(CallTone::MeetingReminder.file_name(), cx);
580
633
}
581
634
}
582
635
583
fn on_call_end_tone(&mut self, tone: EndTone, cx: &mut Context<Self>) {
636
fn on_call_tone(&mut self, tone: CallTone, cx: &mut Context<Self>) {
584
637
if !self.demo_mode {
585
638
sound_cache::play(tone.file_name(), cx);
586
639
}
@@ -607,27 +660,32 @@ impl NotificationCenter {
607
660
platform::flash(native);
608
661
}
609
662
self.sync_windows(cx);
610
self.sync_ring_tone(ringing);
663
self.sync_ring_tone(ringing, cx);
611
664
cx.notify();
612
665
}
613
666
614
fn sync_ring_tone(&mut self, ringing: bool) {
615
let audible = ringing && self.settings.sound && !self.demo_mode;
616
match (audible, self.ring_tone.is_some()) {
617
(true, false) => self.ring_tone = platform::start_ring(self.settings.ringtone),
618
(false, true) => self.ring_tone = None,
619
_ => {}
667
fn sync_ring_tone(&mut self, ringing: bool, cx: &mut Context<Self>) {
668
if !ringing || self.demo_mode {
669
self.ring_tone = None;
670
return;
671
}
672
if self.ring_tone.is_some() {
673
return;
674
}
675
let environment = self.environment("", cx);
676
let native_call = self.app.read(cx).call.is_some();
677
if let Some(ringtone) = ringtone_for(&self.settings, native_call, environment.busy()) {
678
self.ring_tone = Some(sound_cache::start(ringtone.file_name(), true, cx));
620
679
}
621
680
}
622
681
623
fn sync_ringback(&mut self, cx: &Context<Self>) {
624
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model))
625
&& !self.demo_mode;
626
match (audible, self.ringback.is_some()) {
627
(true, false) => self.ringback = platform::start_ringback(),
628
(false, true) => self.ringback = None,
629
_ => {}
630
}
682
fn sync_call_sounds(&mut self, cx: &Context<Self>) {
683
let model = self.app.read(cx).call.as_ref().map(|call| &call.model);
684
let ringback = should_ringback(model) && !self.demo_mode;
685
let reconnecting =
686
model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;
687
sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);
688
sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);
631
689
}
632
690
633
691
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {
@@ -801,9 +859,9 @@ impl NotificationCenter {
801
859
match command {
802
860
TrayCommand::Toggle => self.toggle_main_window(cx),
803
861
TrayCommand::Open => self.raise_main_window(cx),
804
TrayCommand::ToggleSound => {
805
self.update_settings(cx, |settings| settings.sound = !settings.sound)
806
}
862
TrayCommand::ToggleSound => self.update_settings(cx, |settings| {
863
settings.sounds.notification_sound = !settings.sounds.notification_sound
864
}),
807
865
TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {
808
866
settings.do_not_disturb = !settings.do_not_disturb
809
867
}),
@@ -835,7 +893,7 @@ impl NotificationCenter {
835
893
fn sync_tray(&self) {
836
894
if let Some(tray) = &self.tray {
837
895
tray.sync(
838
self.settings.sound,
896
self.settings.sounds.notification_sound,
839
897
self.settings.do_not_disturb,
840
898
!self.unread_mentions.is_empty(),
841
899
);
@@ -1075,7 +1133,7 @@ impl NotificationCenter {
1075
1133
};
1076
1134
let decision = Decision {
1077
1135
toast: true,
1078
sound: self.settings.sound,
1136
sound: self.settings.sounds.notification_sound,
1079
1137
};
1080
1138
self.throttle = SoundThrottle::default();
1081
1139
self.present(&incoming, decision, cx);
@@ -1127,10 +1185,26 @@ fn open_popup<V: Into<AnyView>>(
1127
1185
});
1128
1186
}
1129
1187
1188
fn own_presence(state: &AppState) -> PresenceKind {
1189
state
1190
.directory
1191
.me
1192
.as_ref()
1193
.map_or(PresenceKind::Unknown, |me| {
1194
state.directory.presence_of(&me.user_id).kind()
1195
})
1196
}
1197
1130
1198
fn own_do_not_disturb(state: &AppState) -> bool {
1131
state.directory.me.as_ref().is_some_and(|me| {
1132
state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
1133
})
1199
own_presence(state) == PresenceKind::DoNotDisturb
1200
}
1201
1202
fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {
1203
match (audible, handle.is_some()) {
1204
(true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),
1205
(false, true) => *handle = None,
1206
_ => {}
1207
}
1134
1208
}
1135
1209
1136
1210
fn demo_scene() -> Option<DemoScene> {
@@ -13,10 +13,11 @@ use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};13
use super::ring_view::RingView;13
use super::ring_view::RingView;14
use super::rules::{14
use super::rules::{15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,15
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,16
should_flash, should_ringback,16
meeting_start_sound, ringtone_for, should_flash, should_ringback,17
};17
};18
use super::settings;18
use super::settings;19
use super::sound_cache;19
use super::sound_cache::{self, SoundHandle};20
use super::sounds::{CallTone, Ringtone};20
use super::settings_view::{Section, SettingsView};21
use super::settings_view::{Section, SettingsView};21
use super::stack::{22
use super::stack::{22
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,23
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,@@ -26,7 +27,6 @@ use super::toast::{PillView, ToastView};26
use crate::agents::{AgentRun, AgentRunsEvent, RunState};27
use crate::agents::{AgentRun, AgentRunsEvent, RunState};27
use crate::app_state::{AppEvent, AppState, selection_for};28
use crate::app_state::{AppEvent, AppState, selection_for};28
use crate::call::DemoScene;29
use crate::call::DemoScene;29
use crate::call::end_screen::EndTone;30
use crate::data::{self, Directory, PresenceKind};30
use crate::data::{self, Directory, PresenceKind};31
use crate::runtime;31
use crate::runtime;32
use crate::single_instance;32
use crate::single_instance;@@ -75,8 +75,10 @@ pub struct NotificationCenter {75
opening: HashSet<u64>,75
opening: HashSet<u64>,76
call_windows: HashMap<CallToast, OpenWindow>,76
call_windows: HashMap<CallToast, OpenWindow>,77
call_opening: HashSet<CallToast>,77
call_opening: HashSet<CallToast>,78
ring_tone: Option<platform::RingTone>,78
ring_tone: Option<SoundHandle>,79
ringback: Option<platform::RingTone>,79
ringback: Option<SoundHandle>,80
reconnecting: Option<SoundHandle>,81
preview: Option<SoundHandle>,80
demo_mode: bool,82
demo_mode: bool,81
pill: Option<OpenWindow>,83
pill: Option<OpenWindow>,82
pill_opening: bool,84
pill_opening: bool,@@ -97,7 +99,7 @@ impl NotificationCenter {97
let tray = if app.read(cx).mode.demo {99
let tray = if app.read(cx).mode.demo {98
None100
None99
} else {101
} else {100
Tray::new(settings.sound, settings.do_not_disturb)102
Tray::new(settings.sounds.notification_sound, settings.do_not_disturb)101
};103
};102
let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {104
let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {103
this.on_app_event(event, cx);105
this.on_app_event(event, cx);@@ -124,6 +126,8 @@ impl NotificationCenter {124
call_opening: HashSet::new(),126
call_opening: HashSet::new(),125
ring_tone: None,127
ring_tone: None,126
ringback: None,128
ringback: None,129
reconnecting: None,130
preview: None,127
demo_mode: app.read(cx).mode.demo,131
demo_mode: app.read(cx).mode.demo,128
pill: None,132
pill: None,129
pill_opening: false,133
pill_opening: false,@@ -148,8 +152,7 @@ impl NotificationCenter {148
})152
})149
.detach();153
.detach();150
if !center.demo_mode {154
if !center.demo_mode {151
let end_tones = EndTone::ALL.map(EndTone::file_name);155
center.prefetch_sounds(cx);152
sound_cache::prefetch(&end_tones, cx);153
}156
}154
if center.app.read(cx).mode.demo {157
if center.app.read(cx).mode.demo {155
if demo_scene().is_none() {158
if demo_scene().is_none() {@@ -240,12 +243,57 @@ impl NotificationCenter {240
}243
}241
244
242
pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {245
pub fn update_settings(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut Settings)) {246
let previous = self.settings.sounds.clone();243
change(&mut self.settings);247
change(&mut self.settings);244
settings::save(&self.app.read(cx).store, &self.settings);248
settings::save(&self.app.read(cx).store, &self.settings);245
self.sync_tray();249
self.sync_tray();250
if self.settings.sounds != previous {251
let updated = self.settings.sounds.clone();252
self.app253
.update(cx, |state, cx| state.save_sound_settings(previous, updated, cx));254
self.prefetch_sounds(cx);255
}256
cx.notify();257
}258
259
fn on_account_sounds(&mut self, cx: &mut Context<Self>) {260
let Some(account) = self.app.read(cx).account_sounds.clone() else {261
return;262
};263
if account == self.settings.sounds {264
return;265
}266
self.settings.sounds = account;267
settings::save(&self.app.read(cx).store, &self.settings);268
self.sync_tray();269
if !self.demo_mode {270
self.prefetch_sounds(cx);271
}246
cx.notify();272
cx.notify();247
}273
}248
274
275
fn prefetch_sounds(&self, cx: &App) {276
let sounds = &self.settings.sounds;277
let chosen = [278
sounds.notification_sound_type.file_name(),279
sounds.urgent_sound_type.file_name(),280
sounds.ringtones.regular.file_name(),281
Ringtone::Beep.file_name(),282
];283
let call_tones = CallTone::ALL.map(CallTone::file_name);284
sound_cache::prefetch(&chosen, cx);285
sound_cache::prefetch(&call_tones, cx);286
}287
288
pub fn preview_sound(&mut self, file_name: &'static str, cx: &mut Context<Self>) {289
self.preview = Some(sound_cache::start(file_name, false, cx));290
}291
292
fn play_notification_sound(&self, cx: &App) {293
let file_name = self.settings.sounds.notification_sound_type.file_name();294
sound_cache::play_or(file_name, platform::play_sound, cx);295
}296
249
fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {297
fn on_app_event(&mut self, event: &AppEvent, cx: &mut Context<Self>) {250
match event {298
match event {251
AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),299
AppEvent::Messages(conversation_id) => self.on_messages(conversation_id, cx),@@ -254,8 +302,9 @@ impl NotificationCenter {254
AppEvent::Ring => self.on_rings_changed(cx),302
AppEvent::Ring => self.on_rings_changed(cx),255
AppEvent::MeetingReminder => self.on_meeting_reminder(cx),303
AppEvent::MeetingReminder => self.on_meeting_reminder(cx),256
AppEvent::MeetingChime => self.on_meeting_chime(cx),304
AppEvent::MeetingChime => self.on_meeting_chime(cx),257
AppEvent::CallEndTone(tone) => self.on_call_end_tone(*tone, cx),305
AppEvent::CallTone(tone) => self.on_call_tone(*tone, cx),258
AppEvent::Call => self.sync_ringback(cx),306
AppEvent::Call => self.sync_call_sounds(cx),307
AppEvent::SoundSettings => self.on_account_sounds(cx),259
_ => {}308
_ => {}260
}309
}261
}310
}@@ -297,6 +346,7 @@ impl NotificationCenter {297
.as_ref()346
.as_ref()298
.is_some_and(|selection| selection.conversation_id() == conversation_id);347
.is_some_and(|selection| selection.conversation_id() == conversation_id);299
let own_do_not_disturb = own_do_not_disturb(state);348
let own_do_not_disturb = own_do_not_disturb(state);349
let own_busy = own_presence(state) == PresenceKind::Busy;300
let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {350
let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {301
(Some(engine), Some(me)) => data::in_call(engine, &me.user_id),351
(Some(engine), Some(me)) => data::in_call(engine, &me.user_id),302
_ => false,352
_ => false,@@ -306,6 +356,7 @@ impl NotificationCenter {306
chat_in_foreground: selected && self.main_window_active(cx),356
chat_in_foreground: selected && self.main_window_active(cx),307
system_quiet: platform::system_quiet(),357
system_quiet: platform::system_quiet(),308
own_do_not_disturb,358
own_do_not_disturb,359
own_busy,309
in_call,360
in_call,310
}361
}311
}362
}@@ -356,7 +407,7 @@ impl NotificationCenter {356
}407
}357
let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);408
let throttle_allows = self.throttle.allow(&incoming.conversation_id, now);358
if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {409
if decision.sound && outcome.plays_sound(throttle_allows) && !self.app.read(cx).mode.demo {359
platform::play_sound();410
self.play_notification_sound(cx);360
}411
}361
if let Some(user_id) = incoming.sender_id.clone() {412
if let Some(user_id) = incoming.sender_id.clone() {362
self.app413
self.app@@ -401,8 +452,8 @@ impl NotificationCenter {401
model.time = chrono::Local::now().format("%H:%M").to_string();452
model.time = chrono::Local::now().format("%H:%M").to_string();402
}453
}403
let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;454
let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;404
if self.settings.sound && !quiet {455
if self.settings.sounds.notification_sound && !quiet {405
platform::play_sound();456
self.play_notification_sound(cx);406
}457
}407
self.sync_windows(cx);458
self.sync_windows(cx);408
}459
}@@ -575,12 +626,14 @@ impl NotificationCenter {575
}626
}576
627
577
fn on_meeting_chime(&mut self, cx: &mut Context<Self>) {628
fn on_meeting_chime(&mut self, cx: &mut Context<Self>) {578
if self.settings.sound && !self.reminders_quiet(cx) && !self.demo_mode {629
let busy = self.environment("", cx).busy();579
platform::play_meeting_chime();630
if meeting_start_sound(&self.settings, busy) && !self.reminders_quiet(cx) && !self.demo_mode631
{632
sound_cache::play(CallTone::MeetingReminder.file_name(), cx);580
}633
}581
}634
}582
635
583
fn on_call_end_tone(&mut self, tone: EndTone, cx: &mut Context<Self>) {636
fn on_call_tone(&mut self, tone: CallTone, cx: &mut Context<Self>) {584
if !self.demo_mode {637
if !self.demo_mode {585
sound_cache::play(tone.file_name(), cx);638
sound_cache::play(tone.file_name(), cx);586
}639
}@@ -607,27 +660,32 @@ impl NotificationCenter {607
platform::flash(native);660
platform::flash(native);608
}661
}609
self.sync_windows(cx);662
self.sync_windows(cx);610
self.sync_ring_tone(ringing);663
self.sync_ring_tone(ringing, cx);611
cx.notify();664
cx.notify();612
}665
}613
666
614
fn sync_ring_tone(&mut self, ringing: bool) {667
fn sync_ring_tone(&mut self, ringing: bool, cx: &mut Context<Self>) {615
let audible = ringing && self.settings.sound && !self.demo_mode;668
if !ringing || self.demo_mode {616
match (audible, self.ring_tone.is_some()) {669
self.ring_tone = None;617
(true, false) => self.ring_tone = platform::start_ring(self.settings.ringtone),670
return;618
(false, true) => self.ring_tone = None,671
}619
_ => {}672
if self.ring_tone.is_some() {673
return;674
}675
let environment = self.environment("", cx);676
let native_call = self.app.read(cx).call.is_some();677
if let Some(ringtone) = ringtone_for(&self.settings, native_call, environment.busy()) {678
self.ring_tone = Some(sound_cache::start(ringtone.file_name(), true, cx));620
}679
}621
}680
}622
681
623
fn sync_ringback(&mut self, cx: &Context<Self>) {682
fn sync_call_sounds(&mut self, cx: &Context<Self>) {624
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model))683
let model = self.app.read(cx).call.as_ref().map(|call| &call.model);625
&& !self.demo_mode;684
let ringback = should_ringback(model) && !self.demo_mode;626
match (audible, self.ringback.is_some()) {685
let reconnecting =627
(true, false) => self.ringback = platform::start_ringback(),686
model.is_some_and(|model| model.is_reconnecting() && !model.lobby) && !self.demo_mode;628
(false, true) => self.ringback = None,687
sync_loop(&mut self.ringback, ringback, CallTone::OutgoingRinging, cx);629
_ => {}688
sync_loop(&mut self.reconnecting, reconnecting, CallTone::Reconnecting, cx);630
}631
}689
}632
690
633
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {691
fn slide_offset(&self, opened: Instant, area: WorkArea) -> i32 {@@ -801,9 +859,9 @@ impl NotificationCenter {801
match command {859
match command {802
TrayCommand::Toggle => self.toggle_main_window(cx),860
TrayCommand::Toggle => self.toggle_main_window(cx),803
TrayCommand::Open => self.raise_main_window(cx),861
TrayCommand::Open => self.raise_main_window(cx),804
TrayCommand::ToggleSound => {862
TrayCommand::ToggleSound => self.update_settings(cx, |settings| {805
self.update_settings(cx, |settings| settings.sound = !settings.sound)863
settings.sounds.notification_sound = !settings.sounds.notification_sound806
}864
}),807
TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {865
TrayCommand::ToggleDoNotDisturb => self.update_settings(cx, |settings| {808
settings.do_not_disturb = !settings.do_not_disturb866
settings.do_not_disturb = !settings.do_not_disturb809
}),867
}),@@ -835,7 +893,7 @@ impl NotificationCenter {835
fn sync_tray(&self) {893
fn sync_tray(&self) {836
if let Some(tray) = &self.tray {894
if let Some(tray) = &self.tray {837
tray.sync(895
tray.sync(838
self.settings.sound,896
self.settings.sounds.notification_sound,839
self.settings.do_not_disturb,897
self.settings.do_not_disturb,840
!self.unread_mentions.is_empty(),898
!self.unread_mentions.is_empty(),841
);899
);@@ -1075,7 +1133,7 @@ impl NotificationCenter {1075
};1133
};1076
let decision = Decision {1134
let decision = Decision {1077
toast: true,1135
toast: true,1078
sound: self.settings.sound,1136
sound: self.settings.sounds.notification_sound,1079
};1137
};1080
self.throttle = SoundThrottle::default();1138
self.throttle = SoundThrottle::default();1081
self.present(&incoming, decision, cx);1139
self.present(&incoming, decision, cx);@@ -1127,10 +1185,26 @@ fn open_popup<V: Into<AnyView>>(1127
});1185
});1128
}1186
}1129
1187
1188
fn own_presence(state: &AppState) -> PresenceKind {1189
state1190
.directory1191
.me1192
.as_ref()1193
.map_or(PresenceKind::Unknown, |me| {1194
state.directory.presence_of(&me.user_id).kind()1195
})1196
}1197
1130
fn own_do_not_disturb(state: &AppState) -> bool {1198
fn own_do_not_disturb(state: &AppState) -> bool {1131
state.directory.me.as_ref().is_some_and(|me| {1199
own_presence(state) == PresenceKind::DoNotDisturb1132
state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb1200
}1133
})1201
1202
fn sync_loop(handle: &mut Option<SoundHandle>, audible: bool, tone: CallTone, cx: &App) {1203
match (audible, handle.is_some()) {1204
(true, false) => *handle = Some(sound_cache::start(tone.file_name(), true, cx)),1205
(false, true) => *handle = None,1206
_ => {}1207
}1134
}1208
}1135
1209
1136
fn demo_scene() -> Option<DemoScene> {1210
fn demo_scene() -> Option<DemoScene> {@@ -14,8 +14,7 @@ use gpui_kit::prelude::FluentBuilder as _;
14
14
use gpui_kit::*;
15
15
16
16
use super::center::NotificationCenter;
17
use super::platform;
18
use super::ring_tone::Ringtone;
17
use super::sounds::{AlertSound, Ringtone, RingtoneCallType};
19
18
use super::rules::Settings;
20
19
use super::settings_mcp::McpView;
21
20
use crate::agents::AgentsSettings;
@@ -25,6 +24,7 @@ use crate::theme;
25
24
26
25
const FPS_TICK: Duration = Duration::from_millis(500);
27
26
const SELECT_WIDTH: f32 = 170.;
27
const SOUND_SELECT_WIDTH: f32 = 124.;
28
28
const PREVIEW_WIDTH: f32 = 380.;
29
29
const PREVIEW_HEIGHT: f32 = 214.;
30
30
const PREVIEW_RADIUS: f32 = 10.;
@@ -38,14 +38,16 @@ fn camera_in_call(state: &AppState) -> bool {
38
38
#[derive(Clone, Copy, PartialEq, Eq)]
39
39
pub(super) enum Section {
40
40
Notifications,
41
Calls,
41
42
Devices,
42
43
Agents,
43
44
Mcp,
44
45
}
45
46
46
47
impl Section {
47
const ALL: [Section; 4] = [
48
const ALL: [Section; 5] = [
48
49
Section::Notifications,
50
Section::Calls,
49
51
Section::Devices,
50
52
Section::Agents,
51
53
Section::Mcp,
@@ -54,6 +56,7 @@ impl Section {
54
56
fn label(self) -> &'static str {
55
57
match self {
56
58
Section::Notifications => "Notifications",
59
Section::Calls => "Calls",
57
60
Section::Devices => "Devices",
58
61
Section::Agents => "Agents",
59
62
Section::Mcp => "MCP",
@@ -69,12 +72,7 @@ struct Row {
69
72
field: Accessor,
70
73
}
71
74
72
const ROWS: [Row; 6] = [
73
Row {
74
title: "Sound",
75
detail: "Messages and mentions",
76
field: |settings| &mut settings.sound,
77
},
75
const ROWS: [Row; 5] = [
78
76
Row {
79
77
title: "Mentions only",
80
78
detail: "Direct messages and @mentions",
@@ -102,6 +100,33 @@ const ROWS: [Row; 6] = [
102
100
},
103
101
];
104
102
103
const NOTIFICATION_SOUND_ROW: Row = Row {
104
title: "Play sounds with notifications",
105
detail: "",
106
field: |settings| &mut settings.sounds.notification_sound,
107
};
108
109
const URGENT_SOUND_ROW: Row = Row {
110
title: "Play sounds with urgent and priority contact notifications",
111
detail: "",
112
field: |settings| &mut settings.sounds.urgent_sound,
113
};
114
115
const CALL_SOUND_ROWS: [Row; 2] = [
116
Row {
117
title: "Play sounds with incoming calls, requests to join, and meeting start notifications",
118
detail: "",
119
field: |settings| &mut settings.sounds.call_and_meeting_sound,
120
},
121
Row {
122
title: "Play sounds when I'm busy or in a meeting",
123
detail: "",
124
field: |settings| &mut settings.sounds.sound_when_busy,
125
},
126
];
127
128
type SoundAccessor = fn(&mut Settings) -> &mut AlertSound;
129
105
130
pub struct SettingsView {
106
131
center: Entity<NotificationCenter>,
107
132
section: Section,
@@ -207,7 +232,9 @@ impl SettingsView {
207
232
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
208
233
self.start_preview();
209
234
}
210
Section::Notifications | Section::Agents | Section::Mcp => self.preview.stop(cx),
235
Section::Notifications | Section::Calls | Section::Agents | Section::Mcp => {
236
self.preview.stop(cx)
237
}
211
238
}
212
239
cx.notify();
213
240
}
@@ -388,8 +415,12 @@ pub(crate) fn switch(on: bool) -> Div {
388
415
}
389
416
390
417
fn button(label: &'static str) -> Stateful<Div> {
418
button_with_id(label, label)
419
}
420
421
fn button_with_id(id: &'static str, label: &'static str) -> Stateful<Div> {
391
422
div()
392
.id(label)
423
.id(id)
393
424
.h(px(32.))
394
425
.px(px(14.))
395
426
.flex()
@@ -424,12 +455,18 @@ pub(super) fn titled_with(
424
455
.text_color(theme::text())
425
456
.child(title),
426
457
)
427
.child(
428
div()
429
.text_size(px(12.))
430
.text_color(detail_color)
431
.child(detail.into()),
432
)
458
.map(|column| {
459
let detail = detail.into();
460
if detail.is_empty() {
461
return column;
462
}
463
column.child(
464
div()
465
.text_size(px(12.))
466
.text_color(detail_color)
467
.child(detail),
468
)
469
})
433
470
}
434
471
435
472
pub(super) fn control_row(
@@ -469,43 +506,164 @@ fn section_tab(section: Section, active: bool, view: Entity<SettingsView>) -> St
469
506
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_section(section, cx)))
470
507
}
471
508
509
fn heading(title: &'static str) -> Div {
510
div()
511
.w_full()
512
.px(px(20.))
513
.pt(px(16.))
514
.pb(px(4.))
515
.text_size(px(12.))
516
.font_weight(FontWeight::SEMIBOLD)
517
.text_color(theme::text_muted())
518
.child(title)
519
}
520
521
fn picker(
522
id: &'static str,
523
label: &'static str,
524
disabled: bool,
525
menu_items: impl Fn() -> Vec<(&'static str, bool, Box<dyn Fn(&mut App)>)> + 'static,
526
) -> impl IntoElement {
527
Button::new(id)
528
.outline()
529
.w(px(SOUND_SELECT_WIDTH))
530
.label(label)
531
.icon(IconName::ChevronDown)
532
.disabled(disabled)
533
.dropdown_menu(move |menu, _, _| {
534
menu_items()
535
.into_iter()
536
.fold(menu, |menu, (label, checked, choose)| {
537
menu.item(
538
PopupMenuItem::new(label)
539
.checked(checked)
540
.on_click(move |_, _, cx| choose(cx)),
541
)
542
})
543
})
544
}
545
472
546
impl SettingsView {
473
fn ringtone_row(&self, current: Ringtone) -> Div {
547
fn switch_row(&self, row: &Row, on: bool) -> Stateful<Div> {
548
let center = self.center.clone();
549
let field = row.field;
550
h_flex()
551
.id(row.title)
552
.w_full()
553
.px(px(20.))
554
.py(px(10.))
555
.gap(px(12.))
556
.items_center()
557
.cursor_pointer()
558
.hover(|row| row.bg(theme::row_hover()))
559
.on_click(move |_, _, cx| {
560
center.update(cx, |center, cx| {
561
center.update_settings(cx, |settings| {
562
let value = field(settings);
563
*value = !*value;
564
})
565
});
566
})
567
.child(titled(row.title, row.detail))
568
.child(switch(on))
569
}
570
571
fn alert_sound_row(
572
&self,
573
(id, preview_id): (&'static str, &'static str),
574
title: &'static str,
575
options: &'static [AlertSound],
576
current: AlertSound,
577
enabled: bool,
578
field: SoundAccessor,
579
) -> Div {
474
580
let center = self.center.clone();
581
let preview_center = self.center.clone();
582
let choices = move || {
583
options
584
.iter()
585
.map(|sound| {
586
let (center, sound) = (center.clone(), *sound);
587
let choose: Box<dyn Fn(&mut App)> = Box::new(move |cx| {
588
center.update(cx, |center, cx| {
589
center.update_settings(cx, |settings| *field(settings) = sound);
590
center.preview_sound(sound.file_name(), cx);
591
})
592
});
593
(sound.label(), sound == current, choose)
594
})
595
.collect()
596
};
475
597
control_row(
476
"Ringtone",
477
"Incoming calls",
598
title,
599
"",
478
600
h_flex()
479
601
.gap(px(8.))
480
602
.items_center()
481
.child(
482
Button::new("ringtone-select")
483
.outline()
484
.w(px(110.))
485
.label(current.label())
486
.icon(IconName::ChevronDown)
487
.dropdown_menu(move |menu, _, _| {
488
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {
489
let (center, ringtone) = (center.clone(), *ringtone);
490
menu.item(
491
PopupMenuItem::new(ringtone.label())
492
.checked(ringtone == current)
493
.on_click(move |_, _, cx| {
494
center.update(cx, |center, cx| {
495
center.update_settings(cx, |settings| {
496
settings.ringtone = ringtone
497
})
498
});
499
platform::play_preview(ringtone);
500
}),
501
)
502
})
503
}),
504
)
505
.child(button("Play").on_click(move |_, _, _| platform::play_preview(current))),
603
.child(picker(id, current.label(), !enabled, choices))
604
.child(button_with_id(preview_id, "Preview").on_click(
605
move |_, _, cx| {
606
preview_center
607
.update(cx, |center, cx| center.preview_sound(current.file_name(), cx))
608
},
609
)),
506
610
)
507
611
}
508
612
613
fn ringtone_row(&self, call_type: RingtoneCallType, current: Ringtone) -> Div {
614
let center = self.center.clone();
615
let preview_center = self.center.clone();
616
let choices = move || {
617
Ringtone::ALL
618
.iter()
619
.map(|ringtone| {
620
let (center, ringtone) = (center.clone(), *ringtone);
621
let choose: Box<dyn Fn(&mut App)> = Box::new(move |cx| {
622
center.update(cx, |center, cx| {
623
center.update_settings(cx, |settings| {
624
settings.sounds.ringtones.set(call_type, ringtone)
625
});
626
center.preview_sound(ringtone.file_name(), cx);
627
})
628
});
629
(ringtone.label(), ringtone == current, choose)
630
})
631
.collect()
632
};
633
let (id, preview_id) = ringtone_ids(call_type);
634
control_row(
635
call_type.label(),
636
"",
637
h_flex()
638
.gap(px(8.))
639
.items_center()
640
.child(picker(id, current.label(), false, choices))
641
.child(button_with_id(preview_id, "Preview").on_click(
642
move |_, _, cx| {
643
preview_center.update(cx, |center, cx| {
644
center.preview_sound(current.file_name(), cx)
645
})
646
},
647
)),
648
)
649
}
650
651
fn calls_section(&self, cx: &App) -> Div {
652
let ringtones = self.center.read(cx).settings().sounds.ringtones;
653
let rows = RingtoneCallType::ALL
654
.into_iter()
655
.filter(|call_type| {
656
*call_type == RingtoneCallType::Regular
657
|| ringtones.get(*call_type) != Ringtone::Ring
658
})
659
.map(|call_type| self.ringtone_row(call_type, ringtones.get(call_type)));
660
v_flex()
661
.w_full()
662
.pt(px(8.))
663
.child(heading("Choose a ringtone"))
664
.children(rows)
665
}
666
509
667
fn devices_section(&self, cx: &mut Context<Self>) -> Div {
510
668
let view = cx.entity();
511
669
let camera_label = self
@@ -737,7 +895,14 @@ impl Render for SettingsView {
737
895
Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())),
738
896
);
739
897
let body = match self.section {
740
Section::Notifications => self.notifications_section(cx).into_any_element(),
898
Section::Notifications => div()
899
.id("notifications-scroll")
900
.flex_1()
901
.min_h(px(0.))
902
.overflow_y_scroll()
903
.child(self.notifications_section(cx))
904
.into_any_element(),
905
Section::Calls => self.calls_section(cx).into_any_element(),
741
906
Section::Devices => div()
742
907
.id("devices-scroll")
743
908
.flex_1()
@@ -767,54 +932,27 @@ impl SettingsView {
767
932
fn notifications_section(&self, cx: &App) -> Div {
768
933
let mut current = self.center.read(cx).settings().clone();
769
934
let corner = current.corner;
770
let ringtone = current.ringtone;
771
let rows = ROWS.iter().enumerate().map(|(index, row)| {
772
let on = *(row.field)(&mut current);
773
let center = self.center.clone();
774
let field = row.field;
775
h_flex()
776
.id(("setting", index))
777
.w_full()
778
.px(px(20.))
779
.py(px(10.))
780
.gap(px(12.))
781
.items_center()
782
.cursor_pointer()
783
.hover(|row| row.bg(theme::row_hover()))
784
.on_click(move |_, _, cx| {
785
center.update(cx, |center, cx| {
786
center.update_settings(cx, |settings| {
787
let value = field(settings);
788
*value = !*value;
789
})
790
});
791
})
792
.child(
793
v_flex()
794
.flex_1()
795
.child(
796
div()
797
.text_size(px(14.))
798
.font_weight(FontWeight::SEMIBOLD)
799
.text_color(theme::text())
800
.child(row.title),
801
)
802
.child(
803
div()
804
.text_size(px(12.))
805
.text_color(theme::text_muted())
806
.child(row.detail),
807
),
808
)
809
.child(switch(on))
810
});
935
let sounds = current.sounds.clone();
936
let rows: Vec<Stateful<Div>> = ROWS
937
.iter()
938
.map(|row| {
939
let on = *(row.field)(&mut current);
940
self.switch_row(row, on)
941
})
942
.collect();
943
let call_sound_rows: Vec<Stateful<Div>> = CALL_SOUND_ROWS
944
.iter()
945
.map(|row| {
946
let on = *(row.field)(&mut current);
947
self.switch_row(row, on)
948
})
949
.collect();
811
950
let position_center = self.center.clone();
812
951
let test_center = self.center.clone();
813
952
v_flex()
814
953
.w_full()
815
954
.pt(px(8.))
816
955
.children(rows)
817
.child(self.ringtone_row(ringtone))
818
956
.child(control_row(
819
957
"Position",
820
958
"Corner of the main screen",
@@ -826,10 +964,39 @@ impl SettingsView {
826
964
});
827
965
}),
828
966
))
829
.child(h_flex().w_full().px(px(20.)).pt(px(12.)).child(
967
.child(heading("Sound"))
968
.child(self.switch_row(&NOTIFICATION_SOUND_ROW, sounds.notification_sound))
969
.child(self.alert_sound_row(
970
("notification-sound", "notification-sound-preview"),
971
"Notification sound",
972
&AlertSound::NORMAL,
973
sounds.notification_sound_type,
974
sounds.notification_sound,
975
|settings| &mut settings.sounds.notification_sound_type,
976
))
977
.child(self.switch_row(&URGENT_SOUND_ROW, sounds.urgent_sound))
978
.child(self.alert_sound_row(
979
("urgent-sound", "urgent-sound-preview"),
980
"Urgent sound",
981
&AlertSound::URGENT,
982
sounds.urgent_sound_type,
983
sounds.urgent_sound,
984
|settings| &mut settings.sounds.urgent_sound_type,
985
))
986
.children(call_sound_rows)
987
.child(h_flex().w_full().px(px(20.)).py(px(12.)).child(
830
988
button("Send test notification").on_click(move |_, _, cx| {
831
989
test_center.update(cx, |center, cx| center.send_test_notification(cx));
832
990
}),
833
991
))
834
992
}
835
993
}
994
995
fn ringtone_ids(call_type: RingtoneCallType) -> (&'static str, &'static str) {
996
match call_type {
997
RingtoneCallType::Regular => ("ringtone-regular", "ringtone-regular-preview"),
998
RingtoneCallType::CallGroup => ("ringtone-call-group", "ringtone-call-group-preview"),
999
RingtoneCallType::CallQueue => ("ringtone-call-queue", "ringtone-call-queue-preview"),
1000
RingtoneCallType::Delegate => ("ringtone-delegate", "ringtone-delegate-preview"),
1001
}
1002
}
@@ -14,8 +14,7 @@ use gpui_kit::prelude::FluentBuilder as _;14
use gpui_kit::*;14
use gpui_kit::*;15
15
16
use super::center::NotificationCenter;16
use super::center::NotificationCenter;17
use super::platform;17
use super::sounds::{AlertSound, Ringtone, RingtoneCallType};18
use super::ring_tone::Ringtone;19
use super::rules::Settings;18
use super::rules::Settings;20
use super::settings_mcp::McpView;19
use super::settings_mcp::McpView;21
use crate::agents::AgentsSettings;20
use crate::agents::AgentsSettings;@@ -25,6 +24,7 @@ use crate::theme;25
24
26
const FPS_TICK: Duration = Duration::from_millis(500);25
const FPS_TICK: Duration = Duration::from_millis(500);27
const SELECT_WIDTH: f32 = 170.;26
const SELECT_WIDTH: f32 = 170.;27
const SOUND_SELECT_WIDTH: f32 = 124.;28
const PREVIEW_WIDTH: f32 = 380.;28
const PREVIEW_WIDTH: f32 = 380.;29
const PREVIEW_HEIGHT: f32 = 214.;29
const PREVIEW_HEIGHT: f32 = 214.;30
const PREVIEW_RADIUS: f32 = 10.;30
const PREVIEW_RADIUS: f32 = 10.;@@ -38,14 +38,16 @@ fn camera_in_call(state: &AppState) -> bool {38
#[derive(Clone, Copy, PartialEq, Eq)]38
#[derive(Clone, Copy, PartialEq, Eq)]39
pub(super) enum Section {39
pub(super) enum Section {40
Notifications,40
Notifications,41
Calls,41
Devices,42
Devices,42
Agents,43
Agents,43
Mcp,44
Mcp,44
}45
}45
46
46
impl Section {47
impl Section {47
const ALL: [Section; 4] = [48
const ALL: [Section; 5] = [48
Section::Notifications,49
Section::Notifications,50
Section::Calls,49
Section::Devices,51
Section::Devices,50
Section::Agents,52
Section::Agents,51
Section::Mcp,53
Section::Mcp,@@ -54,6 +56,7 @@ impl Section {54
fn label(self) -> &'static str {56
fn label(self) -> &'static str {55
match self {57
match self {56
Section::Notifications => "Notifications",58
Section::Notifications => "Notifications",59
Section::Calls => "Calls",57
Section::Devices => "Devices",60
Section::Devices => "Devices",58
Section::Agents => "Agents",61
Section::Agents => "Agents",59
Section::Mcp => "MCP",62
Section::Mcp => "MCP",@@ -69,12 +72,7 @@ struct Row {69
field: Accessor,72
field: Accessor,70
}73
}71
74
72
const ROWS: [Row; 6] = [75
const ROWS: [Row; 5] = [73
Row {74
title: "Sound",75
detail: "Messages and mentions",76
field: |settings| &mut settings.sound,77
},78
Row {76
Row {79
title: "Mentions only",77
title: "Mentions only",80
detail: "Direct messages and @mentions",78
detail: "Direct messages and @mentions",@@ -102,6 +100,33 @@ const ROWS: [Row; 6] = [102
},100
},103
];101
];104
102
103
const NOTIFICATION_SOUND_ROW: Row = Row {104
title: "Play sounds with notifications",105
detail: "",106
field: |settings| &mut settings.sounds.notification_sound,107
};108
109
const URGENT_SOUND_ROW: Row = Row {110
title: "Play sounds with urgent and priority contact notifications",111
detail: "",112
field: |settings| &mut settings.sounds.urgent_sound,113
};114
115
const CALL_SOUND_ROWS: [Row; 2] = [116
Row {117
title: "Play sounds with incoming calls, requests to join, and meeting start notifications",118
detail: "",119
field: |settings| &mut settings.sounds.call_and_meeting_sound,120
},121
Row {122
title: "Play sounds when I'm busy or in a meeting",123
detail: "",124
field: |settings| &mut settings.sounds.sound_when_busy,125
},126
];127
128
type SoundAccessor = fn(&mut Settings) -> &mut AlertSound;129
105
pub struct SettingsView {130
pub struct SettingsView {106
center: Entity<NotificationCenter>,131
center: Entity<NotificationCenter>,107
section: Section,132
section: Section,@@ -207,7 +232,9 @@ impl SettingsView {207
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));232
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));208
self.start_preview();233
self.start_preview();209
}234
}210
Section::Notifications | Section::Agents | Section::Mcp => self.preview.stop(cx),235
Section::Notifications | Section::Calls | Section::Agents | Section::Mcp => {236
self.preview.stop(cx)237
}211
}238
}212
cx.notify();239
cx.notify();213
}240
}@@ -388,8 +415,12 @@ pub(crate) fn switch(on: bool) -> Div {388
}415
}389
416
390
fn button(label: &'static str) -> Stateful<Div> {417
fn button(label: &'static str) -> Stateful<Div> {418
button_with_id(label, label)419
}420
421
fn button_with_id(id: &'static str, label: &'static str) -> Stateful<Div> {391
div()422
div()392
.id(label)423
.id(id)393
.h(px(32.))424
.h(px(32.))394
.px(px(14.))425
.px(px(14.))395
.flex()426
.flex()@@ -424,12 +455,18 @@ pub(super) fn titled_with(424
.text_color(theme::text())455
.text_color(theme::text())425
.child(title),456
.child(title),426
)457
)427
.child(458
.map(|column| {428
div()459
let detail = detail.into();429
.text_size(px(12.))460
if detail.is_empty() {430
.text_color(detail_color)461
return column;431
.child(detail.into()),462
}432
)463
column.child(464
div()465
.text_size(px(12.))466
.text_color(detail_color)467
.child(detail),468
)469
})433
}470
}434
471
435
pub(super) fn control_row(472
pub(super) fn control_row(@@ -469,43 +506,164 @@ fn section_tab(section: Section, active: bool, view: Entity<SettingsView>) -> St469
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_section(section, cx)))506
.on_click(move |_, _, cx| view.update(cx, |view, cx| view.select_section(section, cx)))470
}507
}471
508
509
fn heading(title: &'static str) -> Div {510
div()511
.w_full()512
.px(px(20.))513
.pt(px(16.))514
.pb(px(4.))515
.text_size(px(12.))516
.font_weight(FontWeight::SEMIBOLD)517
.text_color(theme::text_muted())518
.child(title)519
}520
521
fn picker(522
id: &'static str,523
label: &'static str,524
disabled: bool,525
menu_items: impl Fn() -> Vec<(&'static str, bool, Box<dyn Fn(&mut App)>)> + 'static,526
) -> impl IntoElement {527
Button::new(id)528
.outline()529
.w(px(SOUND_SELECT_WIDTH))530
.label(label)531
.icon(IconName::ChevronDown)532
.disabled(disabled)533
.dropdown_menu(move |menu, _, _| {534
menu_items()535
.into_iter()536
.fold(menu, |menu, (label, checked, choose)| {537
menu.item(538
PopupMenuItem::new(label)539
.checked(checked)540
.on_click(move |_, _, cx| choose(cx)),541
)542
})543
})544
}545
472
impl SettingsView {546
impl SettingsView {473
fn ringtone_row(&self, current: Ringtone) -> Div {547
fn switch_row(&self, row: &Row, on: bool) -> Stateful<Div> {548
let center = self.center.clone();549
let field = row.field;550
h_flex()551
.id(row.title)552
.w_full()553
.px(px(20.))554
.py(px(10.))555
.gap(px(12.))556
.items_center()557
.cursor_pointer()558
.hover(|row| row.bg(theme::row_hover()))559
.on_click(move |_, _, cx| {560
center.update(cx, |center, cx| {561
center.update_settings(cx, |settings| {562
let value = field(settings);563
*value = !*value;564
})565
});566
})567
.child(titled(row.title, row.detail))568
.child(switch(on))569
}570
571
fn alert_sound_row(572
&self,573
(id, preview_id): (&'static str, &'static str),574
title: &'static str,575
options: &'static [AlertSound],576
current: AlertSound,577
enabled: bool,578
field: SoundAccessor,579
) -> Div {474
let center = self.center.clone();580
let center = self.center.clone();581
let preview_center = self.center.clone();582
let choices = move || {583
options584
.iter()585
.map(|sound| {586
let (center, sound) = (center.clone(), *sound);587
let choose: Box<dyn Fn(&mut App)> = Box::new(move |cx| {588
center.update(cx, |center, cx| {589
center.update_settings(cx, |settings| *field(settings) = sound);590
center.preview_sound(sound.file_name(), cx);591
})592
});593
(sound.label(), sound == current, choose)594
})595
.collect()596
};475
control_row(597
control_row(476
"Ringtone",598
title,477
"Incoming calls",599
"",478
h_flex()600
h_flex()479
.gap(px(8.))601
.gap(px(8.))480
.items_center()602
.items_center()481
.child(603
.child(picker(id, current.label(), !enabled, choices))482
Button::new("ringtone-select")604
.child(button_with_id(preview_id, "Preview").on_click(483
.outline()605
move |_, _, cx| {484
.w(px(110.))606
preview_center485
.label(current.label())607
.update(cx, |center, cx| center.preview_sound(current.file_name(), cx))486
.icon(IconName::ChevronDown)608
},487
.dropdown_menu(move |menu, _, _| {609
)),488
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {489
let (center, ringtone) = (center.clone(), *ringtone);490
menu.item(491
PopupMenuItem::new(ringtone.label())492
.checked(ringtone == current)493
.on_click(move |_, _, cx| {494
center.update(cx, |center, cx| {495
center.update_settings(cx, |settings| {496
settings.ringtone = ringtone497
})498
});499
platform::play_preview(ringtone);500
}),501
)502
})503
}),504
)505
.child(button("Play").on_click(move |_, _, _| platform::play_preview(current))),506
)610
)507
}611
}508
612
613
fn ringtone_row(&self, call_type: RingtoneCallType, current: Ringtone) -> Div {614
let center = self.center.clone();615
let preview_center = self.center.clone();616
let choices = move || {617
Ringtone::ALL618
.iter()619
.map(|ringtone| {620
let (center, ringtone) = (center.clone(), *ringtone);621
let choose: Box<dyn Fn(&mut App)> = Box::new(move |cx| {622
center.update(cx, |center, cx| {623
center.update_settings(cx, |settings| {624
settings.sounds.ringtones.set(call_type, ringtone)625
});626
center.preview_sound(ringtone.file_name(), cx);627
})628
});629
(ringtone.label(), ringtone == current, choose)630
})631
.collect()632
};633
let (id, preview_id) = ringtone_ids(call_type);634
control_row(635
call_type.label(),636
"",637
h_flex()638
.gap(px(8.))639
.items_center()640
.child(picker(id, current.label(), false, choices))641
.child(button_with_id(preview_id, "Preview").on_click(642
move |_, _, cx| {643
preview_center.update(cx, |center, cx| {644
center.preview_sound(current.file_name(), cx)645
})646
},647
)),648
)649
}650
651
fn calls_section(&self, cx: &App) -> Div {652
let ringtones = self.center.read(cx).settings().sounds.ringtones;653
let rows = RingtoneCallType::ALL654
.into_iter()655
.filter(|call_type| {656
*call_type == RingtoneCallType::Regular657
|| ringtones.get(*call_type) != Ringtone::Ring658
})659
.map(|call_type| self.ringtone_row(call_type, ringtones.get(call_type)));660
v_flex()661
.w_full()662
.pt(px(8.))663
.child(heading("Choose a ringtone"))664
.children(rows)665
}666
509
fn devices_section(&self, cx: &mut Context<Self>) -> Div {667
fn devices_section(&self, cx: &mut Context<Self>) -> Div {510
let view = cx.entity();668
let view = cx.entity();511
let camera_label = self669
let camera_label = self@@ -737,7 +895,14 @@ impl Render for SettingsView {737
Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())),895
Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())),738
);896
);739
let body = match self.section {897
let body = match self.section {740
Section::Notifications => self.notifications_section(cx).into_any_element(),898
Section::Notifications => div()899
.id("notifications-scroll")900
.flex_1()901
.min_h(px(0.))902
.overflow_y_scroll()903
.child(self.notifications_section(cx))904
.into_any_element(),905
Section::Calls => self.calls_section(cx).into_any_element(),741
Section::Devices => div()906
Section::Devices => div()742
.id("devices-scroll")907
.id("devices-scroll")743
.flex_1()908
.flex_1()@@ -767,54 +932,27 @@ impl SettingsView {767
fn notifications_section(&self, cx: &App) -> Div {932
fn notifications_section(&self, cx: &App) -> Div {768
let mut current = self.center.read(cx).settings().clone();933
let mut current = self.center.read(cx).settings().clone();769
let corner = current.corner;934
let corner = current.corner;770
let ringtone = current.ringtone;935
let sounds = current.sounds.clone();771
let rows = ROWS.iter().enumerate().map(|(index, row)| {936
let rows: Vec<Stateful<Div>> = ROWS772
let on = *(row.field)(&mut current);937
.iter()773
let center = self.center.clone();938
.map(|row| {774
let field = row.field;939
let on = *(row.field)(&mut current);775
h_flex()940
self.switch_row(row, on)776
.id(("setting", index))941
})777
.w_full()942
.collect();778
.px(px(20.))943
let call_sound_rows: Vec<Stateful<Div>> = CALL_SOUND_ROWS779
.py(px(10.))944
.iter()780
.gap(px(12.))945
.map(|row| {781
.items_center()946
let on = *(row.field)(&mut current);782
.cursor_pointer()947
self.switch_row(row, on)783
.hover(|row| row.bg(theme::row_hover()))948
})784
.on_click(move |_, _, cx| {949
.collect();785
center.update(cx, |center, cx| {786
center.update_settings(cx, |settings| {787
let value = field(settings);788
*value = !*value;789
})790
});791
})792
.child(793
v_flex()794
.flex_1()795
.child(796
div()797
.text_size(px(14.))798
.font_weight(FontWeight::SEMIBOLD)799
.text_color(theme::text())800
.child(row.title),801
)802
.child(803
div()804
.text_size(px(12.))805
.text_color(theme::text_muted())806
.child(row.detail),807
),808
)809
.child(switch(on))810
});811
let position_center = self.center.clone();950
let position_center = self.center.clone();812
let test_center = self.center.clone();951
let test_center = self.center.clone();813
v_flex()952
v_flex()814
.w_full()953
.w_full()815
.pt(px(8.))954
.pt(px(8.))816
.children(rows)955
.children(rows)817
.child(self.ringtone_row(ringtone))818
.child(control_row(956
.child(control_row(819
"Position",957
"Position",820
"Corner of the main screen",958
"Corner of the main screen",@@ -826,10 +964,39 @@ impl SettingsView {826
});964
});827
}),965
}),828
))966
))829
.child(h_flex().w_full().px(px(20.)).pt(px(12.)).child(967
.child(heading("Sound"))968
.child(self.switch_row(&NOTIFICATION_SOUND_ROW, sounds.notification_sound))969
.child(self.alert_sound_row(970
("notification-sound", "notification-sound-preview"),971
"Notification sound",972
&AlertSound::NORMAL,973
sounds.notification_sound_type,974
sounds.notification_sound,975
|settings| &mut settings.sounds.notification_sound_type,976
))977
.child(self.switch_row(&URGENT_SOUND_ROW, sounds.urgent_sound))978
.child(self.alert_sound_row(979
("urgent-sound", "urgent-sound-preview"),980
"Urgent sound",981
&AlertSound::URGENT,982
sounds.urgent_sound_type,983
sounds.urgent_sound,984
|settings| &mut settings.sounds.urgent_sound_type,985
))986
.children(call_sound_rows)987
.child(h_flex().w_full().px(px(20.)).py(px(12.)).child(830
button("Send test notification").on_click(move |_, _, cx| {988
button("Send test notification").on_click(move |_, _, cx| {831
test_center.update(cx, |center, cx| center.send_test_notification(cx));989
test_center.update(cx, |center, cx| center.send_test_notification(cx));832
}),990
}),833
))991
))834
}992
}835
}993
}994
995
fn ringtone_ids(call_type: RingtoneCallType) -> (&'static str, &'static str) {996
match call_type {997
RingtoneCallType::Regular => ("ringtone-regular", "ringtone-regular-preview"),998
RingtoneCallType::CallGroup => ("ringtone-call-group", "ringtone-call-group-preview"),999
RingtoneCallType::CallQueue => ("ringtone-call-queue", "ringtone-call-queue-preview"),1000
RingtoneCallType::Delegate => ("ringtone-delegate", "ringtone-delegate-preview"),1001
}1002
}@@ -647,7 +647,8 @@ impl ConversationView {
647
647
| AppEvent::MissedCall(_)
648
648
| AppEvent::MeetingReminder
649
649
| AppEvent::MeetingChime
650
| AppEvent::CallEndTone(_)
650
| AppEvent::CallTone(_)
651
| AppEvent::SoundSettings
651
652
| AppEvent::Call => {}
652
653
AppEvent::LiveMeeting => cx.notify(),
653
654
AppEvent::Saved => cx.notify(),
@@ -647,7 +647,8 @@ impl ConversationView {647
| AppEvent::MissedCall(_)647
| AppEvent::MissedCall(_)648
| AppEvent::MeetingReminder648
| AppEvent::MeetingReminder649
| AppEvent::MeetingChime649
| AppEvent::MeetingChime650
| AppEvent::CallEndTone(_)650
| AppEvent::CallTone(_)651
| AppEvent::SoundSettings651
| AppEvent::Call => {}652
| AppEvent::Call => {}652
AppEvent::LiveMeeting => cx.notify(),653
AppEvent::LiveMeeting => cx.notify(),653
AppEvent::Saved => cx.notify(),654
AppEvent::Saved => cx.notify(),@@ -214,7 +214,7 @@ impl<T: CsaTransport> LanguageSettingsClient<T> {
214
214
}
215
215
}
216
216
217
fn with_headers(mut request: Request) -> Request {
217
pub(crate) fn with_headers(mut request: Request) -> Request {
218
218
request.headers = vec![
219
219
("x-ms-client-type".to_owned(), CLIENT_TYPE.to_owned()),
220
220
("x-ms-client-version".to_owned(), CLIENT_VERSION.to_owned()),
@@ -214,7 +214,7 @@ impl<T: CsaTransport> LanguageSettingsClient<T> {214
}214
}215
}215
}216
216
217
fn with_headers(mut request: Request) -> Request {217
pub(crate) fn with_headers(mut request: Request) -> Request {218
request.headers = vec![218
request.headers = vec![219
("x-ms-client-type".to_owned(), CLIENT_TYPE.to_owned()),219
("x-ms-client-type".to_owned(), CLIENT_TYPE.to_owned()),220
("x-ms-client-version".to_owned(), CLIENT_VERSION.to_owned()),220
("x-ms-client-version".to_owned(), CLIENT_VERSION.to_owned()),@@ -22,6 +22,8 @@ pub mod recording_policy;
22
22
pub mod receipts;
23
23
pub mod saved;
24
24
pub mod settings;
25
pub mod sound_settings;
26
pub mod sounds;
25
27
pub mod transcripts;
26
28
pub mod translate;
27
29
pub mod window;
@@ -22,6 +22,8 @@ pub mod recording_policy;22
pub mod receipts;22
pub mod receipts;23
pub mod saved;23
pub mod saved;24
pub mod settings;24
pub mod settings;25
pub mod sound_settings;26
pub mod sounds;25
pub mod transcripts;27
pub mod transcripts;26
pub mod translate;28
pub mod translate;27
pub mod window;29
pub mod window;@@ -1,4 +1,4 @@
1
use serde_json::{Map, Value, json};
1
use serde_json::{Map, Value};
2
2
use session::{Method, Request, Session};
3
3
4
4
use crate::error::{Error, Result};
@@ -84,21 +84,21 @@ impl<T: MessageTransport> UserSettings<T> {
84
84
pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {
85
85
let properties = self.properties().await?;
86
86
let merged = merge_chat_section(&properties, section, enabled);
87
let url = format!("{}?name={SETTINGS_KEY}", self.base_url);
88
let body = json!({ SETTINGS_KEY: merged });
89
let answer = self
90
.transport
91
.send(Request::with_body(Method::Put, url, body))
92
.await?;
93
ensure_success(&answer)
87
self.set_property(SETTINGS_KEY, Value::String(merged)).await
94
88
}
95
89
96
90
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {
97
let url = format!("{}?name={SKIN_TONE_KEY}", self.base_url);
98
let body = json!({ SKIN_TONE_KEY: tone.to_string() });
91
self.set_property(SKIN_TONE_KEY, Value::String(tone.to_string()))
92
.await
93
}
94
95
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {
96
let url = format!("{}?name={name}", self.base_url);
97
let mut body = Map::new();
98
body.insert(name.to_owned(), value);
99
99
let answer = self
100
100
.transport
101
.send(Request::with_body(Method::Put, url, body))
101
.send(Request::with_body(Method::Put, url, Value::Object(body)))
102
102
.await?;
103
103
ensure_success(&answer)
104
104
}
@@ -182,6 +182,7 @@ mod tests {
182
182
use std::collections::VecDeque;
183
183
use std::sync::Mutex;
184
184
185
use serde_json::json;
185
186
use session::ApiResponse;
186
187
187
188
use super::*;
@@ -1,4 +1,4 @@1
use serde_json::{Map, Value, json};1
use serde_json::{Map, Value};2
use session::{Method, Request, Session};2
use session::{Method, Request, Session};3
3
4
use crate::error::{Error, Result};4
use crate::error::{Error, Result};@@ -84,21 +84,21 @@ impl<T: MessageTransport> UserSettings<T> {84
pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {84
pub async fn set_chat_section(&self, section: ChatSection, enabled: bool) -> Result<()> {85
let properties = self.properties().await?;85
let properties = self.properties().await?;86
let merged = merge_chat_section(&properties, section, enabled);86
let merged = merge_chat_section(&properties, section, enabled);87
let url = format!("{}?name={SETTINGS_KEY}", self.base_url);87
self.set_property(SETTINGS_KEY, Value::String(merged)).await88
let body = json!({ SETTINGS_KEY: merged });89
let answer = self90
.transport91
.send(Request::with_body(Method::Put, url, body))92
.await?;93
ensure_success(&answer)94
}88
}95
89
96
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {90
pub async fn set_skin_tone(&self, tone: u8) -> Result<()> {97
let url = format!("{}?name={SKIN_TONE_KEY}", self.base_url);91
self.set_property(SKIN_TONE_KEY, Value::String(tone.to_string()))98
let body = json!({ SKIN_TONE_KEY: tone.to_string() });92
.await93
}94
95
pub async fn set_property(&self, name: &str, value: Value) -> Result<()> {96
let url = format!("{}?name={name}", self.base_url);97
let mut body = Map::new();98
body.insert(name.to_owned(), value);99
let answer = self99
let answer = self100
.transport100
.transport101
.send(Request::with_body(Method::Put, url, body))101
.send(Request::with_body(Method::Put, url, Value::Object(body)))102
.await?;102
.await?;103
ensure_success(&answer)103
ensure_success(&answer)104
}104
}@@ -182,6 +182,7 @@ mod tests {182
use std::collections::VecDeque;182
use std::collections::VecDeque;183
use std::sync::Mutex;183
use std::sync::Mutex;184
184
185
use serde_json::json;185
use session::ApiResponse;186
use session::ApiResponse;186
187
187
use super::*;188
use super::*;@@ -0,0 +1,419 @@
1
use serde_json::{Map, Value, json};
2
use session::{Method, Request, SPACES, Scope, Session};
3
4
use crate::error::{Error, Result};
5
use crate::language_settings::with_headers;
6
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};
7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};
8
use crate::settings::UserSettings;
9
use crate::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};
10
11
const SKYPE_SCOPE: &str = "user_impersonation";
12
const PERSONAL_SETTINGS_KEY: &str = "userPersonalSettings";
13
const TOAST_SETTINGS: &str = "toastSettings";
14
const SOUNDS_SETTINGS: &str = "soundsSettings";
15
const ALERT_SOUND: &str = "alertSound";
16
const ALERT_SOUND_TYPE: &str = "alertSoundType";
17
const URGENT_SOUND: &str = "PlayNotificationSoundsForUrgentAndPriority";
18
const URGENT_SOUND_TYPE: &str = "alertUrgentSoundType";
19
const CALL_AND_MEETING_SOUND: &str = "incomingCallsAndMeetingStartSound";
20
const SOUND_WHEN_BUSY: &str = "PlayNotificationSoundsWhenBusyOrInMeetings";
21
const ALERT_SOUND_ON: &str = "All";
22
const ON: &str = "On";
23
const OFF: &str = "Off";
24
const RINGTONE_ASSIGNMENTS_POINTER: &str =
25
"/voiceAdminSettings/value/ringtoneSettings/assignments/ringToneAssignments";
26
27
#[derive(Debug, Clone, PartialEq, Eq)]
28
pub struct SoundSettings {
29
pub notification_sound: bool,
30
pub notification_sound_type: AlertSound,
31
pub urgent_sound: bool,
32
pub urgent_sound_type: AlertSound,
33
pub call_and_meeting_sound: bool,
34
pub sound_when_busy: bool,
35
pub ringtones: RingtoneAssignments,
36
}
37
38
impl Default for SoundSettings {
39
fn default() -> Self {
40
SoundSettings {
41
notification_sound: true,
42
notification_sound_type: AlertSound::Default,
43
urgent_sound: true,
44
urgent_sound_type: AlertSound::DefaultUrgent,
45
call_and_meeting_sound: true,
46
sound_when_busy: true,
47
ringtones: RingtoneAssignments::default(),
48
}
49
}
50
}
51
52
impl SoundSettings {
53
pub fn personal_part_differs(&self, other: &SoundSettings) -> bool {
54
SoundSettings {
55
ringtones: other.ringtones,
56
..self.clone()
57
} != *other
58
}
59
}
60
61
fn personal_settings(properties: &Value) -> Map<String, Value> {
62
properties
63
.get(PERSONAL_SETTINGS_KEY)
64
.and_then(Value::as_str)
65
.and_then(|text| serde_json::from_str::<Value>(text).ok())
66
.and_then(|value| value.as_object().cloned())
67
.unwrap_or_default()
68
}
69
70
fn text_at<'a>(settings: &'a Map<String, Value>, group: &str, field: &str) -> Option<&'a str> {
71
settings.get(group)?.get(field)?.as_str()
72
}
73
74
pub fn parse_sound_settings(properties: &Value, aggregate: &Value) -> SoundSettings {
75
let settings = personal_settings(properties);
76
let defaults = SoundSettings::default();
77
let switch = |group: &str, field: &str, fallback: bool| {
78
text_at(&settings, group, field).map_or(fallback, |value| value != OFF)
79
};
80
let sound = |field: &str, fallback: AlertSound| {
81
text_at(&settings, TOAST_SETTINGS, field)
82
.and_then(AlertSound::from_name)
83
.unwrap_or(fallback)
84
};
85
SoundSettings {
86
notification_sound: switch(SOUNDS_SETTINGS, ALERT_SOUND, defaults.notification_sound),
87
notification_sound_type: sound(ALERT_SOUND_TYPE, defaults.notification_sound_type),
88
urgent_sound: switch(TOAST_SETTINGS, URGENT_SOUND, defaults.urgent_sound),
89
urgent_sound_type: sound(URGENT_SOUND_TYPE, defaults.urgent_sound_type),
90
call_and_meeting_sound: switch(
91
SOUNDS_SETTINGS,
92
CALL_AND_MEETING_SOUND,
93
defaults.call_and_meeting_sound,
94
),
95
sound_when_busy: switch(TOAST_SETTINGS, SOUND_WHEN_BUSY, defaults.sound_when_busy),
96
ringtones: parse_ringtones(aggregate),
97
}
98
}
99
100
pub fn parse_ringtones(aggregate: &Value) -> RingtoneAssignments {
101
let mut assignments = RingtoneAssignments::default();
102
let entries = aggregate
103
.pointer(RINGTONE_ASSIGNMENTS_POINTER)
104
.and_then(Value::as_array)
105
.into_iter()
106
.flatten();
107
for entry in entries {
108
let call_type = entry
109
.get("type")
110
.and_then(Value::as_str)
111
.and_then(RingtoneCallType::from_name);
112
let ringtone = entry
113
.get("value")
114
.and_then(Value::as_str)
115
.and_then(Ringtone::from_name);
116
if let (Some(call_type), Some(ringtone)) = (call_type, ringtone) {
117
assignments.set(call_type, ringtone);
118
}
119
}
120
assignments
121
}
122
123
fn switch_value(on: bool) -> &'static str {
124
if on { ON } else { OFF }
125
}
126
127
/// Writes only the fields that changed, so values rusty-teams does not know (tactile sounds) survive.
128
pub fn merge_sound_settings(
129
properties: &Value,
130
previous: &SoundSettings,
131
updated: &SoundSettings,
132
) -> String {
133
let mut settings = personal_settings(properties);
134
let mut changes: Vec<(&str, &str, &str)> = Vec::new();
135
if previous.notification_sound != updated.notification_sound {
136
let value = if updated.notification_sound {
137
ALERT_SOUND_ON
138
} else {
139
OFF
140
};
141
changes.push((SOUNDS_SETTINGS, ALERT_SOUND, value));
142
}
143
if previous.notification_sound_type != updated.notification_sound_type {
144
changes.push((
145
TOAST_SETTINGS,
146
ALERT_SOUND_TYPE,
147
updated.notification_sound_type.name(),
148
));
149
}
150
if previous.urgent_sound != updated.urgent_sound {
151
changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));
152
}
153
if previous.urgent_sound_type != updated.urgent_sound_type {
154
changes.push((
155
TOAST_SETTINGS,
156
URGENT_SOUND_TYPE,
157
updated.urgent_sound_type.name(),
158
));
159
}
160
if previous.call_and_meeting_sound != updated.call_and_meeting_sound {
161
changes.push((
162
SOUNDS_SETTINGS,
163
CALL_AND_MEETING_SOUND,
164
switch_value(updated.call_and_meeting_sound),
165
));
166
}
167
if previous.sound_when_busy != updated.sound_when_busy {
168
changes.push((
169
TOAST_SETTINGS,
170
SOUND_WHEN_BUSY,
171
switch_value(updated.sound_when_busy),
172
));
173
}
174
for (group, field, value) in changes {
175
let entry = settings
176
.entry(group)
177
.or_insert_with(|| Value::Object(Map::new()));
178
if !entry.is_object() {
179
*entry = Value::Object(Map::new());
180
}
181
if let Some(object) = entry.as_object_mut() {
182
object.insert(field.to_owned(), Value::String(value.to_owned()));
183
}
184
}
185
Value::Object(settings).to_string()
186
}
187
188
pub fn ringtone_body(assignments: &RingtoneAssignments) -> Value {
189
let entries: Vec<Value> = assignments
190
.custom()
191
.into_iter()
192
.map(|(call_type, ringtone)| {
193
json!({"type": call_type.name(), "value": ringtone.name(), "associatedEntityId": ""})
194
})
195
.collect();
196
json!({"assignments": {"ringToneAssignments": entries}})
197
}
198
199
pub fn aggregate_read_body() -> Value {
200
json!({"voiceAdminSettings": true})
201
}
202
203
pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>
204
{
205
properties: UserSettings<P>,
206
middle_tier: M,
207
middle_tier_url: String,
208
}
209
210
impl SoundSettingsClient {
211
pub fn new(session: &Session) -> Self {
212
SoundSettingsClient::with_transports(
213
UserSettings::new(session),
214
SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE)),
215
DEFAULT_REGION,
216
)
217
}
218
}
219
220
impl<P: MessageTransport, M: CsaTransport> SoundSettingsClient<P, M> {
221
pub fn with_transports(properties: UserSettings<P>, middle_tier: M, region: &str) -> Self {
222
SoundSettingsClient {
223
properties,
224
middle_tier,
225
middle_tier_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta"),
226
}
227
}
228
229
pub async fn read(&self) -> Result<SoundSettings> {
230
let properties = self.properties.properties().await?;
231
let url = format!("{}/users/useraggregatesettings", self.middle_tier_url);
232
let answer = self
233
.middle_tier
234
.send(with_headers(Request::with_body(
235
Method::Post,
236
url,
237
aggregate_read_body(),
238
)))
239
.await?;
240
ensure_success(&answer)?;
241
if answer.body.get("voiceAdminSettings").is_none() {
242
return Err(Error::UnexpectedAnswer("no voice settings".into()));
243
}
244
Ok(parse_sound_settings(&properties, &answer.body))
245
}
246
247
pub async fn write(
248
&self,
249
user_mri: &str,
250
previous: &SoundSettings,
251
updated: &SoundSettings,
252
) -> Result<()> {
253
if previous.personal_part_differs(updated) {
254
let properties = self.properties.properties().await?;
255
let merged = merge_sound_settings(&properties, previous, updated);
256
self.properties
257
.set_property(PERSONAL_SETTINGS_KEY, Value::String(merged))
258
.await?;
259
}
260
if previous.ringtones != updated.ringtones {
261
let url = format!(
262
"{}/usersettings/{user_mri}/ringtonesettings",
263
self.middle_tier_url
264
);
265
let answer = self
266
.middle_tier
267
.send(with_headers(Request::with_body(
268
Method::Post,
269
url,
270
ringtone_body(&updated.ringtones),
271
)))
272
.await?;
273
ensure_success(&answer)?;
274
}
275
Ok(())
276
}
277
}
278
279
#[cfg(test)]
280
mod tests {
281
use super::*;
282
283
fn properties(personal: Value) -> Value {
284
json!({"other": "kept", PERSONAL_SETTINGS_KEY: personal.to_string()})
285
}
286
287
fn aggregate(assignments: Value) -> Value {
288
json!({"voiceAdminSettings": {"value": {"ringtoneSettings": {"assignments": {"ringToneAssignments": assignments}}}}})
289
}
290
291
#[test]
292
fn missing_settings_give_the_teams_defaults() {
293
assert_eq!(
294
parse_sound_settings(&json!({}), &json!({})),
295
SoundSettings::default()
296
);
297
}
298
299
#[test]
300
fn reads_the_account_values_teams_writes() {
301
let personal = json!({
302
"toastSettings": {
303
"alertSoundType": "Tap",
304
"alertUrgentSoundType": "Alarm",
305
"PlayNotificationSoundsForUrgentAndPriority": "Off",
306
"PlayNotificationSoundsWhenBusyOrInMeetings": "Off"
307
},
308
"soundsSettings": {"alertSound": "Off", "incomingCallsAndMeetingStartSound": "Off"}
309
});
310
let parsed = parse_sound_settings(
311
&properties(personal),
312
&aggregate(json!([
313
{"type": "Regular", "value": "Bop", "associatedEntityId": ""},
314
{"type": "Delegate", "value": "plink"},
315
{"type": "Unknown", "value": "Bop"},
316
{"type": "CallGroup", "value": "Chime"}
317
])),
318
);
319
assert_eq!(
320
parsed,
321
SoundSettings {
322
notification_sound: false,
323
notification_sound_type: AlertSound::Tap,
324
urgent_sound: false,
325
urgent_sound_type: AlertSound::Alarm,
326
call_and_meeting_sound: false,
327
sound_when_busy: false,
328
ringtones: RingtoneAssignments {
329
regular: Ringtone::Bop,
330
delegate: Ringtone::Plink,
331
..Default::default()
332
},
333
}
334
);
335
}
336
337
#[test]
338
fn an_unknown_sound_falls_back_to_the_default() {
339
let personal = json!({"toastSettings": {"alertSoundType": "TACTILE_DEFAULT"}, "soundsSettings": {"alertSound": "All"}});
340
let parsed = parse_sound_settings(&properties(personal), &json!({}));
341
assert!(parsed.notification_sound);
342
assert_eq!(parsed.notification_sound_type, AlertSound::Default);
343
}
344
345
#[test]
346
fn merge_writes_only_the_changed_fields_and_keeps_the_rest() {
347
let personal = json!({
348
"toastSettings": {"alertSoundType": "TACTILE_DEFAULT", "Chat": true},
349
"soundsSettings": {"alertSound": "All"},
350
"emailSettings": {"EmailDigestDelay": "Daily"}
351
});
352
let previous = SoundSettings::default();
353
let updated = SoundSettings {
354
notification_sound: false,
355
urgent_sound_type: AlertSound::Escalate,
356
sound_when_busy: false,
357
..previous.clone()
358
};
359
let merged: Value =
360
serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))
361
.unwrap();
362
assert_eq!(
363
merged,
364
json!({
365
"toastSettings": {
366
"alertSoundType": "TACTILE_DEFAULT",
367
"Chat": true,
368
"alertUrgentSoundType": "Escalate",
369
"PlayNotificationSoundsWhenBusyOrInMeetings": "Off"
370
},
371
"soundsSettings": {"alertSound": "Off"},
372
"emailSettings": {"EmailDigestDelay": "Daily"}
373
})
374
);
375
}
376
377
#[test]
378
fn turning_the_notification_sound_on_writes_all_like_teams() {
379
let previous = SoundSettings {
380
notification_sound: false,
381
..Default::default()
382
};
383
let merged: Value = serde_json::from_str(&merge_sound_settings(
384
&json!({}),
385
&previous,
386
&SoundSettings::default(),
387
))
388
.unwrap();
389
assert_eq!(merged, json!({"soundsSettings": {"alertSound": "All"}}));
390
}
391
392
#[test]
393
fn the_ringtone_body_lists_only_custom_ringtones() {
394
let assignments = RingtoneAssignments {
395
call_group: Ringtone::WishGranted,
396
..Default::default()
397
};
398
assert_eq!(
399
ringtone_body(&assignments),
400
json!({"assignments": {"ringToneAssignments": [
401
{"type": "CallGroup", "value": "WishGranted", "associatedEntityId": ""}
402
]}})
403
);
404
assert_eq!(
405
ringtone_body(&RingtoneAssignments::default()),
406
json!({"assignments": {"ringToneAssignments": []}})
407
);
408
}
409
410
#[test]
411
fn only_a_ringtone_change_skips_the_personal_settings() {
412
let previous = SoundSettings::default();
413
let mut updated = previous.clone();
414
updated.ringtones.regular = Ringtone::Bop;
415
assert!(!previous.personal_part_differs(&updated));
416
updated.call_and_meeting_sound = false;
417
assert!(previous.personal_part_differs(&updated));
418
}
419
}
@@ -0,0 +1,419 @@1
use serde_json::{Map, Value, json};2
use session::{Method, Request, SPACES, Scope, Session};3
4
use crate::error::{Error, Result};5
use crate::language_settings::with_headers;6
use crate::messages::{MessageTransport, SessionMessageTransport, ensure_success};7
use crate::pins::{CsaTransport, DEFAULT_REGION, SessionTransport};8
use crate::settings::UserSettings;9
use crate::sounds::{AlertSound, Ringtone, RingtoneAssignments, RingtoneCallType};10
11
const SKYPE_SCOPE: &str = "user_impersonation";12
const PERSONAL_SETTINGS_KEY: &str = "userPersonalSettings";13
const TOAST_SETTINGS: &str = "toastSettings";14
const SOUNDS_SETTINGS: &str = "soundsSettings";15
const ALERT_SOUND: &str = "alertSound";16
const ALERT_SOUND_TYPE: &str = "alertSoundType";17
const URGENT_SOUND: &str = "PlayNotificationSoundsForUrgentAndPriority";18
const URGENT_SOUND_TYPE: &str = "alertUrgentSoundType";19
const CALL_AND_MEETING_SOUND: &str = "incomingCallsAndMeetingStartSound";20
const SOUND_WHEN_BUSY: &str = "PlayNotificationSoundsWhenBusyOrInMeetings";21
const ALERT_SOUND_ON: &str = "All";22
const ON: &str = "On";23
const OFF: &str = "Off";24
const RINGTONE_ASSIGNMENTS_POINTER: &str =25
"/voiceAdminSettings/value/ringtoneSettings/assignments/ringToneAssignments";26
27
#[derive(Debug, Clone, PartialEq, Eq)]28
pub struct SoundSettings {29
pub notification_sound: bool,30
pub notification_sound_type: AlertSound,31
pub urgent_sound: bool,32
pub urgent_sound_type: AlertSound,33
pub call_and_meeting_sound: bool,34
pub sound_when_busy: bool,35
pub ringtones: RingtoneAssignments,36
}37
38
impl Default for SoundSettings {39
fn default() -> Self {40
SoundSettings {41
notification_sound: true,42
notification_sound_type: AlertSound::Default,43
urgent_sound: true,44
urgent_sound_type: AlertSound::DefaultUrgent,45
call_and_meeting_sound: true,46
sound_when_busy: true,47
ringtones: RingtoneAssignments::default(),48
}49
}50
}51
52
impl SoundSettings {53
pub fn personal_part_differs(&self, other: &SoundSettings) -> bool {54
SoundSettings {55
ringtones: other.ringtones,56
..self.clone()57
} != *other58
}59
}60
61
fn personal_settings(properties: &Value) -> Map<String, Value> {62
properties63
.get(PERSONAL_SETTINGS_KEY)64
.and_then(Value::as_str)65
.and_then(|text| serde_json::from_str::<Value>(text).ok())66
.and_then(|value| value.as_object().cloned())67
.unwrap_or_default()68
}69
70
fn text_at<'a>(settings: &'a Map<String, Value>, group: &str, field: &str) -> Option<&'a str> {71
settings.get(group)?.get(field)?.as_str()72
}73
74
pub fn parse_sound_settings(properties: &Value, aggregate: &Value) -> SoundSettings {75
let settings = personal_settings(properties);76
let defaults = SoundSettings::default();77
let switch = |group: &str, field: &str, fallback: bool| {78
text_at(&settings, group, field).map_or(fallback, |value| value != OFF)79
};80
let sound = |field: &str, fallback: AlertSound| {81
text_at(&settings, TOAST_SETTINGS, field)82
.and_then(AlertSound::from_name)83
.unwrap_or(fallback)84
};85
SoundSettings {86
notification_sound: switch(SOUNDS_SETTINGS, ALERT_SOUND, defaults.notification_sound),87
notification_sound_type: sound(ALERT_SOUND_TYPE, defaults.notification_sound_type),88
urgent_sound: switch(TOAST_SETTINGS, URGENT_SOUND, defaults.urgent_sound),89
urgent_sound_type: sound(URGENT_SOUND_TYPE, defaults.urgent_sound_type),90
call_and_meeting_sound: switch(91
SOUNDS_SETTINGS,92
CALL_AND_MEETING_SOUND,93
defaults.call_and_meeting_sound,94
),95
sound_when_busy: switch(TOAST_SETTINGS, SOUND_WHEN_BUSY, defaults.sound_when_busy),96
ringtones: parse_ringtones(aggregate),97
}98
}99
100
pub fn parse_ringtones(aggregate: &Value) -> RingtoneAssignments {101
let mut assignments = RingtoneAssignments::default();102
let entries = aggregate103
.pointer(RINGTONE_ASSIGNMENTS_POINTER)104
.and_then(Value::as_array)105
.into_iter()106
.flatten();107
for entry in entries {108
let call_type = entry109
.get("type")110
.and_then(Value::as_str)111
.and_then(RingtoneCallType::from_name);112
let ringtone = entry113
.get("value")114
.and_then(Value::as_str)115
.and_then(Ringtone::from_name);116
if let (Some(call_type), Some(ringtone)) = (call_type, ringtone) {117
assignments.set(call_type, ringtone);118
}119
}120
assignments121
}122
123
fn switch_value(on: bool) -> &'static str {124
if on { ON } else { OFF }125
}126
127
/// Writes only the fields that changed, so values rusty-teams does not know (tactile sounds) survive.128
pub fn merge_sound_settings(129
properties: &Value,130
previous: &SoundSettings,131
updated: &SoundSettings,132
) -> String {133
let mut settings = personal_settings(properties);134
let mut changes: Vec<(&str, &str, &str)> = Vec::new();135
if previous.notification_sound != updated.notification_sound {136
let value = if updated.notification_sound {137
ALERT_SOUND_ON138
} else {139
OFF140
};141
changes.push((SOUNDS_SETTINGS, ALERT_SOUND, value));142
}143
if previous.notification_sound_type != updated.notification_sound_type {144
changes.push((145
TOAST_SETTINGS,146
ALERT_SOUND_TYPE,147
updated.notification_sound_type.name(),148
));149
}150
if previous.urgent_sound != updated.urgent_sound {151
changes.push((TOAST_SETTINGS, URGENT_SOUND, switch_value(updated.urgent_sound)));152
}153
if previous.urgent_sound_type != updated.urgent_sound_type {154
changes.push((155
TOAST_SETTINGS,156
URGENT_SOUND_TYPE,157
updated.urgent_sound_type.name(),158
));159
}160
if previous.call_and_meeting_sound != updated.call_and_meeting_sound {161
changes.push((162
SOUNDS_SETTINGS,163
CALL_AND_MEETING_SOUND,164
switch_value(updated.call_and_meeting_sound),165
));166
}167
if previous.sound_when_busy != updated.sound_when_busy {168
changes.push((169
TOAST_SETTINGS,170
SOUND_WHEN_BUSY,171
switch_value(updated.sound_when_busy),172
));173
}174
for (group, field, value) in changes {175
let entry = settings176
.entry(group)177
.or_insert_with(|| Value::Object(Map::new()));178
if !entry.is_object() {179
*entry = Value::Object(Map::new());180
}181
if let Some(object) = entry.as_object_mut() {182
object.insert(field.to_owned(), Value::String(value.to_owned()));183
}184
}185
Value::Object(settings).to_string()186
}187
188
pub fn ringtone_body(assignments: &RingtoneAssignments) -> Value {189
let entries: Vec<Value> = assignments190
.custom()191
.into_iter()192
.map(|(call_type, ringtone)| {193
json!({"type": call_type.name(), "value": ringtone.name(), "associatedEntityId": ""})194
})195
.collect();196
json!({"assignments": {"ringToneAssignments": entries}})197
}198
199
pub fn aggregate_read_body() -> Value {200
json!({"voiceAdminSettings": true})201
}202
203
pub struct SoundSettingsClient<P: MessageTransport = SessionMessageTransport, M: CsaTransport = SessionTransport>204
{205
properties: UserSettings<P>,206
middle_tier: M,207
middle_tier_url: String,208
}209
210
impl SoundSettingsClient {211
pub fn new(session: &Session) -> Self {212
SoundSettingsClient::with_transports(213
UserSettings::new(session),214
SessionTransport::with_scope(session, Scope::new(SPACES, SKYPE_SCOPE)),215
DEFAULT_REGION,216
)217
}218
}219
220
impl<P: MessageTransport, M: CsaTransport> SoundSettingsClient<P, M> {221
pub fn with_transports(properties: UserSettings<P>, middle_tier: M, region: &str) -> Self {222
SoundSettingsClient {223
properties,224
middle_tier,225
middle_tier_url: format!("https://teams.cloud.microsoft/api/mt/{region}/beta"),226
}227
}228
229
pub async fn read(&self) -> Result<SoundSettings> {230
let properties = self.properties.properties().await?;231
let url = format!("{}/users/useraggregatesettings", self.middle_tier_url);232
let answer = self233
.middle_tier234
.send(with_headers(Request::with_body(235
Method::Post,236
url,237
aggregate_read_body(),238
)))239
.await?;240
ensure_success(&answer)?;241
if answer.body.get("voiceAdminSettings").is_none() {242
return Err(Error::UnexpectedAnswer("no voice settings".into()));243
}244
Ok(parse_sound_settings(&properties, &answer.body))245
}246
247
pub async fn write(248
&self,249
user_mri: &str,250
previous: &SoundSettings,251
updated: &SoundSettings,252
) -> Result<()> {253
if previous.personal_part_differs(updated) {254
let properties = self.properties.properties().await?;255
let merged = merge_sound_settings(&properties, previous, updated);256
self.properties257
.set_property(PERSONAL_SETTINGS_KEY, Value::String(merged))258
.await?;259
}260
if previous.ringtones != updated.ringtones {261
let url = format!(262
"{}/usersettings/{user_mri}/ringtonesettings",263
self.middle_tier_url264
);265
let answer = self266
.middle_tier267
.send(with_headers(Request::with_body(268
Method::Post,269
url,270
ringtone_body(&updated.ringtones),271
)))272
.await?;273
ensure_success(&answer)?;274
}275
Ok(())276
}277
}278
279
#[cfg(test)]280
mod tests {281
use super::*;282
283
fn properties(personal: Value) -> Value {284
json!({"other": "kept", PERSONAL_SETTINGS_KEY: personal.to_string()})285
}286
287
fn aggregate(assignments: Value) -> Value {288
json!({"voiceAdminSettings": {"value": {"ringtoneSettings": {"assignments": {"ringToneAssignments": assignments}}}}})289
}290
291
#[test]292
fn missing_settings_give_the_teams_defaults() {293
assert_eq!(294
parse_sound_settings(&json!({}), &json!({})),295
SoundSettings::default()296
);297
}298
299
#[test]300
fn reads_the_account_values_teams_writes() {301
let personal = json!({302
"toastSettings": {303
"alertSoundType": "Tap",304
"alertUrgentSoundType": "Alarm",305
"PlayNotificationSoundsForUrgentAndPriority": "Off",306
"PlayNotificationSoundsWhenBusyOrInMeetings": "Off"307
},308
"soundsSettings": {"alertSound": "Off", "incomingCallsAndMeetingStartSound": "Off"}309
});310
let parsed = parse_sound_settings(311
&properties(personal),312
&aggregate(json!([313
{"type": "Regular", "value": "Bop", "associatedEntityId": ""},314
{"type": "Delegate", "value": "plink"},315
{"type": "Unknown", "value": "Bop"},316
{"type": "CallGroup", "value": "Chime"}317
])),318
);319
assert_eq!(320
parsed,321
SoundSettings {322
notification_sound: false,323
notification_sound_type: AlertSound::Tap,324
urgent_sound: false,325
urgent_sound_type: AlertSound::Alarm,326
call_and_meeting_sound: false,327
sound_when_busy: false,328
ringtones: RingtoneAssignments {329
regular: Ringtone::Bop,330
delegate: Ringtone::Plink,331
..Default::default()332
},333
}334
);335
}336
337
#[test]338
fn an_unknown_sound_falls_back_to_the_default() {339
let personal = json!({"toastSettings": {"alertSoundType": "TACTILE_DEFAULT"}, "soundsSettings": {"alertSound": "All"}});340
let parsed = parse_sound_settings(&properties(personal), &json!({}));341
assert!(parsed.notification_sound);342
assert_eq!(parsed.notification_sound_type, AlertSound::Default);343
}344
345
#[test]346
fn merge_writes_only_the_changed_fields_and_keeps_the_rest() {347
let personal = json!({348
"toastSettings": {"alertSoundType": "TACTILE_DEFAULT", "Chat": true},349
"soundsSettings": {"alertSound": "All"},350
"emailSettings": {"EmailDigestDelay": "Daily"}351
});352
let previous = SoundSettings::default();353
let updated = SoundSettings {354
notification_sound: false,355
urgent_sound_type: AlertSound::Escalate,356
sound_when_busy: false,357
..previous.clone()358
};359
let merged: Value =360
serde_json::from_str(&merge_sound_settings(&properties(personal), &previous, &updated))361
.unwrap();362
assert_eq!(363
merged,364
json!({365
"toastSettings": {366
"alertSoundType": "TACTILE_DEFAULT",367
"Chat": true,368
"alertUrgentSoundType": "Escalate",369
"PlayNotificationSoundsWhenBusyOrInMeetings": "Off"370
},371
"soundsSettings": {"alertSound": "Off"},372
"emailSettings": {"EmailDigestDelay": "Daily"}373
})374
);375
}376
377
#[test]378
fn turning_the_notification_sound_on_writes_all_like_teams() {379
let previous = SoundSettings {380
notification_sound: false,381
..Default::default()382
};383
let merged: Value = serde_json::from_str(&merge_sound_settings(384
&json!({}),385
&previous,386
&SoundSettings::default(),387
))388
.unwrap();389
assert_eq!(merged, json!({"soundsSettings": {"alertSound": "All"}}));390
}391
392
#[test]393
fn the_ringtone_body_lists_only_custom_ringtones() {394
let assignments = RingtoneAssignments {395
call_group: Ringtone::WishGranted,396
..Default::default()397
};398
assert_eq!(399
ringtone_body(&assignments),400
json!({"assignments": {"ringToneAssignments": [401
{"type": "CallGroup", "value": "WishGranted", "associatedEntityId": ""}402
]}})403
);404
assert_eq!(405
ringtone_body(&RingtoneAssignments::default()),406
json!({"assignments": {"ringToneAssignments": []}})407
);408
}409
410
#[test]411
fn only_a_ringtone_change_skips_the_personal_settings() {412
let previous = SoundSettings::default();413
let mut updated = previous.clone();414
updated.ringtones.regular = Ringtone::Bop;415
assert!(!previous.personal_part_differs(&updated));416
updated.call_and_meeting_sound = false;417
assert!(previous.personal_part_differs(&updated));418
}419
}@@ -0,0 +1,352 @@
1
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
2
pub enum Ringtone {
3
#[default]
4
Ring,
5
Beep,
6
Bop,
7
Bounce,
8
Bubbles,
9
BubblesLoud,
10
DripDrop,
11
Eureka,
12
Flutter,
13
HighScore,
14
NextLevel,
15
Plink,
16
Remix,
17
RingRing,
18
Ripple,
19
Spacetime,
20
WishGranted,
21
Wobble,
22
}
23
24
impl Ringtone {
25
pub const ALL: [Ringtone; 18] = [
26
Ringtone::Ring,
27
Ringtone::Beep,
28
Ringtone::Bop,
29
Ringtone::Bounce,
30
Ringtone::Bubbles,
31
Ringtone::BubblesLoud,
32
Ringtone::DripDrop,
33
Ringtone::Eureka,
34
Ringtone::Flutter,
35
Ringtone::HighScore,
36
Ringtone::NextLevel,
37
Ringtone::Plink,
38
Ringtone::Remix,
39
Ringtone::RingRing,
40
Ringtone::Ripple,
41
Ringtone::Spacetime,
42
Ringtone::WishGranted,
43
Ringtone::Wobble,
44
];
45
46
pub fn name(self) -> &'static str {
47
match self {
48
Ringtone::Ring => "Ring",
49
Ringtone::Beep => "Beep",
50
Ringtone::Bop => "Bop",
51
Ringtone::Bounce => "Bounce",
52
Ringtone::Bubbles => "Bubbles",
53
Ringtone::BubblesLoud => "BubblesLoud",
54
Ringtone::DripDrop => "DripDrop",
55
Ringtone::Eureka => "Eureka",
56
Ringtone::Flutter => "Flutter",
57
Ringtone::HighScore => "HighScore",
58
Ringtone::NextLevel => "NextLevel",
59
Ringtone::Plink => "Plink",
60
Ringtone::Remix => "Remix",
61
Ringtone::RingRing => "RingRing",
62
Ringtone::Ripple => "Ripple",
63
Ringtone::Spacetime => "Spacetime",
64
Ringtone::WishGranted => "WishGranted",
65
Ringtone::Wobble => "Wobble",
66
}
67
}
68
69
pub fn label(self) -> &'static str {
70
match self {
71
Ringtone::Ring => "Default",
72
Ringtone::BubblesLoud => "Bubbles (Loud)",
73
Ringtone::DripDrop => "Drip Drop",
74
Ringtone::HighScore => "High Score",
75
Ringtone::NextLevel => "Next Level",
76
Ringtone::RingRing => "Ring Ring",
77
Ringtone::WishGranted => "Wish Granted",
78
other => other.name(),
79
}
80
}
81
82
pub fn file_name(self) -> &'static str {
83
match self {
84
Ringtone::Ring => "ring.mp3",
85
Ringtone::Beep => "beep.mp3",
86
Ringtone::Bop => "bop.mp3",
87
Ringtone::Bounce => "bounce.mp3",
88
Ringtone::Bubbles => "bubbles.mp3",
89
Ringtone::BubblesLoud => "bubblesloud.mp3",
90
Ringtone::DripDrop => "dripdrop.mp3",
91
Ringtone::Eureka => "eureka.mp3",
92
Ringtone::Flutter => "flutter.mp3",
93
Ringtone::HighScore => "highscore.mp3",
94
Ringtone::NextLevel => "nextlevel.mp3",
95
Ringtone::Plink => "plink.mp3",
96
Ringtone::Remix => "remix.mp3",
97
Ringtone::RingRing => "ringring.mp3",
98
Ringtone::Ripple => "ripple.mp3",
99
Ringtone::Spacetime => "spacetime.mp3",
100
Ringtone::WishGranted => "wishgranted.mp3",
101
Ringtone::Wobble => "wobble.mp3",
102
}
103
}
104
105
pub fn from_name(name: &str) -> Option<Ringtone> {
106
Ringtone::ALL
107
.into_iter()
108
.find(|ringtone| ringtone.name().eq_ignore_ascii_case(name))
109
}
110
}
111
112
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
113
pub enum RingtoneCallType {
114
Regular,
115
CallGroup,
116
CallQueue,
117
Delegate,
118
}
119
120
impl RingtoneCallType {
121
pub const ALL: [RingtoneCallType; 4] = [
122
RingtoneCallType::Regular,
123
RingtoneCallType::CallGroup,
124
RingtoneCallType::CallQueue,
125
RingtoneCallType::Delegate,
126
];
127
128
pub fn name(self) -> &'static str {
129
match self {
130
RingtoneCallType::Regular => "Regular",
131
RingtoneCallType::CallGroup => "CallGroup",
132
RingtoneCallType::CallQueue => "CallQueue",
133
RingtoneCallType::Delegate => "Delegate",
134
}
135
}
136
137
pub fn label(self) -> &'static str {
138
match self {
139
RingtoneCallType::Regular => "Calls for you",
140
RingtoneCallType::CallGroup => "Forwarded calls",
141
RingtoneCallType::CallQueue => "Call queue calls",
142
RingtoneCallType::Delegate => "Delegated calls",
143
}
144
}
145
146
pub fn from_name(name: &str) -> Option<RingtoneCallType> {
147
RingtoneCallType::ALL
148
.into_iter()
149
.find(|call_type| call_type.name() == name)
150
}
151
}
152
153
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
154
pub struct RingtoneAssignments {
155
pub regular: Ringtone,
156
pub call_group: Ringtone,
157
pub call_queue: Ringtone,
158
pub delegate: Ringtone,
159
}
160
161
impl RingtoneAssignments {
162
pub fn get(&self, call_type: RingtoneCallType) -> Ringtone {
163
match call_type {
164
RingtoneCallType::Regular => self.regular,
165
RingtoneCallType::CallGroup => self.call_group,
166
RingtoneCallType::CallQueue => self.call_queue,
167
RingtoneCallType::Delegate => self.delegate,
168
}
169
}
170
171
pub fn set(&mut self, call_type: RingtoneCallType, ringtone: Ringtone) {
172
match call_type {
173
RingtoneCallType::Regular => self.regular = ringtone,
174
RingtoneCallType::CallGroup => self.call_group = ringtone,
175
RingtoneCallType::CallQueue => self.call_queue = ringtone,
176
RingtoneCallType::Delegate => self.delegate = ringtone,
177
}
178
}
179
180
pub fn custom(&self) -> Vec<(RingtoneCallType, Ringtone)> {
181
RingtoneCallType::ALL
182
.into_iter()
183
.map(|call_type| (call_type, self.get(call_type)))
184
.filter(|(_, ringtone)| *ringtone != Ringtone::Ring)
185
.collect()
186
}
187
}
188
189
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
190
pub enum AlertSound {
191
Default,
192
Vibe,
193
Nudge,
194
Tap,
195
Flick,
196
Pluck,
197
Summon,
198
Ping,
199
DefaultUrgent,
200
Prioritize,
201
Escalate,
202
Alarm,
203
}
204
205
impl AlertSound {
206
pub const NORMAL: [AlertSound; 8] = [
207
AlertSound::Default,
208
AlertSound::Vibe,
209
AlertSound::Nudge,
210
AlertSound::Tap,
211
AlertSound::Flick,
212
AlertSound::Pluck,
213
AlertSound::Summon,
214
AlertSound::Ping,
215
];
216
pub const URGENT: [AlertSound; 4] = [
217
AlertSound::DefaultUrgent,
218
AlertSound::Prioritize,
219
AlertSound::Escalate,
220
AlertSound::Alarm,
221
];
222
223
pub fn name(self) -> &'static str {
224
match self {
225
AlertSound::Default => "Default",
226
AlertSound::Vibe => "Vibe",
227
AlertSound::Nudge => "Nudge",
228
AlertSound::Tap => "Tap",
229
AlertSound::Flick => "Flick",
230
AlertSound::Pluck => "Pluck",
231
AlertSound::Summon => "Summon",
232
AlertSound::Ping => "Ping",
233
AlertSound::DefaultUrgent => "DefaultUrgent",
234
AlertSound::Prioritize => "Prioritize",
235
AlertSound::Escalate => "Escalate",
236
AlertSound::Alarm => "Alarm",
237
}
238
}
239
240
pub fn label(self) -> &'static str {
241
match self {
242
AlertSound::DefaultUrgent => "Default",
243
other => other.name(),
244
}
245
}
246
247
pub fn file_name(self) -> &'static str {
248
match self {
249
AlertSound::Default | AlertSound::DefaultUrgent => {
250
"00_teams_basic_notification_r4_default.mp3"
251
}
252
AlertSound::Vibe => "a2_teams_basic_notification_r4_vibe.mp3",
253
AlertSound::Nudge => "a3_teams_basic_notification_r4_nudge.mp3",
254
AlertSound::Tap => "a4_teams_basic_notification_r4_tap.mp3",
255
AlertSound::Flick => "a5_teams_basic_notification_r4_flick.mp3",
256
AlertSound::Pluck => "a6_teams_basic_notification_r4_pluck.mp3",
257
AlertSound::Summon => "a7_teams_basic_notification_r4_summon.mp3",
258
AlertSound::Ping => "a8_teams_basic_notification_r4_ping.mp3",
259
AlertSound::Prioritize => "b2_teams_urgent_notification_r4_prioritize.mp3",
260
AlertSound::Escalate => "b3_teams_urgent_notification_r4_escalate.mp3",
261
AlertSound::Alarm => "b4_teams_urgent_notification_r4_alarm.mp3",
262
}
263
}
264
265
pub fn from_name(name: &str) -> Option<AlertSound> {
266
AlertSound::NORMAL
267
.into_iter()
268
.chain(AlertSound::URGENT)
269
.find(|sound| sound.name() == name)
270
}
271
}
272
273
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274
pub enum CallTone {
275
OutgoingRinging,
276
Reconnecting,
277
MeetingJoined,
278
CallEnded,
279
MeetingLeft,
280
MeetingReminder,
281
}
282
283
impl CallTone {
284
pub const ALL: [CallTone; 6] = [
285
CallTone::OutgoingRinging,
286
CallTone::Reconnecting,
287
CallTone::MeetingJoined,
288
CallTone::CallEnded,
289
CallTone::MeetingLeft,
290
CallTone::MeetingReminder,
291
];
292
293
pub fn file_name(self) -> &'static str {
294
match self {
295
CallTone::OutgoingRinging => "Teams_Call_Ringing.mp3",
296
CallTone::Reconnecting => "Teams_Call_Reconnecting.mp3",
297
CallTone::MeetingJoined => "Teams_Meet_Up_Jump_In.mp3",
298
CallTone::CallEnded => "Teams_Call_Ended.mp3",
299
CallTone::MeetingLeft => "Teams_Meet_Up_Leave.mp3",
300
CallTone::MeetingReminder => "Teams_Meet_Up_Reminder.mp3",
301
}
302
}
303
}
304
305
#[cfg(test)]
306
mod tests {
307
use super::*;
308
309
#[test]
310
fn ringtone_names_round_trip_and_files_are_the_lowercase_name() {
311
for ringtone in Ringtone::ALL {
312
assert_eq!(Ringtone::from_name(ringtone.name()), Some(ringtone));
313
assert_eq!(
314
ringtone.file_name(),
315
format!("{}.mp3", ringtone.name().to_lowercase())
316
);
317
}
318
assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));
319
assert_eq!(Ringtone::from_name("Chime"), None);
320
assert_eq!(Ringtone::Ring.label(), "Default");
321
}
322
323
#[test]
324
fn assignments_list_only_the_types_that_do_not_ring_the_default() {
325
let mut assignments = RingtoneAssignments::default();
326
assert!(assignments.custom().is_empty());
327
assignments.set(RingtoneCallType::Delegate, Ringtone::Plink);
328
assignments.set(RingtoneCallType::Regular, Ringtone::Bop);
329
assert_eq!(
330
assignments.custom(),
331
vec![
332
(RingtoneCallType::Regular, Ringtone::Bop),
333
(RingtoneCallType::Delegate, Ringtone::Plink)
334
]
335
);
336
assert_eq!(assignments.get(RingtoneCallType::CallQueue), Ringtone::Ring);
337
}
338
339
#[test]
340
fn alert_sounds_round_trip_and_both_defaults_share_one_file() {
341
for sound in AlertSound::NORMAL.into_iter().chain(AlertSound::URGENT) {
342
assert_eq!(AlertSound::from_name(sound.name()), Some(sound));
343
assert!(sound.file_name().ends_with(".mp3"));
344
}
345
assert_eq!(
346
AlertSound::Default.file_name(),
347
AlertSound::DefaultUrgent.file_name()
348
);
349
assert_eq!(AlertSound::DefaultUrgent.label(), "Default");
350
assert_eq!(AlertSound::from_name("TACTILE_DEFAULT"), None);
351
}
352
}
@@ -0,0 +1,352 @@1
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]2
pub enum Ringtone {3
#[default]4
Ring,5
Beep,6
Bop,7
Bounce,8
Bubbles,9
BubblesLoud,10
DripDrop,11
Eureka,12
Flutter,13
HighScore,14
NextLevel,15
Plink,16
Remix,17
RingRing,18
Ripple,19
Spacetime,20
WishGranted,21
Wobble,22
}23
24
impl Ringtone {25
pub const ALL: [Ringtone; 18] = [26
Ringtone::Ring,27
Ringtone::Beep,28
Ringtone::Bop,29
Ringtone::Bounce,30
Ringtone::Bubbles,31
Ringtone::BubblesLoud,32
Ringtone::DripDrop,33
Ringtone::Eureka,34
Ringtone::Flutter,35
Ringtone::HighScore,36
Ringtone::NextLevel,37
Ringtone::Plink,38
Ringtone::Remix,39
Ringtone::RingRing,40
Ringtone::Ripple,41
Ringtone::Spacetime,42
Ringtone::WishGranted,43
Ringtone::Wobble,44
];45
46
pub fn name(self) -> &'static str {47
match self {48
Ringtone::Ring => "Ring",49
Ringtone::Beep => "Beep",50
Ringtone::Bop => "Bop",51
Ringtone::Bounce => "Bounce",52
Ringtone::Bubbles => "Bubbles",53
Ringtone::BubblesLoud => "BubblesLoud",54
Ringtone::DripDrop => "DripDrop",55
Ringtone::Eureka => "Eureka",56
Ringtone::Flutter => "Flutter",57
Ringtone::HighScore => "HighScore",58
Ringtone::NextLevel => "NextLevel",59
Ringtone::Plink => "Plink",60
Ringtone::Remix => "Remix",61
Ringtone::RingRing => "RingRing",62
Ringtone::Ripple => "Ripple",63
Ringtone::Spacetime => "Spacetime",64
Ringtone::WishGranted => "WishGranted",65
Ringtone::Wobble => "Wobble",66
}67
}68
69
pub fn label(self) -> &'static str {70
match self {71
Ringtone::Ring => "Default",72
Ringtone::BubblesLoud => "Bubbles (Loud)",73
Ringtone::DripDrop => "Drip Drop",74
Ringtone::HighScore => "High Score",75
Ringtone::NextLevel => "Next Level",76
Ringtone::RingRing => "Ring Ring",77
Ringtone::WishGranted => "Wish Granted",78
other => other.name(),79
}80
}81
82
pub fn file_name(self) -> &'static str {83
match self {84
Ringtone::Ring => "ring.mp3",85
Ringtone::Beep => "beep.mp3",86
Ringtone::Bop => "bop.mp3",87
Ringtone::Bounce => "bounce.mp3",88
Ringtone::Bubbles => "bubbles.mp3",89
Ringtone::BubblesLoud => "bubblesloud.mp3",90
Ringtone::DripDrop => "dripdrop.mp3",91
Ringtone::Eureka => "eureka.mp3",92
Ringtone::Flutter => "flutter.mp3",93
Ringtone::HighScore => "highscore.mp3",94
Ringtone::NextLevel => "nextlevel.mp3",95
Ringtone::Plink => "plink.mp3",96
Ringtone::Remix => "remix.mp3",97
Ringtone::RingRing => "ringring.mp3",98
Ringtone::Ripple => "ripple.mp3",99
Ringtone::Spacetime => "spacetime.mp3",100
Ringtone::WishGranted => "wishgranted.mp3",101
Ringtone::Wobble => "wobble.mp3",102
}103
}104
105
pub fn from_name(name: &str) -> Option<Ringtone> {106
Ringtone::ALL107
.into_iter()108
.find(|ringtone| ringtone.name().eq_ignore_ascii_case(name))109
}110
}111
112
#[derive(Debug, Clone, Copy, PartialEq, Eq)]113
pub enum RingtoneCallType {114
Regular,115
CallGroup,116
CallQueue,117
Delegate,118
}119
120
impl RingtoneCallType {121
pub const ALL: [RingtoneCallType; 4] = [122
RingtoneCallType::Regular,123
RingtoneCallType::CallGroup,124
RingtoneCallType::CallQueue,125
RingtoneCallType::Delegate,126
];127
128
pub fn name(self) -> &'static str {129
match self {130
RingtoneCallType::Regular => "Regular",131
RingtoneCallType::CallGroup => "CallGroup",132
RingtoneCallType::CallQueue => "CallQueue",133
RingtoneCallType::Delegate => "Delegate",134
}135
}136
137
pub fn label(self) -> &'static str {138
match self {139
RingtoneCallType::Regular => "Calls for you",140
RingtoneCallType::CallGroup => "Forwarded calls",141
RingtoneCallType::CallQueue => "Call queue calls",142
RingtoneCallType::Delegate => "Delegated calls",143
}144
}145
146
pub fn from_name(name: &str) -> Option<RingtoneCallType> {147
RingtoneCallType::ALL148
.into_iter()149
.find(|call_type| call_type.name() == name)150
}151
}152
153
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]154
pub struct RingtoneAssignments {155
pub regular: Ringtone,156
pub call_group: Ringtone,157
pub call_queue: Ringtone,158
pub delegate: Ringtone,159
}160
161
impl RingtoneAssignments {162
pub fn get(&self, call_type: RingtoneCallType) -> Ringtone {163
match call_type {164
RingtoneCallType::Regular => self.regular,165
RingtoneCallType::CallGroup => self.call_group,166
RingtoneCallType::CallQueue => self.call_queue,167
RingtoneCallType::Delegate => self.delegate,168
}169
}170
171
pub fn set(&mut self, call_type: RingtoneCallType, ringtone: Ringtone) {172
match call_type {173
RingtoneCallType::Regular => self.regular = ringtone,174
RingtoneCallType::CallGroup => self.call_group = ringtone,175
RingtoneCallType::CallQueue => self.call_queue = ringtone,176
RingtoneCallType::Delegate => self.delegate = ringtone,177
}178
}179
180
pub fn custom(&self) -> Vec<(RingtoneCallType, Ringtone)> {181
RingtoneCallType::ALL182
.into_iter()183
.map(|call_type| (call_type, self.get(call_type)))184
.filter(|(_, ringtone)| *ringtone != Ringtone::Ring)185
.collect()186
}187
}188
189
#[derive(Debug, Clone, Copy, PartialEq, Eq)]190
pub enum AlertSound {191
Default,192
Vibe,193
Nudge,194
Tap,195
Flick,196
Pluck,197
Summon,198
Ping,199
DefaultUrgent,200
Prioritize,201
Escalate,202
Alarm,203
}204
205
impl AlertSound {206
pub const NORMAL: [AlertSound; 8] = [207
AlertSound::Default,208
AlertSound::Vibe,209
AlertSound::Nudge,210
AlertSound::Tap,211
AlertSound::Flick,212
AlertSound::Pluck,213
AlertSound::Summon,214
AlertSound::Ping,215
];216
pub const URGENT: [AlertSound; 4] = [217
AlertSound::DefaultUrgent,218
AlertSound::Prioritize,219
AlertSound::Escalate,220
AlertSound::Alarm,221
];222
223
pub fn name(self) -> &'static str {224
match self {225
AlertSound::Default => "Default",226
AlertSound::Vibe => "Vibe",227
AlertSound::Nudge => "Nudge",228
AlertSound::Tap => "Tap",229
AlertSound::Flick => "Flick",230
AlertSound::Pluck => "Pluck",231
AlertSound::Summon => "Summon",232
AlertSound::Ping => "Ping",233
AlertSound::DefaultUrgent => "DefaultUrgent",234
AlertSound::Prioritize => "Prioritize",235
AlertSound::Escalate => "Escalate",236
AlertSound::Alarm => "Alarm",237
}238
}239
240
pub fn label(self) -> &'static str {241
match self {242
AlertSound::DefaultUrgent => "Default",243
other => other.name(),244
}245
}246
247
pub fn file_name(self) -> &'static str {248
match self {249
AlertSound::Default | AlertSound::DefaultUrgent => {250
"00_teams_basic_notification_r4_default.mp3"251
}252
AlertSound::Vibe => "a2_teams_basic_notification_r4_vibe.mp3",253
AlertSound::Nudge => "a3_teams_basic_notification_r4_nudge.mp3",254
AlertSound::Tap => "a4_teams_basic_notification_r4_tap.mp3",255
AlertSound::Flick => "a5_teams_basic_notification_r4_flick.mp3",256
AlertSound::Pluck => "a6_teams_basic_notification_r4_pluck.mp3",257
AlertSound::Summon => "a7_teams_basic_notification_r4_summon.mp3",258
AlertSound::Ping => "a8_teams_basic_notification_r4_ping.mp3",259
AlertSound::Prioritize => "b2_teams_urgent_notification_r4_prioritize.mp3",260
AlertSound::Escalate => "b3_teams_urgent_notification_r4_escalate.mp3",261
AlertSound::Alarm => "b4_teams_urgent_notification_r4_alarm.mp3",262
}263
}264
265
pub fn from_name(name: &str) -> Option<AlertSound> {266
AlertSound::NORMAL267
.into_iter()268
.chain(AlertSound::URGENT)269
.find(|sound| sound.name() == name)270
}271
}272
273
#[derive(Debug, Clone, Copy, PartialEq, Eq)]274
pub enum CallTone {275
OutgoingRinging,276
Reconnecting,277
MeetingJoined,278
CallEnded,279
MeetingLeft,280
MeetingReminder,281
}282
283
impl CallTone {284
pub const ALL: [CallTone; 6] = [285
CallTone::OutgoingRinging,286
CallTone::Reconnecting,287
CallTone::MeetingJoined,288
CallTone::CallEnded,289
CallTone::MeetingLeft,290
CallTone::MeetingReminder,291
];292
293
pub fn file_name(self) -> &'static str {294
match self {295
CallTone::OutgoingRinging => "Teams_Call_Ringing.mp3",296
CallTone::Reconnecting => "Teams_Call_Reconnecting.mp3",297
CallTone::MeetingJoined => "Teams_Meet_Up_Jump_In.mp3",298
CallTone::CallEnded => "Teams_Call_Ended.mp3",299
CallTone::MeetingLeft => "Teams_Meet_Up_Leave.mp3",300
CallTone::MeetingReminder => "Teams_Meet_Up_Reminder.mp3",301
}302
}303
}304
305
#[cfg(test)]306
mod tests {307
use super::*;308
309
#[test]310
fn ringtone_names_round_trip_and_files_are_the_lowercase_name() {311
for ringtone in Ringtone::ALL {312
assert_eq!(Ringtone::from_name(ringtone.name()), Some(ringtone));313
assert_eq!(314
ringtone.file_name(),315
format!("{}.mp3", ringtone.name().to_lowercase())316
);317
}318
assert_eq!(Ringtone::from_name("wishgranted"), Some(Ringtone::WishGranted));319
assert_eq!(Ringtone::from_name("Chime"), None);320
assert_eq!(Ringtone::Ring.label(), "Default");321
}322
323
#[test]324
fn assignments_list_only_the_types_that_do_not_ring_the_default() {325
let mut assignments = RingtoneAssignments::default();326
assert!(assignments.custom().is_empty());327
assignments.set(RingtoneCallType::Delegate, Ringtone::Plink);328
assignments.set(RingtoneCallType::Regular, Ringtone::Bop);329
assert_eq!(330
assignments.custom(),331
vec![332
(RingtoneCallType::Regular, Ringtone::Bop),333
(RingtoneCallType::Delegate, Ringtone::Plink)334
]335
);336
assert_eq!(assignments.get(RingtoneCallType::CallQueue), Ringtone::Ring);337
}338
339
#[test]340
fn alert_sounds_round_trip_and_both_defaults_share_one_file() {341
for sound in AlertSound::NORMAL.into_iter().chain(AlertSound::URGENT) {342
assert_eq!(AlertSound::from_name(sound.name()), Some(sound));343
assert!(sound.file_name().ends_with(".mp3"));344
}345
assert_eq!(346
AlertSound::Default.file_name(),347
AlertSound::DefaultUrgent.file_name()348
);349
assert_eq!(AlertSound::DefaultUrgent.label(), "Default");350
assert_eq!(AlertSound::from_name("TACTILE_DEFAULT"), None);351
}352
}@@ -6,6 +6,7 @@ use chatsvc::{
6
6
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,
7
7
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,
8
8
};
9
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};
9
10
use chrono::{DateTime, Utc};
10
11
use graph::{
11
12
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,
@@ -415,6 +416,19 @@ pub trait Remote {
415
416
Err(Error::Unsupported("recording policy"))
416
417
}
417
418
419
async fn sound_settings(&self) -> Result<SoundSettings> {
420
Err(Error::Unsupported("sound settings"))
421
}
422
423
async fn save_sound_settings(
424
&self,
425
_user_mri: &str,
426
_previous: &SoundSettings,
427
_updated: &SoundSettings,
428
) -> Result<()> {
429
Err(Error::Unsupported("sound settings"))
430
}
431
418
432
async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {
419
433
Err(Error::Unsupported("GIF search"))
420
434
}
@@ -1050,6 +1064,21 @@ impl Remote for Graph {
1050
1064
.await?)
1051
1065
}
1052
1066
1067
async fn sound_settings(&self) -> Result<SoundSettings> {
1068
Ok(SoundSettingsClient::new(self.session()).read().await?)
1069
}
1070
1071
async fn save_sound_settings(
1072
&self,
1073
user_mri: &str,
1074
previous: &SoundSettings,
1075
updated: &SoundSettings,
1076
) -> Result<()> {
1077
Ok(SoundSettingsClient::new(self.session())
1078
.write(user_mri, previous, updated)
1079
.await?)
1080
}
1081
1053
1082
async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {
1054
1083
Ok(Gifs::new(self.session()).search(query).await?)
1055
1084
}
@@ -6,6 +6,7 @@ use chatsvc::{6
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,6
Receipts, RecordingPolicy, SavedMessage, ScheduledDraft, ScheduledDrafts, StatusNote, TranslateRequest,7
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,7
Translation, TranslationTrigger, Translator, WindowDirection, WorkLocationKind,8
};8
};9
use chatsvc::sound_settings::{SoundSettings, SoundSettingsClient};9
use chrono::{DateTime, Utc};10
use chrono::{DateTime, Utc};10
use graph::{11
use graph::{11
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,12
Channel, Chat, DriveEntry, DriveFolder, Graph, Member, Message, MessageExtras, MessageTarget,@@ -415,6 +416,19 @@ pub trait Remote {415
Err(Error::Unsupported("recording policy"))416
Err(Error::Unsupported("recording policy"))416
}417
}417
418
419
async fn sound_settings(&self) -> Result<SoundSettings> {420
Err(Error::Unsupported("sound settings"))421
}422
423
async fn save_sound_settings(424
&self,425
_user_mri: &str,426
_previous: &SoundSettings,427
_updated: &SoundSettings,428
) -> Result<()> {429
Err(Error::Unsupported("sound settings"))430
}431
418
async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {432
async fn search_gifs(&self, _query: &str) -> Result<Vec<Gif>> {419
Err(Error::Unsupported("GIF search"))433
Err(Error::Unsupported("GIF search"))420
}434
}@@ -1050,6 +1064,21 @@ impl Remote for Graph {1050
.await?)1064
.await?)1051
}1065
}1052
1066
1067
async fn sound_settings(&self) -> Result<SoundSettings> {1068
Ok(SoundSettingsClient::new(self.session()).read().await?)1069
}1070
1071
async fn save_sound_settings(1072
&self,1073
user_mri: &str,1074
previous: &SoundSettings,1075
updated: &SoundSettings,1076
) -> Result<()> {1077
Ok(SoundSettingsClient::new(self.session())1078
.write(user_mri, previous, updated)1079
.await?)1080
}1081
1053
async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {1082
async fn search_gifs(&self, query: &str) -> Result<Vec<Gif>> {1054
Ok(Gifs::new(self.session()).search(query).await?)1083
Ok(Gifs::new(self.session()).search(query).await?)1055
}1084
}@@ -4,6 +4,7 @@ use chatsvc::{
4
4
ConversationRef, Language, LanguageSettings, MAX_TRANSLATE_BATCH, MessageLanguage,
5
5
TranslateRequest, Translation, TranslationTrigger,
6
6
};
7
use chatsvc::sound_settings::SoundSettings;
7
8
use serde_json::Value;
8
9
9
10
use crate::engine::{Conversation, SyncEngine};
@@ -125,4 +126,19 @@ impl<R: Remote> SyncEngine<R> {
125
126
pub async fn patch_language_settings(&self, patch: Value) -> Result<()> {
126
127
self.remote.patch_language_settings(patch).await
127
128
}
129
130
pub async fn sound_settings(&self) -> Result<SoundSettings> {
131
self.remote.sound_settings().await
132
}
133
134
pub async fn save_sound_settings(
135
&self,
136
user_mri: &str,
137
previous: &SoundSettings,
138
updated: &SoundSettings,
139
) -> Result<()> {
140
self.remote
141
.save_sound_settings(user_mri, previous, updated)
142
.await
143
}
128
144
}
@@ -4,6 +4,7 @@ use chatsvc::{4
ConversationRef, Language, LanguageSettings, MAX_TRANSLATE_BATCH, MessageLanguage,4
ConversationRef, Language, LanguageSettings, MAX_TRANSLATE_BATCH, MessageLanguage,5
TranslateRequest, Translation, TranslationTrigger,5
TranslateRequest, Translation, TranslationTrigger,6
};6
};7
use chatsvc::sound_settings::SoundSettings;7
use serde_json::Value;8
use serde_json::Value;8
9
9
use crate::engine::{Conversation, SyncEngine};10
use crate::engine::{Conversation, SyncEngine};@@ -125,4 +126,19 @@ impl<R: Remote> SyncEngine<R> {125
pub async fn patch_language_settings(&self, patch: Value) -> Result<()> {126
pub async fn patch_language_settings(&self, patch: Value) -> Result<()> {126
self.remote.patch_language_settings(patch).await127
self.remote.patch_language_settings(patch).await127
}128
}129
130
pub async fn sound_settings(&self) -> Result<SoundSettings> {131
self.remote.sound_settings().await132
}133
134
pub async fn save_sound_settings(135
&self,136
user_mri: &str,137
previous: &SoundSettings,138
updated: &SoundSettings,139
) -> Result<()> {140
self.remote141
.save_sound_settings(user_mri, previous, updated)142
.await143
}128
}144
}