fix(calls): review findings - mini window repaints, 30 fps camera format, preview vs call camera, group call reactions
- mini call window observes CallMedia, so video and timer keep moving - camera picks a 30 fps NV12/YUYV format from the device list before falling back - Settings camera preview pauses while the call has the camera on; picks are saved - hand and reactions back in group calls, hidden only in 1:1 and the test call - background preview ignores stale image loads; mini window clamps to its own monitor - calendar refresh nudges inside the 30 s gap are postponed, not dropped - Meet now ignores clicks while the meeting is being created - refresh_folders reports both errors; test for layout refresh when folders fail - Join button appears on time; overlay timer idles at 1 s without a call Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -122,6 +122,8 @@ pub struct AppState {
122
122
pub call_count: u64,
123
123
pub call_share_sound: bool,
124
124
pub call_background: crate::call::BackgroundPick,
125
pub call_camera: calling::DeviceChoice,
126
pub meet_now_pending: bool,
125
127
pub call_backgrounds: crate::call::BackgroundLibrary,
126
128
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
127
129
pub rings: Rings,
@@ -221,6 +223,8 @@ impl AppState {
221
223
call_count: 0,
222
224
call_share_sound: false,
223
225
call_background: crate::call::BackgroundPick::None,
226
call_camera: calling::DeviceChoice::SystemDefault,
227
meet_now_pending: false,
224
228
call_backgrounds: if mode.demo {
225
229
crate::call::demo_library()
226
230
} else {
@@ -236,6 +240,7 @@ impl AppState {
236
240
state.collapsed = state.load_collapsed();
237
241
state.call_share_sound = crate::call::load_share_sound(&state.store);
238
242
state.call_background = crate::call::load_background(&state.store);
243
state.call_camera = crate::call::load_camera(&state.store);
239
244
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
240
245
state.load_cached_translation_settings();
241
246
if !mode.demo {
@@ -122,6 +122,8 @@ pub struct AppState {122
pub call_count: u64,122
pub call_count: u64,123
pub call_share_sound: bool,123
pub call_share_sound: bool,124
pub call_background: crate::call::BackgroundPick,124
pub call_background: crate::call::BackgroundPick,125
pub call_camera: calling::DeviceChoice,126
pub meet_now_pending: bool,125
pub call_backgrounds: crate::call::BackgroundLibrary,127
pub call_backgrounds: crate::call::BackgroundLibrary,126
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,128
pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,127
pub rings: Rings,129
pub rings: Rings,@@ -221,6 +223,8 @@ impl AppState {221
call_count: 0,223
call_count: 0,222
call_share_sound: false,224
call_share_sound: false,223
call_background: crate::call::BackgroundPick::None,225
call_background: crate::call::BackgroundPick::None,226
call_camera: calling::DeviceChoice::SystemDefault,227
meet_now_pending: false,224
call_backgrounds: if mode.demo {228
call_backgrounds: if mode.demo {225
crate::call::demo_library()229
crate::call::demo_library()226
} else {230
} else {@@ -236,6 +240,7 @@ impl AppState {236
state.collapsed = state.load_collapsed();240
state.collapsed = state.load_collapsed();237
state.call_share_sound = crate::call::load_share_sound(&state.store);241
state.call_share_sound = crate::call::load_share_sound(&state.store);238
state.call_background = crate::call::load_background(&state.store);242
state.call_background = crate::call::load_background(&state.store);243
state.call_camera = crate::call::load_camera(&state.store);239
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);244
state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);240
state.load_cached_translation_settings();245
state.load_cached_translation_settings();241
if !mode.demo {246
if !mode.demo {@@ -339,19 +339,23 @@ async fn calendar_loop(session: Session, events: EventSender) {
339
339
let _ = events.send(BackendEvent::CalendarNudge(nudge));
340
340
let mut interval = tokio::time::interval(CALENDAR_INTERVAL);
341
341
let mut last_fetch: Option<tokio::time::Instant> = None;
342
let mut deferred_fetch: Option<tokio::time::Instant> = None;
342
343
loop {
343
344
tokio::select! {
344
345
_ = interval.tick() => {}
346
_ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {}
345
347
nudge = nudges.recv() => {
346
348
if nudge.is_none() {
347
349
return;
348
350
}
349
351
while nudges.try_recv().is_ok() {}
350
if last_fetch.is_some_and(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
352
if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {
353
deferred_fetch = Some(fetched + CALENDAR_MIN_GAP);
351
354
continue;
352
355
}
353
356
}
354
357
}
358
deferred_fetch = None;
355
359
last_fetch = Some(tokio::time::Instant::now());
356
360
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());
357
361
match calendar.calendar_view(start, end).await {
@@ -339,19 +339,23 @@ async fn calendar_loop(session: Session, events: EventSender) {339
let _ = events.send(BackendEvent::CalendarNudge(nudge));339
let _ = events.send(BackendEvent::CalendarNudge(nudge));340
let mut interval = tokio::time::interval(CALENDAR_INTERVAL);340
let mut interval = tokio::time::interval(CALENDAR_INTERVAL);341
let mut last_fetch: Option<tokio::time::Instant> = None;341
let mut last_fetch: Option<tokio::time::Instant> = None;342
let mut deferred_fetch: Option<tokio::time::Instant> = None;342
loop {343
loop {343
tokio::select! {344
tokio::select! {344
_ = interval.tick() => {}345
_ = interval.tick() => {}346
_ = tokio::time::sleep_until(deferred_fetch.unwrap_or_else(tokio::time::Instant::now)), if deferred_fetch.is_some() => {}345
nudge = nudges.recv() => {347
nudge = nudges.recv() => {346
if nudge.is_none() {348
if nudge.is_none() {347
return;349
return;348
}350
}349
while nudges.try_recv().is_ok() {}351
while nudges.try_recv().is_ok() {}350
if last_fetch.is_some_and(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {352
if let Some(fetched) = last_fetch.filter(|fetched| fetched.elapsed() < CALENDAR_MIN_GAP) {353
deferred_fetch = Some(fetched + CALENDAR_MIN_GAP);351
continue;354
continue;352
}355
}353
}356
}354
}357
}358
deferred_fetch = None;355
last_fetch = Some(tokio::time::Instant::now());359
last_fetch = Some(tokio::time::Instant::now());356
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());360
let (start, end) = fetch_window(Utc::now(), Local::now().offset().fix());357
match calendar.calendar_view(start, end).await {361
match calendar.calendar_view(start, end).await {@@ -30,11 +30,27 @@ const DEMO_SMALL_MEETING: usize = 4;
30
30
const DEMO_LIVE_MINUTES: i64 = 60;
31
31
const ORGID_PREFIX: &str = "8:orgid:";
32
32
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";
33
const CAMERA_META_KEY: &str = "call_camera";
34
const DEFAULT_CAMERA_META: &str = "default";
33
35
34
36
pub fn load_share_sound(store: &store::Store) -> bool {
35
37
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")
36
38
}
37
39
40
pub fn load_camera(store: &store::Store) -> DeviceChoice {
41
match store.meta(CAMERA_META_KEY).ok().flatten() {
42
Some(key) if !key.is_empty() && key != DEFAULT_CAMERA_META => DeviceChoice::Device(key),
43
_ => DeviceChoice::SystemDefault,
44
}
45
}
46
47
fn camera_meta(choice: &DeviceChoice) -> &str {
48
match choice {
49
DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,
50
DeviceChoice::Device(key) => key,
51
}
52
}
53
38
54
fn now_unix() -> i64 {
39
55
chrono::Utc::now().timestamp()
40
56
}
@@ -155,6 +171,10 @@ impl AppState {
155
171
}
156
172
if let Some(call) = self.call.as_mut() {
157
173
call.model.background = self.call_background.clone();
174
call.model.camera = self.call_camera.clone();
175
}
176
if self.call_camera != DeviceChoice::SystemDefault {
177
self.send_call_command(CallCommand::SelectCamera(self.call_camera.clone()));
158
178
}
159
179
if self.call_background != BackgroundPick::None {
160
180
self.send_background_command(cx);
@@ -291,6 +311,8 @@ impl AppState {
291
311
}
292
312
293
313
pub fn select_call_camera(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {
314
let _ = self.store.set_meta(CAMERA_META_KEY, camera_meta(&choice));
315
self.call_camera = choice.clone();
294
316
if let Some(call) = self.call.as_mut() {
295
317
call.model.camera = choice.clone();
296
318
}
@@ -824,11 +846,11 @@ mod tests {
824
846
825
847
use std::path::PathBuf;
826
848
827
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};
849
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};
828
850
use gpui_kit::{AppContext as _, Entity, TestAppContext};
829
851
use store::{ChatRecord, MemberRecord, Store};
830
852
831
use super::{ActiveCall, CallModel};
853
use super::{ActiveCall, CallModel, load_camera};
832
854
use crate::app_state::{AppEvent, AppState, Mode, Selection};
833
855
use crate::call::TransferCandidate;
834
856
use crate::call::background::BackgroundPick;
@@ -909,6 +931,19 @@ mod tests {
909
931
assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));
910
932
}
911
933
934
#[gpui_kit::test]
935
fn the_camera_pick_is_remembered_and_the_next_call_starts_with_it(cx: &mut TestAppContext) {
936
let (app, _control) = app_with_commands(cx, live_meeting(false), None);
937
let store = cx.update(|cx| app.read(cx).store.clone());
938
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
939
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)));
940
assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));
941
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
942
assert_eq!(cx.update(|cx| reopened.read(cx).call_camera.clone()), DeviceChoice::Device("cam-2".into()));
943
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::SystemDefault, cx)));
944
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
945
}
946
912
947
#[gpui_kit::test]
913
948
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {
914
949
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
@@ -30,11 +30,27 @@ const DEMO_SMALL_MEETING: usize = 4;30
const DEMO_LIVE_MINUTES: i64 = 60;30
const DEMO_LIVE_MINUTES: i64 = 60;31
const ORGID_PREFIX: &str = "8:orgid:";31
const ORGID_PREFIX: &str = "8:orgid:";32
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";32
pub const SHARE_SOUND_META_KEY: &str = "call_share_sound";33
const CAMERA_META_KEY: &str = "call_camera";34
const DEFAULT_CAMERA_META: &str = "default";33
35
34
pub fn load_share_sound(store: &store::Store) -> bool {36
pub fn load_share_sound(store: &store::Store) -> bool {35
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")37
store.meta(SHARE_SOUND_META_KEY).ok().flatten().as_deref() == Some("1")36
}38
}37
39
40
pub fn load_camera(store: &store::Store) -> DeviceChoice {41
match store.meta(CAMERA_META_KEY).ok().flatten() {42
Some(key) if !key.is_empty() && key != DEFAULT_CAMERA_META => DeviceChoice::Device(key),43
_ => DeviceChoice::SystemDefault,44
}45
}46
47
fn camera_meta(choice: &DeviceChoice) -> &str {48
match choice {49
DeviceChoice::SystemDefault => DEFAULT_CAMERA_META,50
DeviceChoice::Device(key) => key,51
}52
}53
38
fn now_unix() -> i64 {54
fn now_unix() -> i64 {39
chrono::Utc::now().timestamp()55
chrono::Utc::now().timestamp()40
}56
}@@ -155,6 +171,10 @@ impl AppState {155
}171
}156
if let Some(call) = self.call.as_mut() {172
if let Some(call) = self.call.as_mut() {157
call.model.background = self.call_background.clone();173
call.model.background = self.call_background.clone();174
call.model.camera = self.call_camera.clone();175
}176
if self.call_camera != DeviceChoice::SystemDefault {177
self.send_call_command(CallCommand::SelectCamera(self.call_camera.clone()));158
}178
}159
if self.call_background != BackgroundPick::None {179
if self.call_background != BackgroundPick::None {160
self.send_background_command(cx);180
self.send_background_command(cx);@@ -291,6 +311,8 @@ impl AppState {291
}311
}292
312
293
pub fn select_call_camera(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {313
pub fn select_call_camera(&mut self, choice: DeviceChoice, _cx: &mut Context<Self>) {314
let _ = self.store.set_meta(CAMERA_META_KEY, camera_meta(&choice));315
self.call_camera = choice.clone();294
if let Some(call) = self.call.as_mut() {316
if let Some(call) = self.call.as_mut() {295
call.model.camera = choice.clone();317
call.model.camera = choice.clone();296
}318
}@@ -824,11 +846,11 @@ mod tests {824
846
825
use std::path::PathBuf;847
use std::path::PathBuf;826
848
827
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};849
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};828
use gpui_kit::{AppContext as _, Entity, TestAppContext};850
use gpui_kit::{AppContext as _, Entity, TestAppContext};829
use store::{ChatRecord, MemberRecord, Store};851
use store::{ChatRecord, MemberRecord, Store};830
852
831
use super::{ActiveCall, CallModel};853
use super::{ActiveCall, CallModel, load_camera};832
use crate::app_state::{AppEvent, AppState, Mode, Selection};854
use crate::app_state::{AppEvent, AppState, Mode, Selection};833
use crate::call::TransferCandidate;855
use crate::call::TransferCandidate;834
use crate::call::background::BackgroundPick;856
use crate::call::background::BackgroundPick;@@ -909,6 +931,19 @@ mod tests {909
assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));931
assert!(!cx.update(|cx| reopened.read(cx).call_share_sound));910
}932
}911
933
934
#[gpui_kit::test]935
fn the_camera_pick_is_remembered_and_the_next_call_starts_with_it(cx: &mut TestAppContext) {936
let (app, _control) = app_with_commands(cx, live_meeting(false), None);937
let store = cx.update(|cx| app.read(cx).store.clone());938
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);939
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)));940
assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));941
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));942
assert_eq!(cx.update(|cx| reopened.read(cx).call_camera.clone()), DeviceChoice::Device("cam-2".into()));943
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::SystemDefault, cx)));944
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);945
}946
912
#[gpui_kit::test]947
#[gpui_kit::test]913
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {948
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {914
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);949
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);@@ -67,6 +67,9 @@ impl AppState {
67
67
return;
68
68
}
69
69
let meeting_data = code.meeting_data();
70
if self.meet_now_pending {
71
return;
72
}
70
73
if self.mode.demo {
71
74
let target = MeetingTarget {
72
75
thread_id: DEMO_CODE_THREAD.to_owned(),
@@ -122,13 +125,19 @@ impl AppState {
122
125
self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);
123
126
return;
124
127
};
128
self.meet_now_pending = true;
129
cx.notify();
125
130
let receiver =
126
131
runtime::spawn(async move { launcher.create_meet_now(MEET_NOW_SUBJECT).await });
127
132
cx.spawn(async move |this, cx| {
128
133
let created = receiver.await.ok().and_then(Result::ok);
129
this.update(cx, |state, cx| match created {
130
Some(url) => state.join_meeting_link(&url, cx),
131
None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
134
this.update(cx, |state, cx| {
135
state.meet_now_pending = false;
136
match created {
137
Some(url) => state.join_meeting_link(&url, cx),
138
None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
139
}
140
cx.notify();
132
141
})
133
142
.ok();
134
143
})
@@ -67,6 +67,9 @@ impl AppState {67
return;67
return;68
}68
}69
let meeting_data = code.meeting_data();69
let meeting_data = code.meeting_data();70
if self.meet_now_pending {71
return;72
}70
if self.mode.demo {73
if self.mode.demo {71
let target = MeetingTarget {74
let target = MeetingTarget {72
thread_id: DEMO_CODE_THREAD.to_owned(),75
thread_id: DEMO_CODE_THREAD.to_owned(),@@ -122,13 +125,19 @@ impl AppState {122
self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);125
self.raise_notice(NOT_CONNECTED_NOTICE.to_owned(), None, cx);123
return;126
return;124
};127
};128
self.meet_now_pending = true;129
cx.notify();125
let receiver =130
let receiver =126
runtime::spawn(async move { launcher.create_meet_now(MEET_NOW_SUBJECT).await });131
runtime::spawn(async move { launcher.create_meet_now(MEET_NOW_SUBJECT).await });127
cx.spawn(async move |this, cx| {132
cx.spawn(async move |this, cx| {128
let created = receiver.await.ok().and_then(Result::ok);133
let created = receiver.await.ok().and_then(Result::ok);129
this.update(cx, |state, cx| match created {134
this.update(cx, |state, cx| {130
Some(url) => state.join_meeting_link(&url, cx),135
state.meet_now_pending = false;131
None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),136
match created {137
Some(url) => state.join_meeting_link(&url, cx),138
None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),139
}140
cx.notify();132
})141
})133
.ok();142
.ok();134
})143
})@@ -18,7 +18,7 @@ mod preview;
18
18
mod ring;
19
19
mod target;
20
20
21
pub use actions::load_share_sound;
21
pub use actions::{load_camera, load_share_sound};
22
22
pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};
23
23
pub use features::TransferCandidate;
24
24
pub use demo::DemoScene;
@@ -18,7 +18,7 @@ mod preview;18
mod ring;18
mod ring;19
mod target;19
mod target;20
20
21
pub use actions::load_share_sound;21
pub use actions::{load_camera, load_share_sound};22
pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};22
pub use background::{BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background, load_custom_backgrounds};23
pub use features::TransferCandidate;23
pub use features::TransferCandidate;24
pub use demo::DemoScene;24
pub use demo::DemoScene;@@ -728,7 +728,7 @@ impl CallModel {
728
728
}
729
729
730
730
pub fn has_reaction_controls(&self) -> bool {
731
self.kind == CallKind::Meeting
731
matches!(self.kind, CallKind::Group | CallKind::Meeting)
732
732
}
733
733
734
734
pub fn can_react(&self) -> bool {
@@ -1105,6 +1105,15 @@ mod tests {
1105
1105
assert_eq!(model.own_hand, None);
1106
1106
}
1107
1107
1108
#[test]
1109
fn reaction_controls_show_in_group_calls_and_meetings_only() {
1110
let mut model = CallModel::test();
1111
for (kind, expected) in [(CallKind::Test, false), (CallKind::Direct, false), (CallKind::Group, true), (CallKind::Meeting, true)] {
1112
model.kind = kind;
1113
assert_eq!(model.has_reaction_controls(), expected);
1114
}
1115
}
1116
1108
1117
#[test]
1109
1118
fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {
1110
1119
let mut model = meeting_with_me();
@@ -728,7 +728,7 @@ impl CallModel {728
}728
}729
729
730
pub fn has_reaction_controls(&self) -> bool {730
pub fn has_reaction_controls(&self) -> bool {731
self.kind == CallKind::Meeting731
matches!(self.kind, CallKind::Group | CallKind::Meeting)732
}732
}733
733
734
pub fn can_react(&self) -> bool {734
pub fn can_react(&self) -> bool {@@ -1105,6 +1105,15 @@ mod tests {1105
assert_eq!(model.own_hand, None);1105
assert_eq!(model.own_hand, None);1106
}1106
}1107
1107
1108
#[test]1109
fn reaction_controls_show_in_group_calls_and_meetings_only() {1110
let mut model = CallModel::test();1111
for (kind, expected) in [(CallKind::Test, false), (CallKind::Direct, false), (CallKind::Group, true), (CallKind::Meeting, true)] {1112
model.kind = kind;1113
assert_eq!(model.has_reaction_controls(), expected);1114
}1115
}1116
1108
#[test]1117
#[test]1109
fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {1118
fn the_server_echo_of_an_own_reaction_does_not_restart_the_chip() {1110
let mut model = meeting_with_me();1119
let mut model = meeting_with_me();@@ -7,7 +7,7 @@ use gpui_kit::*;
7
7
use super::model::format_elapsed;
8
8
use super::overlay_layout::{
9
9
MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness, format_position, mini_rect,
10
mini_wanted, parse_position,
10
mini_wanted, mini_work_area, parse_position,
11
11
};
12
12
use crate::app_state::AppState;
13
13
use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
@@ -15,6 +15,7 @@ use crate::views::call_mini_window::MiniWindowView;
15
15
use crate::views::share_bar::{ShareBarView, ShareBorderView};
16
16
17
17
const TICK: Duration = Duration::from_millis(100);
18
const IDLE_TICK: Duration = Duration::from_secs(1);
18
19
const SLOW_TICK_EVERY: u32 = 5;
19
20
const BORDER_SIDES: usize = 4;
20
21
@@ -129,10 +130,12 @@ impl CallWindows {
129
130
ticks: 0,
130
131
};
131
132
cx.spawn(async move |this, cx| {
133
let mut pause = TICK;
132
134
loop {
133
cx.background_executor().timer(TICK).await;
134
if this.update(cx, |windows, cx| windows.tick(cx)).is_err() {
135
break;
135
cx.background_executor().timer(pause).await;
136
match this.update(cx, |windows, cx| windows.tick(cx)) {
137
Ok(next_pause) => pause = next_pause,
138
Err(_) => break,
136
139
}
137
140
}
138
141
})
@@ -185,7 +188,14 @@ impl CallWindows {
185
188
self.app.update(cx, |state, cx| state.show_call(true, cx));
186
189
}
187
190
188
fn tick(&mut self, cx: &mut Context<Self>) {
191
fn idle(&self, cx: &App) -> bool {
192
self.app.read(cx).call.is_none() && self.share.is_none() && self.windows.is_empty() && self.opening.is_empty()
193
}
194
195
fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
196
if self.idle(cx) {
197
return IDLE_TICK;
198
}
189
199
self.ticks = self.ticks.wrapping_add(1);
190
200
let slow = self.ticks % SLOW_TICK_EVERY == 0;
191
201
self.refresh_main_window();
@@ -194,6 +204,7 @@ impl CallWindows {
194
204
if slow {
195
205
self.track_mini_position(cx);
196
206
}
207
TICK
197
208
}
198
209
199
210
fn refresh_main_window(&mut self) {
@@ -273,7 +284,8 @@ impl CallWindows {
273
284
let in_call = self.app.read(cx).call.is_some();
274
285
let work = self.work_area.or_else(|| display_work_area(cx));
275
286
match work.filter(|_| mini_wanted(in_call, self.minimized)) {
276
Some(work) => {
287
Some(main_work) => {
288
let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
277
289
let rect = mini_rect(work, self.mini_saved);
278
290
self.ensure_window(Role::Mini, rect, work.scale, false, cx);
279
291
}
@@ -7,7 +7,7 @@ use gpui_kit::*;7
use super::model::format_elapsed;7
use super::model::format_elapsed;8
use super::overlay_layout::{8
use super::overlay_layout::{9
MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness, format_position, mini_rect,9
MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness, format_position, mini_rect,10
mini_wanted, parse_position,10
mini_wanted, mini_work_area, parse_position,11
};11
};12
use crate::app_state::AppState;12
use crate::app_state::AppState;13
use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};13
use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};@@ -15,6 +15,7 @@ use crate::views::call_mini_window::MiniWindowView;15
use crate::views::share_bar::{ShareBarView, ShareBorderView};15
use crate::views::share_bar::{ShareBarView, ShareBorderView};16
16
17
const TICK: Duration = Duration::from_millis(100);17
const TICK: Duration = Duration::from_millis(100);18
const IDLE_TICK: Duration = Duration::from_secs(1);18
const SLOW_TICK_EVERY: u32 = 5;19
const SLOW_TICK_EVERY: u32 = 5;19
const BORDER_SIDES: usize = 4;20
const BORDER_SIDES: usize = 4;20
21
@@ -129,10 +130,12 @@ impl CallWindows {129
ticks: 0,130
ticks: 0,130
};131
};131
cx.spawn(async move |this, cx| {132
cx.spawn(async move |this, cx| {133
let mut pause = TICK;132
loop {134
loop {133
cx.background_executor().timer(TICK).await;135
cx.background_executor().timer(pause).await;134
if this.update(cx, |windows, cx| windows.tick(cx)).is_err() {136
match this.update(cx, |windows, cx| windows.tick(cx)) {135
break;137
Ok(next_pause) => pause = next_pause,138
Err(_) => break,136
}139
}137
}140
}138
})141
})@@ -185,7 +188,14 @@ impl CallWindows {185
self.app.update(cx, |state, cx| state.show_call(true, cx));188
self.app.update(cx, |state, cx| state.show_call(true, cx));186
}189
}187
190
188
fn tick(&mut self, cx: &mut Context<Self>) {191
fn idle(&self, cx: &App) -> bool {192
self.app.read(cx).call.is_none() && self.share.is_none() && self.windows.is_empty() && self.opening.is_empty()193
}194
195
fn tick(&mut self, cx: &mut Context<Self>) -> Duration {196
if self.idle(cx) {197
return IDLE_TICK;198
}189
self.ticks = self.ticks.wrapping_add(1);199
self.ticks = self.ticks.wrapping_add(1);190
let slow = self.ticks % SLOW_TICK_EVERY == 0;200
let slow = self.ticks % SLOW_TICK_EVERY == 0;191
self.refresh_main_window();201
self.refresh_main_window();@@ -194,6 +204,7 @@ impl CallWindows {194
if slow {204
if slow {195
self.track_mini_position(cx);205
self.track_mini_position(cx);196
}206
}207
TICK197
}208
}198
209
199
fn refresh_main_window(&mut self) {210
fn refresh_main_window(&mut self) {@@ -273,7 +284,8 @@ impl CallWindows {273
let in_call = self.app.read(cx).call.is_some();284
let in_call = self.app.read(cx).call.is_some();274
let work = self.work_area.or_else(|| display_work_area(cx));285
let work = self.work_area.or_else(|| display_work_area(cx));275
match work.filter(|_| mini_wanted(in_call, self.minimized)) {286
match work.filter(|_| mini_wanted(in_call, self.minimized)) {276
Some(work) => {287
Some(main_work) => {288
let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);277
let rect = mini_rect(work, self.mini_saved);289
let rect = mini_rect(work, self.mini_saved);278
self.ensure_window(Role::Mini, rect, work.scale, false, cx);290
self.ensure_window(Role::Mini, rect, work.scale, false, cx);279
}291
}@@ -67,6 +67,10 @@ pub fn mini_rect(work: WorkArea, saved: Option<(i32, i32)>) -> ScreenRect {
67
67
}
68
68
}
69
69
70
pub fn mini_work_area(main: WorkArea, saved: Option<(i32, i32)>, area_at: impl Fn(i32, i32) -> Option<WorkArea>) -> WorkArea {
71
saved.and_then(|(left, top)| area_at(left, top)).unwrap_or(main)
72
}
73
70
74
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {
71
75
call_active && main_minimized
72
76
}
@@ -158,6 +162,17 @@ mod tests {
158
162
assert_eq!((pulled.left, pulled.bottom), (0, 1040));
159
163
}
160
164
165
#[test]
166
fn mini_stays_on_the_monitor_that_holds_the_saved_point() {
167
let second = WorkArea { left: 1920, top: 0, right: 3840, bottom: 1040, scale: 1. };
168
let area_at = |left: i32, _: i32| (left >= 1920).then_some(second);
169
let saved = Some((3700, 900));
170
let rect = mini_rect(mini_work_area(work(1.), saved, area_at), saved);
171
assert_eq!((rect.right, rect.bottom), (3840, 1040));
172
assert_eq!(mini_work_area(work(1.), Some((100, 100)), area_at), work(1.));
173
assert_eq!(mini_work_area(work(1.), None, area_at), work(1.));
174
}
175
161
176
#[test]
162
177
fn mini_scales_with_the_monitor() {
163
178
let rect = mini_rect(work(2.), None);
@@ -67,6 +67,10 @@ pub fn mini_rect(work: WorkArea, saved: Option<(i32, i32)>) -> ScreenRect {67
}67
}68
}68
}69
69
70
pub fn mini_work_area(main: WorkArea, saved: Option<(i32, i32)>, area_at: impl Fn(i32, i32) -> Option<WorkArea>) -> WorkArea {71
saved.and_then(|(left, top)| area_at(left, top)).unwrap_or(main)72
}73
70
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {74
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {71
call_active && main_minimized75
call_active && main_minimized72
}76
}@@ -158,6 +162,17 @@ mod tests {158
assert_eq!((pulled.left, pulled.bottom), (0, 1040));162
assert_eq!((pulled.left, pulled.bottom), (0, 1040));159
}163
}160
164
165
#[test]166
fn mini_stays_on_the_monitor_that_holds_the_saved_point() {167
let second = WorkArea { left: 1920, top: 0, right: 3840, bottom: 1040, scale: 1. };168
let area_at = |left: i32, _: i32| (left >= 1920).then_some(second);169
let saved = Some((3700, 900));170
let rect = mini_rect(mini_work_area(work(1.), saved, area_at), saved);171
assert_eq!((rect.right, rect.bottom), (3840, 1040));172
assert_eq!(mini_work_area(work(1.), Some((100, 100)), area_at), work(1.));173
assert_eq!(mini_work_area(work(1.), None, area_at), work(1.));174
}175
161
#[test]176
#[test]162
fn mini_scales_with_the_monitor() {177
fn mini_scales_with_the_monitor() {163
let rect = mini_rect(work(2.), None);178
let rect = mini_rect(work(2.), None);@@ -21,6 +21,7 @@ pub struct CameraPreview {
21
21
hub: Arc<VideoHub>,
22
22
pictures: CallPictures,
23
23
blur: Arc<BlurSettings>,
24
background_request: Arc<AtomicU64>,
24
25
capture: Option<Capture>,
25
26
frames: Arc<AtomicU64>,
26
27
failure: Arc<Mutex<Option<String>>>,
@@ -35,6 +36,7 @@ impl CameraPreview {
35
36
hub: VideoHub::new(sender),
36
37
pictures: CallPictures::default(),
37
38
blur: Arc::new(BlurSettings::default()),
39
background_request: Arc::new(AtomicU64::new(0)),
38
40
capture: None,
39
41
frames: Arc::new(AtomicU64::new(0)),
40
42
failure: Arc::new(Mutex::new(None)),
@@ -71,13 +73,17 @@ impl CameraPreview {
71
73
}
72
74
73
75
pub fn set_background(&self, choice: BackgroundChoice) {
76
let request = self.background_request.fetch_add(1, Ordering::SeqCst) + 1;
74
77
match choice {
75
78
BackgroundChoice::None => self.apply_background(false, None),
76
79
BackgroundChoice::Blur => self.apply_background(true, None),
77
80
BackgroundChoice::Image(path) => {
78
81
let blur = self.blur.clone();
82
let latest_request = self.background_request.clone();
79
83
std::thread::spawn(move || {
80
if let Ok(picture) = BackgroundPicture::load(&path) {
84
if let Ok(picture) = BackgroundPicture::load(&path)
85
&& latest_request.load(Ordering::SeqCst) == request
86
{
81
87
blur.set_picture(Some(Arc::new(picture)));
82
88
blur.set_enabled(true);
83
89
}
@@ -21,6 +21,7 @@ pub struct CameraPreview {21
hub: Arc<VideoHub>,21
hub: Arc<VideoHub>,22
pictures: CallPictures,22
pictures: CallPictures,23
blur: Arc<BlurSettings>,23
blur: Arc<BlurSettings>,24
background_request: Arc<AtomicU64>,24
capture: Option<Capture>,25
capture: Option<Capture>,25
frames: Arc<AtomicU64>,26
frames: Arc<AtomicU64>,26
failure: Arc<Mutex<Option<String>>>,27
failure: Arc<Mutex<Option<String>>>,@@ -35,6 +36,7 @@ impl CameraPreview {35
hub: VideoHub::new(sender),36
hub: VideoHub::new(sender),36
pictures: CallPictures::default(),37
pictures: CallPictures::default(),37
blur: Arc::new(BlurSettings::default()),38
blur: Arc::new(BlurSettings::default()),39
background_request: Arc::new(AtomicU64::new(0)),38
capture: None,40
capture: None,39
frames: Arc::new(AtomicU64::new(0)),41
frames: Arc::new(AtomicU64::new(0)),40
failure: Arc::new(Mutex::new(None)),42
failure: Arc::new(Mutex::new(None)),@@ -71,13 +73,17 @@ impl CameraPreview {71
}73
}72
74
73
pub fn set_background(&self, choice: BackgroundChoice) {75
pub fn set_background(&self, choice: BackgroundChoice) {76
let request = self.background_request.fetch_add(1, Ordering::SeqCst) + 1;74
match choice {77
match choice {75
BackgroundChoice::None => self.apply_background(false, None),78
BackgroundChoice::None => self.apply_background(false, None),76
BackgroundChoice::Blur => self.apply_background(true, None),79
BackgroundChoice::Blur => self.apply_background(true, None),77
BackgroundChoice::Image(path) => {80
BackgroundChoice::Image(path) => {78
let blur = self.blur.clone();81
let blur = self.blur.clone();82
let latest_request = self.background_request.clone();79
std::thread::spawn(move || {83
std::thread::spawn(move || {80
if let Ok(picture) = BackgroundPicture::load(&path) {84
if let Ok(picture) = BackgroundPicture::load(&path)85
&& latest_request.load(Ordering::SeqCst) == request86
{81
blur.set_picture(Some(Arc::new(picture)));87
blur.set_picture(Some(Arc::new(picture)));82
blur.set_enabled(true);88
blur.set_enabled(true);83
}89
}@@ -18,6 +18,10 @@ pub fn work_area(_handle: NativeHandle) -> Option<WorkArea> {
18
18
None
19
19
}
20
20
21
pub fn work_area_at(_x: i32, _y: i32) -> Option<WorkArea> {
22
None
23
}
24
21
25
pub fn place(_handle: NativeHandle, _x: i32, _y: i32, _width: i32, _height: i32) {}
22
26
23
27
pub fn exclude_from_capture(_handle: NativeHandle) {}
@@ -18,6 +18,10 @@ pub fn work_area(_handle: NativeHandle) -> Option<WorkArea> {18
None18
None19
}19
}20
20
21
pub fn work_area_at(_x: i32, _y: i32) -> Option<WorkArea> {22
None23
}24
21
pub fn place(_handle: NativeHandle, _x: i32, _y: i32, _width: i32, _height: i32) {}25
pub fn place(_handle: NativeHandle, _x: i32, _y: i32, _width: i32, _height: i32) {}22
26
23
pub fn exclude_from_capture(_handle: NativeHandle) {}27
pub fn exclude_from_capture(_handle: NativeHandle) {}@@ -10,7 +10,7 @@ use gpui_kit::Window;
10
10
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
11
11
use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem};
12
12
use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
13
use windows::Win32::Foundation::{COLORREF, HWND, RECT};
13
use windows::Win32::Foundation::{COLORREF, HWND, POINT, RECT};
14
14
use windows::Win32::Graphics::Dwm::{
15
15
DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS, DWMWA_WINDOW_CORNER_PREFERENCE,
16
16
DWMWCP_DONOTROUND, DwmGetWindowAttribute, DwmSetWindowAttribute,
@@ -18,7 +18,7 @@ use windows::Win32::Graphics::Dwm::{
18
18
use windows::Win32::Graphics::Gdi::{
19
19
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject, ENUM_CURRENT_SETTINGS,
20
20
EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,
21
MonitorFromRect, MonitorFromWindow,
21
MonitorFromPoint, MonitorFromRect, MonitorFromWindow,
22
22
};
23
23
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
24
24
use windows::Win32::UI::HiDpi::{GetDpiForWindow, GetDpiForMonitor, MDT_EFFECTIVE_DPI};
@@ -140,6 +140,26 @@ pub fn work_area(handle: NativeHandle) -> Option<WorkArea> {
140
140
}
141
141
}
142
142
143
pub fn work_area_at(x: i32, y: i32) -> Option<WorkArea> {
144
unsafe {
145
let monitor = MonitorFromPoint(POINT { x, y }, MONITOR_DEFAULTTONEAREST);
146
let mut info = MONITORINFO {
147
cbSize: size_of::<MONITORINFO>() as u32,
148
..Default::default()
149
};
150
if !GetMonitorInfoW(monitor, &mut info).as_bool() {
151
return None;
152
}
153
let (mut dpi_x, mut dpi_y) = (0, 0);
154
let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {
155
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
156
_ => 1.,
157
};
158
let RECT { left, top, right, bottom } = info.rcWork;
159
Some(WorkArea { left, top, right, bottom, scale })
160
}
161
}
162
143
163
pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {
144
164
unsafe {
145
165
let _ = SetWindowPos(
@@ -10,7 +10,7 @@ use gpui_kit::Window;10
use raw_window_handle::{HasWindowHandle, RawWindowHandle};10
use raw_window_handle::{HasWindowHandle, RawWindowHandle};11
use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem};11
use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuItem};12
use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};12
use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};13
use windows::Win32::Foundation::{COLORREF, HWND, RECT};13
use windows::Win32::Foundation::{COLORREF, HWND, POINT, RECT};14
use windows::Win32::Graphics::Dwm::{14
use windows::Win32::Graphics::Dwm::{15
DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS, DWMWA_WINDOW_CORNER_PREFERENCE,15
DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS, DWMWA_WINDOW_CORNER_PREFERENCE,16
DWMWCP_DONOTROUND, DwmGetWindowAttribute, DwmSetWindowAttribute,16
DWMWCP_DONOTROUND, DwmGetWindowAttribute, DwmSetWindowAttribute,@@ -18,7 +18,7 @@ use windows::Win32::Graphics::Dwm::{18
use windows::Win32::Graphics::Gdi::{18
use windows::Win32::Graphics::Gdi::{19
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject, ENUM_CURRENT_SETTINGS,19
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject, ENUM_CURRENT_SETTINGS,20
EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,20
EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,21
MonitorFromRect, MonitorFromWindow,21
MonitorFromPoint, MonitorFromRect, MonitorFromWindow,22
};22
};23
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};23
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};24
use windows::Win32::UI::HiDpi::{GetDpiForWindow, GetDpiForMonitor, MDT_EFFECTIVE_DPI};24
use windows::Win32::UI::HiDpi::{GetDpiForWindow, GetDpiForMonitor, MDT_EFFECTIVE_DPI};@@ -140,6 +140,26 @@ pub fn work_area(handle: NativeHandle) -> Option<WorkArea> {140
}140
}141
}141
}142
142
143
pub fn work_area_at(x: i32, y: i32) -> Option<WorkArea> {144
unsafe {145
let monitor = MonitorFromPoint(POINT { x, y }, MONITOR_DEFAULTTONEAREST);146
let mut info = MONITORINFO {147
cbSize: size_of::<MONITORINFO>() as u32,148
..Default::default()149
};150
if !GetMonitorInfoW(monitor, &mut info).as_bool() {151
return None;152
}153
let (mut dpi_x, mut dpi_y) = (0, 0);154
let scale = match GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) {155
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,156
_ => 1.,157
};158
let RECT { left, top, right, bottom } = info.rcWork;159
Some(WorkArea { left, top, right, bottom, scale })160
}161
}162
143
pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {163
pub fn place(handle: NativeHandle, x: i32, y: i32, width: i32, height: i32) {144
unsafe {164
unsafe {145
let _ = SetWindowPos(165
let _ = SetWindowPos(@@ -16,6 +16,7 @@ use super::center::NotificationCenter;
16
16
use super::platform;
17
17
use super::ring_tone::Ringtone;
18
18
use super::rules::Settings;
19
use crate::app_state::AppState;
19
20
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
20
21
use crate::theme;
21
22
@@ -24,6 +25,11 @@ const SELECT_WIDTH: f32 = 170.;
24
25
const PREVIEW_WIDTH: f32 = 380.;
25
26
const PREVIEW_HEIGHT: f32 = 214.;
26
27
const PREVIEW_RADIUS: f32 = 10.;
28
const CAMERA_IN_USE: &str = "Camera is in use by the call";
29
30
fn camera_in_call(state: &AppState) -> bool {
31
state.call.as_ref().is_some_and(|call| call.model.camera_on)
32
}
27
33
28
34
#[derive(Clone, Copy, PartialEq, Eq)]
29
35
enum Section {
@@ -86,7 +92,9 @@ pub struct SettingsView {
86
92
cameras_requested: bool,
87
93
camera: DeviceChoice,
88
94
background: BackgroundPick,
95
preview_blocked: bool,
89
96
_subscription: Subscription,
97
_app_subscription: Subscription,
90
98
_release: Subscription,
91
99
}
92
100
@@ -96,9 +104,13 @@ impl SettingsView {
96
104
97
105
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {
98
106
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());
107
let app = center.read(cx).app().clone();
108
let app_subscription = cx.observe(&app, |view, _, cx| view.sync_preview_block(cx));
99
109
let release = cx.on_release(|view, cx| view.preview.stop(cx));
100
110
let (preview, mut updates) = CameraPreview::new();
101
let state = center.read(cx).app().read(cx);
111
let state = app.read(cx);
112
let camera = state.call_camera.clone();
113
let preview_blocked = camera_in_call(state);
102
114
let background = Some(state.call_background.clone())
103
115
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))
104
116
.unwrap_or_default();
@@ -125,9 +137,11 @@ impl SettingsView {
125
137
preview,
126
138
cameras: camera_entries(&[]),
127
139
cameras_requested: false,
128
camera: DeviceChoice::SystemDefault,
140
camera,
129
141
background,
142
preview_blocked,
130
143
_subscription: subscription,
144
_app_subscription: app_subscription,
131
145
_release: release,
132
146
}
133
147
}
@@ -153,7 +167,8 @@ impl SettingsView {
153
167
Section::Devices => {
154
168
self.load_cameras(cx);
155
169
self.apply_background(cx);
156
self.preview.start(&self.camera);
170
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
171
self.start_preview();
157
172
}
158
173
Section::Notifications => self.preview.stop(cx),
159
174
}
@@ -175,14 +190,38 @@ impl SettingsView {
175
190
.detach();
176
191
}
177
192
193
fn start_preview(&mut self) {
194
if !self.preview_blocked {
195
self.preview.start(&self.camera);
196
}
197
}
198
199
fn sync_preview_block(&mut self, cx: &mut Context<Self>) {
200
let blocked = camera_in_call(self.center.read(cx).app().read(cx));
201
if blocked == self.preview_blocked {
202
return;
203
}
204
self.preview_blocked = blocked;
205
if blocked {
206
self.preview.stop(cx);
207
} else if self.section == Section::Devices {
208
self.start_preview();
209
}
210
cx.notify();
211
}
212
178
213
fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {
179
self.camera = camera;
180
self.preview.start(&self.camera);
214
self.camera = camera.clone();
215
let app = self.center.read(cx).app().clone();
216
app.update(cx, |state, cx| state.select_call_camera(camera, cx));
217
self.start_preview();
181
218
cx.notify();
182
219
}
183
220
184
221
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {
185
self.background = pick;
222
self.background = pick.clone();
223
let app = self.center.read(cx).app().clone();
224
app.update(cx, |state, cx| state.set_call_background(pick, cx));
186
225
self.apply_background(cx);
187
226
cx.notify();
188
227
}
@@ -333,14 +372,18 @@ impl SettingsView {
333
372
.map_or("None".to_owned(), |(_, label)| label.clone());
334
373
let current_background = self.background.clone();
335
374
let image = self.preview.image(Instant::now());
336
let status = self.preview.failure().map_or_else(
337
|| {
338
self.preview
339
.fps()
340
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))
341
},
342
|reason| format!("Camera could not start: {reason}"),
343
);
375
let status = if self.preview_blocked {
376
CAMERA_IN_USE.to_owned()
377
} else {
378
self.preview.failure().map_or_else(
379
|| {
380
self.preview
381
.fps()
382
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))
383
},
384
|reason| format!("Camera could not start: {reason}"),
385
)
386
};
344
387
v_flex()
345
388
.w_full()
346
389
.child(control_row(
@@ -16,6 +16,7 @@ use super::center::NotificationCenter;16
use super::platform;16
use super::platform;17
use super::ring_tone::Ringtone;17
use super::ring_tone::Ringtone;18
use super::rules::Settings;18
use super::rules::Settings;19
use crate::app_state::AppState;19
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};20
use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};20
use crate::theme;21
use crate::theme;21
22
@@ -24,6 +25,11 @@ const SELECT_WIDTH: f32 = 170.;24
const PREVIEW_WIDTH: f32 = 380.;25
const PREVIEW_WIDTH: f32 = 380.;25
const PREVIEW_HEIGHT: f32 = 214.;26
const PREVIEW_HEIGHT: f32 = 214.;26
const PREVIEW_RADIUS: f32 = 10.;27
const PREVIEW_RADIUS: f32 = 10.;28
const CAMERA_IN_USE: &str = "Camera is in use by the call";29
30
fn camera_in_call(state: &AppState) -> bool {31
state.call.as_ref().is_some_and(|call| call.model.camera_on)32
}27
33
28
#[derive(Clone, Copy, PartialEq, Eq)]34
#[derive(Clone, Copy, PartialEq, Eq)]29
enum Section {35
enum Section {@@ -86,7 +92,9 @@ pub struct SettingsView {86
cameras_requested: bool,92
cameras_requested: bool,87
camera: DeviceChoice,93
camera: DeviceChoice,88
background: BackgroundPick,94
background: BackgroundPick,95
preview_blocked: bool,89
_subscription: Subscription,96
_subscription: Subscription,97
_app_subscription: Subscription,90
_release: Subscription,98
_release: Subscription,91
}99
}92
100
@@ -96,9 +104,13 @@ impl SettingsView {96
104
97
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {105
pub fn new(center: Entity<NotificationCenter>, cx: &mut Context<Self>) -> Self {98
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());106
let subscription = cx.observe(¢er, |_, _, cx| cx.notify());107
let app = center.read(cx).app().clone();108
let app_subscription = cx.observe(&app, |view, _, cx| view.sync_preview_block(cx));99
let release = cx.on_release(|view, cx| view.preview.stop(cx));109
let release = cx.on_release(|view, cx| view.preview.stop(cx));100
let (preview, mut updates) = CameraPreview::new();110
let (preview, mut updates) = CameraPreview::new();101
let state = center.read(cx).app().read(cx);111
let state = app.read(cx);112
let camera = state.call_camera.clone();113
let preview_blocked = camera_in_call(state);102
let background = Some(state.call_background.clone())114
let background = Some(state.call_background.clone())103
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))115
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))104
.unwrap_or_default();116
.unwrap_or_default();@@ -125,9 +137,11 @@ impl SettingsView {125
preview,137
preview,126
cameras: camera_entries(&[]),138
cameras: camera_entries(&[]),127
cameras_requested: false,139
cameras_requested: false,128
camera: DeviceChoice::SystemDefault,140
camera,129
background,141
background,142
preview_blocked,130
_subscription: subscription,143
_subscription: subscription,144
_app_subscription: app_subscription,131
_release: release,145
_release: release,132
}146
}133
}147
}@@ -153,7 +167,8 @@ impl SettingsView {153
Section::Devices => {167
Section::Devices => {154
self.load_cameras(cx);168
self.load_cameras(cx);155
self.apply_background(cx);169
self.apply_background(cx);156
self.preview.start(&self.camera);170
self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));171
self.start_preview();157
}172
}158
Section::Notifications => self.preview.stop(cx),173
Section::Notifications => self.preview.stop(cx),159
}174
}@@ -175,14 +190,38 @@ impl SettingsView {175
.detach();190
.detach();176
}191
}177
192
193
fn start_preview(&mut self) {194
if !self.preview_blocked {195
self.preview.start(&self.camera);196
}197
}198
199
fn sync_preview_block(&mut self, cx: &mut Context<Self>) {200
let blocked = camera_in_call(self.center.read(cx).app().read(cx));201
if blocked == self.preview_blocked {202
return;203
}204
self.preview_blocked = blocked;205
if blocked {206
self.preview.stop(cx);207
} else if self.section == Section::Devices {208
self.start_preview();209
}210
cx.notify();211
}212
178
fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {213
fn select_camera(&mut self, camera: DeviceChoice, cx: &mut Context<Self>) {179
self.camera = camera;214
self.camera = camera.clone();180
self.preview.start(&self.camera);215
let app = self.center.read(cx).app().clone();216
app.update(cx, |state, cx| state.select_call_camera(camera, cx));217
self.start_preview();181
cx.notify();218
cx.notify();182
}219
}183
220
184
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {221
fn select_background(&mut self, pick: BackgroundPick, cx: &mut Context<Self>) {185
self.background = pick;222
self.background = pick.clone();223
let app = self.center.read(cx).app().clone();224
app.update(cx, |state, cx| state.set_call_background(pick, cx));186
self.apply_background(cx);225
self.apply_background(cx);187
cx.notify();226
cx.notify();188
}227
}@@ -333,14 +372,18 @@ impl SettingsView {333
.map_or("None".to_owned(), |(_, label)| label.clone());372
.map_or("None".to_owned(), |(_, label)| label.clone());334
let current_background = self.background.clone();373
let current_background = self.background.clone();335
let image = self.preview.image(Instant::now());374
let image = self.preview.image(Instant::now());336
let status = self.preview.failure().map_or_else(375
let status = if self.preview_blocked {337
|| {376
CAMERA_IN_USE.to_owned()338
self.preview377
} else {339
.fps()378
self.preview.failure().map_or_else(340
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))379
|| {341
},380
self.preview342
|reason| format!("Camera could not start: {reason}"),381
.fps()343
);382
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))383
},384
|reason| format!("Camera could not start: {reason}"),385
)386
};344
v_flex()387
v_flex()345
.w_full()388
.w_full()346
.child(control_row(389
.child(control_row(@@ -25,16 +25,23 @@ pub struct MiniWindowView {
25
25
windows: Entity<CallWindows>,
26
26
app: Entity<AppState>,
27
27
_app_subscription: Subscription,
28
_media_subscription: Option<Subscription>,
28
29
}
29
30
30
31
impl MiniWindowView {
31
32
pub fn new(windows: Entity<CallWindows>, cx: &mut Context<Self>) -> Self {
32
33
let app = windows.read(cx).app().clone();
33
34
let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());
35
let media_subscription = app
36
.read(cx)
37
.call_media
38
.clone()
39
.map(|media| cx.observe(&media, |_, _, cx| cx.notify()));
34
40
MiniWindowView {
35
41
windows,
36
42
app,
37
43
_app_subscription: app_subscription,
44
_media_subscription: media_subscription,
38
45
}
39
46
}
40
47
}
@@ -25,16 +25,23 @@ pub struct MiniWindowView {25
windows: Entity<CallWindows>,25
windows: Entity<CallWindows>,26
app: Entity<AppState>,26
app: Entity<AppState>,27
_app_subscription: Subscription,27
_app_subscription: Subscription,28
_media_subscription: Option<Subscription>,28
}29
}29
30
30
impl MiniWindowView {31
impl MiniWindowView {31
pub fn new(windows: Entity<CallWindows>, cx: &mut Context<Self>) -> Self {32
pub fn new(windows: Entity<CallWindows>, cx: &mut Context<Self>) -> Self {32
let app = windows.read(cx).app().clone();33
let app = windows.read(cx).app().clone();33
let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());34
let app_subscription = cx.observe(&app, |_, _, cx| cx.notify());35
let media_subscription = app36
.read(cx)37
.call_media38
.clone()39
.map(|media| cx.observe(&media, |_, _, cx| cx.notify()));34
MiniWindowView {40
MiniWindowView {35
windows,41
windows,36
app,42
app,37
_app_subscription: app_subscription,43
_app_subscription: app_subscription,44
_media_subscription: media_subscription,38
}45
}39
}46
}40
}47
}@@ -1,6 +1,7 @@
1
1
use chrono::{Local, Offset, Utc};
2
2
use gpui_kit::assets::IconName;
3
3
use gpui_kit::component::Sizable as _;
4
use gpui_kit::base::Disableable as _;
4
5
use gpui_kit::component::button::{Button, ButtonVariants as _};
5
6
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6
7
use gpui_kit::component::{h_flex, v_flex};
@@ -144,7 +145,7 @@ fn call_row(
144
145
.into_any_element()
145
146
}
146
147
147
fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
148
fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoElement {
148
149
let meet_state = state.clone();
149
150
let id_state = state.clone();
150
151
let paste_state = state.clone();
@@ -159,6 +160,7 @@ fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {
159
160
.small()
160
161
.primary()
161
162
.label("Meet now")
163
.disabled(meet_now_pending)
162
164
.on_click(move |_, _, cx| {
163
165
meet_state.update(cx, |state, cx| state.start_meet_now(cx));
164
166
}),
@@ -330,7 +332,7 @@ pub fn calls_body(
330
332
v_flex()
331
333
.flex_1()
332
334
.min_h_0()
333
.child(join_buttons(state))
335
.child(join_buttons(state, app.meet_now_pending))
334
336
.child(
335
337
div()
336
338
.id("calls-scroll")
@@ -1,6 +1,7 @@1
use chrono::{Local, Offset, Utc};1
use chrono::{Local, Offset, Utc};2
use gpui_kit::assets::IconName;2
use gpui_kit::assets::IconName;3
use gpui_kit::component::Sizable as _;3
use gpui_kit::component::Sizable as _;4
use gpui_kit::base::Disableable as _;4
use gpui_kit::component::button::{Button, ButtonVariants as _};5
use gpui_kit::component::button::{Button, ButtonVariants as _};5
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};6
use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};6
use gpui_kit::component::{h_flex, v_flex};7
use gpui_kit::component::{h_flex, v_flex};@@ -144,7 +145,7 @@ fn call_row(144
.into_any_element()145
.into_any_element()145
}146
}146
147
147
fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {148
fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoElement {148
let meet_state = state.clone();149
let meet_state = state.clone();149
let id_state = state.clone();150
let id_state = state.clone();150
let paste_state = state.clone();151
let paste_state = state.clone();@@ -159,6 +160,7 @@ fn join_buttons(state: &Entity<AppState>) -> impl IntoElement {159
.small()160
.small()160
.primary()161
.primary()161
.label("Meet now")162
.label("Meet now")163
.disabled(meet_now_pending)162
.on_click(move |_, _, cx| {164
.on_click(move |_, _, cx| {163
meet_state.update(cx, |state, cx| state.start_meet_now(cx));165
meet_state.update(cx, |state, cx| state.start_meet_now(cx));164
}),166
}),@@ -330,7 +332,7 @@ pub fn calls_body(330
v_flex()332
v_flex()331
.flex_1()333
.flex_1()332
.min_h_0()334
.min_h_0()333
.child(join_buttons(state))335
.child(join_buttons(state, app.meet_now_pending))334
.child(336
.child(335
div()337
div()336
.id("calls-scroll")338
.id("calls-scroll")@@ -1,4 +1,5 @@
1
1
use std::collections::HashSet;
2
use std::time::Duration;
2
3
3
4
use chrono::{Local, Offset, Utc};
4
5
use gpui_kit::assets::IconName;
@@ -37,6 +38,7 @@ const SECTION_GAP: f32 = 4.;
37
38
const HINT_HEIGHT: f32 = 26.;
38
39
const SEE_MORE_HEIGHT: f32 = 28.;
39
40
const FALLBACK_VIEWPORT: f32 = 900.;
41
const CALLS_REFRESH: Duration = Duration::from_secs(30);
40
42
const VIEWPORT_MARGIN: f32 = 300.;
41
43
const AVATAR_SIZE: f32 = 36.;
42
44
const PINNED_LABEL: &str = "Pinned";
@@ -351,6 +353,20 @@ impl SidebarView {
351
353
SidebarTab::Chats
352
354
};
353
355
let collapsed_teams = load_collapsed_teams(&state.read(cx).store);
356
cx.spawn(async move |this, cx| {
357
loop {
358
cx.background_executor().timer(CALLS_REFRESH).await;
359
let alive = this.update(cx, |view, cx| {
360
if view.tab == SidebarTab::Calls {
361
cx.notify();
362
}
363
});
364
if alive.is_err() {
365
break;
366
}
367
}
368
})
369
.detach();
354
370
SidebarView {
355
371
state,
356
372
tab,
@@ -1,4 +1,5 @@1
use std::collections::HashSet;1
use std::collections::HashSet;2
use std::time::Duration;2
3
3
use chrono::{Local, Offset, Utc};4
use chrono::{Local, Offset, Utc};4
use gpui_kit::assets::IconName;5
use gpui_kit::assets::IconName;@@ -37,6 +38,7 @@ const SECTION_GAP: f32 = 4.;37
const HINT_HEIGHT: f32 = 26.;38
const HINT_HEIGHT: f32 = 26.;38
const SEE_MORE_HEIGHT: f32 = 28.;39
const SEE_MORE_HEIGHT: f32 = 28.;39
const FALLBACK_VIEWPORT: f32 = 900.;40
const FALLBACK_VIEWPORT: f32 = 900.;41
const CALLS_REFRESH: Duration = Duration::from_secs(30);40
const VIEWPORT_MARGIN: f32 = 300.;42
const VIEWPORT_MARGIN: f32 = 300.;41
const AVATAR_SIZE: f32 = 36.;43
const AVATAR_SIZE: f32 = 36.;42
const PINNED_LABEL: &str = "Pinned";44
const PINNED_LABEL: &str = "Pinned";@@ -351,6 +353,20 @@ impl SidebarView {351
SidebarTab::Chats353
SidebarTab::Chats352
};354
};353
let collapsed_teams = load_collapsed_teams(&state.read(cx).store);355
let collapsed_teams = load_collapsed_teams(&state.read(cx).store);356
cx.spawn(async move |this, cx| {357
loop {358
cx.background_executor().timer(CALLS_REFRESH).await;359
let alive = this.update(cx, |view, cx| {360
if view.tab == SidebarTab::Calls {361
cx.notify();362
}363
});364
if alive.is_err() {365
break;366
}367
}368
})369
.detach();354
SidebarView {370
SidebarView {355
state,371
state,356
tab,372
tab,@@ -66,7 +66,35 @@ pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer
66
66
buffer
67
67
}
68
68
69
fn format_rank(frame_format: FrameFormat) -> u8 {
70
match frame_format {
71
FrameFormat::NV12 => 1,
72
_ => 0,
73
}
74
}
75
76
fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {
77
formats
78
.iter()
79
.copied()
80
.filter(|format| DIRECT_FORMATS.contains(&format.format()))
81
.filter(|format| format.frame_rate() >= CAPTURE_FPS && format.height() <= CAPTURE_HEIGHT)
82
.max_by_key(|format| (format.height(), format_rank(format.format()), format.frame_rate()))
83
}
84
85
fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
86
let mut camera = Camera::new(index, RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate))?;
87
let formats = camera.compatible_camera_formats()?;
88
let format = pick_format(&formats).ok_or_else(|| nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned()))?;
89
camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Exact(format)))?;
90
camera.open_stream()?;
91
Ok(camera)
92
}
93
69
94
fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
95
if let Ok(camera) = open_picked_format(index.clone()) {
96
return Ok(camera);
97
}
70
98
let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);
71
99
let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS
72
100
.into_iter()
@@ -234,6 +262,38 @@ mod tests {
234
262
assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());
235
263
}
236
264
265
fn format(width: u32, height: u32, frame_format: FrameFormat, fps: u32) -> CameraFormat {
266
CameraFormat::new(Resolution::new(width, height), frame_format, fps)
267
}
268
269
#[test]
270
fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {
271
let formats = [
272
format(1280, 720, FrameFormat::YUYV, 10),
273
format(640, 480, FrameFormat::YUYV, 30),
274
format(1280, 720, FrameFormat::MJPEG, 30),
275
];
276
assert_eq!(pick_format(&formats), Some(format(640, 480, FrameFormat::YUYV, 30)));
277
}
278
279
#[test]
280
fn the_largest_height_up_to_720_wins_then_nv12() {
281
let formats = [
282
format(1920, 1080, FrameFormat::NV12, 30),
283
format(640, 480, FrameFormat::NV12, 30),
284
format(1280, 720, FrameFormat::YUYV, 30),
285
format(1280, 720, FrameFormat::NV12, 30),
286
];
287
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));
288
}
289
290
#[test]
291
fn no_usable_format_picks_nothing() {
292
let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];
293
assert_eq!(pick_format(&formats), None);
294
assert_eq!(pick_format(&[]), None);
295
}
296
237
297
#[test]
238
298
fn camera_choices_map_to_indices_or_names() {
239
299
assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));
@@ -66,7 +66,35 @@ pub(crate) fn i420_from_rgba(rgba: &[u8], width: u32, height: u32) -> I420Buffer66
buffer66
buffer67
}67
}68
68
69
fn format_rank(frame_format: FrameFormat) -> u8 {70
match frame_format {71
FrameFormat::NV12 => 1,72
_ => 0,73
}74
}75
76
fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {77
formats78
.iter()79
.copied()80
.filter(|format| DIRECT_FORMATS.contains(&format.format()))81
.filter(|format| format.frame_rate() >= CAPTURE_FPS && format.height() <= CAPTURE_HEIGHT)82
.max_by_key(|format| (format.height(), format_rank(format.format()), format.frame_rate()))83
}84
85
fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {86
let mut camera = Camera::new(index, RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate))?;87
let formats = camera.compatible_camera_formats()?;88
let format = pick_format(&formats).ok_or_else(|| nokhwa::NokhwaError::GeneralError("no raw camera format at 30 fps".to_owned()))?;89
camera.set_camera_requset(RequestedFormat::new::<RgbAFormat>(RequestedFormatType::Exact(format)))?;90
camera.open_stream()?;91
Ok(camera)92
}93
69
fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {94
fn open_camera(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {95
if let Ok(camera) = open_picked_format(index.clone()) {96
return Ok(camera);97
}70
let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);98
let wanted = Resolution::new(CAPTURE_WIDTH, CAPTURE_HEIGHT);71
let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS99
let mut requests: Vec<RequestedFormatType> = DIRECT_FORMATS72
.into_iter()100
.into_iter()@@ -234,6 +262,38 @@ mod tests {234
assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());262
assert!(i420_from_nv12(&[0; 8], 4, 2).is_none());235
}263
}236
264
265
fn format(width: u32, height: u32, frame_format: FrameFormat, fps: u32) -> CameraFormat {266
CameraFormat::new(Resolution::new(width, height), frame_format, fps)267
}268
269
#[test]270
fn a_c920_like_list_picks_the_raw_format_that_runs_at_30_fps() {271
let formats = [272
format(1280, 720, FrameFormat::YUYV, 10),273
format(640, 480, FrameFormat::YUYV, 30),274
format(1280, 720, FrameFormat::MJPEG, 30),275
];276
assert_eq!(pick_format(&formats), Some(format(640, 480, FrameFormat::YUYV, 30)));277
}278
279
#[test]280
fn the_largest_height_up_to_720_wins_then_nv12() {281
let formats = [282
format(1920, 1080, FrameFormat::NV12, 30),283
format(640, 480, FrameFormat::NV12, 30),284
format(1280, 720, FrameFormat::YUYV, 30),285
format(1280, 720, FrameFormat::NV12, 30),286
];287
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));288
}289
290
#[test]291
fn no_usable_format_picks_nothing() {292
let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];293
assert_eq!(pick_format(&formats), None);294
assert_eq!(pick_format(&[]), None);295
}296
237
#[test]297
#[test]238
fn camera_choices_map_to_indices_or_names() {298
fn camera_choices_map_to_indices_or_names() {239
assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));299
assert!(matches!(camera_index(&DeviceChoice::SystemDefault), CameraIndex::Index(0)));@@ -335,7 +335,13 @@ impl<R: Remote> SyncEngine<R> {
335
335
};
336
336
self.refresh_section_settings(source).await;
337
337
let layout = self.refresh_team_layout(source).await;
338
folders.and(layout)
338
match (folders, layout) {
339
(Err(folders_error), Err(layout_error)) => {
340
Err(Error::Folders(format!("{folders_error}; {layout_error}")))
341
}
342
(Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),
343
(Ok(()), Ok(())) => Ok(()),
344
}
339
345
}
340
346
341
347
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {
@@ -335,7 +335,13 @@ impl<R: Remote> SyncEngine<R> {335
};335
};336
self.refresh_section_settings(source).await;336
self.refresh_section_settings(source).await;337
let layout = self.refresh_team_layout(source).await;337
let layout = self.refresh_team_layout(source).await;338
folders.and(layout)338
match (folders, layout) {339
(Err(folders_error), Err(layout_error)) => {340
Err(Error::Folders(format!("{folders_error}; {layout_error}")))341
}342
(Err(error), Ok(())) | (Ok(()), Err(error)) => Err(error),343
(Ok(()), Ok(())) => Ok(()),344
}339
}345
}340
346
341
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {347
async fn refresh_section_settings(&self, source: &Arc<dyn FolderSource>) {@@ -8,7 +8,7 @@ use graph::{
8
8
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,
9
9
};
10
10
use serde_json::json;
11
use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};
11
use store::{ChannelLayoutRecord, ChannelRecord, ChannelTabRecord, Store, TeamLayoutRecord, TeamRecord};
12
12
use teams_core::{
13
13
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,
14
14
DeltaPage, Error, FolderKind, FolderSource, MentionCandidate, MentionInput, MentionTarget,
@@ -2249,6 +2249,8 @@ struct FakeFolders {
2249
2249
channels: Vec<String>,
2250
2250
layout: Vec<TeamLayoutRecord>,
2251
2251
settings: ChatSectionSettings,
2252
folders_fail: bool,
2253
layout_fail: bool,
2252
2254
calls: Mutex<Vec<String>>,
2253
2255
}
2254
2256
@@ -2269,6 +2271,8 @@ impl FakeFolders {
2269
2271
channels: ids(&["ch1", "ch2"]),
2270
2272
layout: Vec::new(),
2271
2273
settings: ChatSectionSettings::default(),
2274
folders_fail: false,
2275
layout_fail: false,
2272
2276
calls: Mutex::new(Vec::new()),
2273
2277
})
2274
2278
}
@@ -2276,7 +2280,12 @@ impl FakeFolders {
2276
2280
2277
2281
impl FolderSource for FakeFolders {
2278
2282
fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> {
2279
Box::pin(async { Ok(self.state.lock().unwrap().clone()) })
2283
Box::pin(async {
2284
if self.folders_fail {
2285
return Err(Error::Folders("folders down".to_owned()));
2286
}
2287
Ok(self.state.lock().unwrap().clone())
2288
})
2280
2289
}
2281
2290
2282
2291
fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> {
@@ -2284,7 +2293,12 @@ impl FolderSource for FakeFolders {
2284
2293
}
2285
2294
2286
2295
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {
2287
Box::pin(async { Ok(self.layout.clone()) })
2296
Box::pin(async {
2297
if self.layout_fail {
2298
return Err(Error::Folders("layout down".to_owned()));
2299
}
2300
Ok(self.layout.clone())
2301
})
2288
2302
}
2289
2303
2290
2304
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {
@@ -2438,6 +2452,57 @@ async fn collapse_and_section_settings_go_through_the_source() {
2438
2452
);
2439
2453
}
2440
2454
2455
#[tokio::test]
2456
async fn a_failing_folder_list_still_stores_the_team_layout_and_tabs() {
2457
let fake = Arc::new(Fake::default());
2458
let mut source = FakeFolders::new();
2459
let source_mut = Arc::get_mut(&mut source).unwrap();
2460
source_mut.folders_fail = true;
2461
source_mut.layout = vec![TeamLayoutRecord {
2462
team_id: "alpha".into(),
2463
hidden: false,
2464
channels: vec![ChannelLayoutRecord {
2465
channel_id: "alpha-general".into(),
2466
general: true,
2467
hidden: false,
2468
tabs: vec![ChannelTabRecord {
2469
tab_id: "tab-1".into(),
2470
name: "Wiki".into(),
2471
definition_id: "com.microsoft.teamspace.tab.wiki".into(),
2472
open_url: None,
2473
}],
2474
notifications: Default::default(),
2475
}],
2476
}];
2477
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
2478
2479
let error = engine.refresh_folders().await.unwrap_err();
2480
2481
assert!(error.to_string().contains("folders down"));
2482
assert_eq!(engine.store().channel_tabs("alpha-general").unwrap().len(), 1);
2483
assert!(
2484
engine
2485
.store()
2486
.meta_time("team_layout_refreshed_at")
2487
.unwrap()
2488
.is_some()
2489
);
2490
}
2491
2492
#[tokio::test]
2493
async fn both_refresh_errors_are_reported_together() {
2494
let fake = Arc::new(Fake::default());
2495
let mut source = FakeFolders::new();
2496
let source_mut = Arc::get_mut(&mut source).unwrap();
2497
source_mut.folders_fail = true;
2498
source_mut.layout_fail = true;
2499
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());
2500
2501
let message = engine.refresh_folders().await.unwrap_err().to_string();
2502
2503
assert!(message.contains("folders down") && message.contains("layout down"));
2504
}
2505
2441
2506
#[tokio::test]
2442
2507
async fn team_layout_from_teams_orders_and_hides_the_sidebar() {
2443
2508
let fake = Arc::new(Fake::default());
@@ -8,7 +8,7 @@ use graph::{8
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,8
OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User,9
};9
};10
use serde_json::json;10
use serde_json::json;11
use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord};11
use store::{ChannelLayoutRecord, ChannelRecord, ChannelTabRecord, Store, TeamLayoutRecord, TeamRecord};12
use teams_core::{12
use teams_core::{13
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,13
Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent,14
DeltaPage, Error, FolderKind, FolderSource, MentionCandidate, MentionInput, MentionTarget,14
DeltaPage, Error, FolderKind, FolderSource, MentionCandidate, MentionInput, MentionTarget,@@ -2249,6 +2249,8 @@ struct FakeFolders {2249
channels: Vec<String>,2249
channels: Vec<String>,2250
layout: Vec<TeamLayoutRecord>,2250
layout: Vec<TeamLayoutRecord>,2251
settings: ChatSectionSettings,2251
settings: ChatSectionSettings,2252
folders_fail: bool,2253
layout_fail: bool,2252
calls: Mutex<Vec<String>>,2254
calls: Mutex<Vec<String>>,2253
}2255
}2254
2256
@@ -2269,6 +2271,8 @@ impl FakeFolders {2269
channels: ids(&["ch1", "ch2"]),2271
channels: ids(&["ch1", "ch2"]),2270
layout: Vec::new(),2272
layout: Vec::new(),2271
settings: ChatSectionSettings::default(),2273
settings: ChatSectionSettings::default(),2274
folders_fail: false,2275
layout_fail: false,2272
calls: Mutex::new(Vec::new()),2276
calls: Mutex::new(Vec::new()),2273
})2277
})2274
}2278
}@@ -2276,7 +2280,12 @@ impl FakeFolders {2276
2280
2277
impl FolderSource for FakeFolders {2281
impl FolderSource for FakeFolders {2278
fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> {2282
fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> {2279
Box::pin(async { Ok(self.state.lock().unwrap().clone()) })2283
Box::pin(async {2284
if self.folders_fail {2285
return Err(Error::Folders("folders down".to_owned()));2286
}2287
Ok(self.state.lock().unwrap().clone())2288
})2280
}2289
}2281
2290
2282
fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> {2291
fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> {@@ -2284,7 +2293,12 @@ impl FolderSource for FakeFolders {2284
}2293
}2285
2294
2286
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {2295
fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> {2287
Box::pin(async { Ok(self.layout.clone()) })2296
Box::pin(async {2297
if self.layout_fail {2298
return Err(Error::Folders("layout down".to_owned()));2299
}2300
Ok(self.layout.clone())2301
})2288
}2302
}2289
2303
2290
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {2304
fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> {@@ -2438,6 +2452,57 @@ async fn collapse_and_section_settings_go_through_the_source() {2438
);2452
);2439
}2453
}2440
2454
2455
#[tokio::test]2456
async fn a_failing_folder_list_still_stores_the_team_layout_and_tabs() {2457
let fake = Arc::new(Fake::default());2458
let mut source = FakeFolders::new();2459
let source_mut = Arc::get_mut(&mut source).unwrap();2460
source_mut.folders_fail = true;2461
source_mut.layout = vec![TeamLayoutRecord {2462
team_id: "alpha".into(),2463
hidden: false,2464
channels: vec![ChannelLayoutRecord {2465
channel_id: "alpha-general".into(),2466
general: true,2467
hidden: false,2468
tabs: vec![ChannelTabRecord {2469
tab_id: "tab-1".into(),2470
name: "Wiki".into(),2471
definition_id: "com.microsoft.teamspace.tab.wiki".into(),2472
open_url: None,2473
}],2474
notifications: Default::default(),2475
}],2476
}];2477
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());2478
2479
let error = engine.refresh_folders().await.unwrap_err();2480
2481
assert!(error.to_string().contains("folders down"));2482
assert_eq!(engine.store().channel_tabs("alpha-general").unwrap().len(), 1);2483
assert!(2484
engine2485
.store()2486
.meta_time("team_layout_refreshed_at")2487
.unwrap()2488
.is_some()2489
);2490
}2491
2492
#[tokio::test]2493
async fn both_refresh_errors_are_reported_together() {2494
let fake = Arc::new(Fake::default());2495
let mut source = FakeFolders::new();2496
let source_mut = Arc::get_mut(&mut source).unwrap();2497
source_mut.folders_fail = true;2498
source_mut.layout_fail = true;2499
let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone());2500
2501
let message = engine.refresh_folders().await.unwrap_err().to_string();2502
2503
assert!(message.contains("folders down") && message.contains("layout down"));2504
}2505
2441
#[tokio::test]2506
#[tokio::test]2442
async fn team_layout_from_teams_orders_and_hides_the_sidebar() {2507
async fn team_layout_from_teams_orders_and_hides_the_sidebar() {2443
let fake = Arc::new(Fake::default());2508
let fake = Arc::new(Fake::default());