fix(mcp): demo runs bind a free port instead of the real 47615
- `teams --demo` picks a free localhost port unless RUSTY_TEAMS_MCP_PORT is set. WSL shares localhost with Windows, so demo sweeps blocked the Windows app's MCP server. - Demo install/reinstall of agent configs writes to a temp sandbox home, never the real ones. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -28,9 +28,14 @@ impl Kind {
28
28
}
29
29
30
30
fn from_key(key: &str) -> Option<Kind> {
31
[Kind::Messages, Kind::Mention, Kind::Reaction, Kind::MissedCall]
32
.into_iter()
33
.find(|kind| kind.key() == key)
31
[
32
Kind::Messages,
33
Kind::Mention,
34
Kind::Reaction,
35
Kind::MissedCall,
36
]
37
.into_iter()
38
.find(|kind| kind.key() == key)
34
39
}
35
40
}
36
41
@@ -346,7 +351,10 @@ impl Feed {
346
351
let open_row = self.entries.iter().position(|entry| {
347
352
entry.kind == Kind::MissedCall
348
353
&& !entry.read
349
&& entry.actors.first().is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
354
&& entry
355
.actors
356
.first()
357
.is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)
350
358
});
351
359
match open_row {
352
360
Some(index) => {
@@ -872,7 +880,10 @@ mod tests {
872
880
#[test]
873
881
fn a_missed_call_is_one_row_per_caller_until_it_is_read() {
874
882
let mut feed = Feed::load(Vec::new());
875
let caller = Actor { user_id: Some("u1".into()), name: "Cara".into() };
883
let caller = Actor {
884
user_id: Some("u1".into()),
885
name: "Cara".into(),
886
};
876
887
feed.record_missed_call("19:dm", caller.clone(), at(9, 0));
877
888
feed.record_missed_call("19:dm", caller.clone(), at(9, 5));
878
889
assert_eq!(feed.unread_count(), 1);
@@ -883,14 +894,28 @@ mod tests {
883
894
feed.mark_all_read();
884
895
feed.record_missed_call("19:dm", caller, at(10, 0));
885
896
assert_eq!(feed.unread_count(), 1);
886
feed.record_missed_call("19:other", Actor { user_id: Some("u2".into()), name: "Dan".into() }, at(10, 1));
897
feed.record_missed_call(
898
"19:other",
899
Actor {
900
user_id: Some("u2".into()),
901
name: "Dan".into(),
902
},
903
at(10, 1),
904
);
887
905
assert_eq!(feed.unread_count(), 2);
888
906
}
889
907
890
908
#[test]
891
909
fn missed_calls_survive_the_store_round_trip() {
892
910
let mut feed = Feed::load(Vec::new());
893
feed.record_missed_call("19:dm", Actor { user_id: Some("u1".into()), name: "Cara".into() }, at(9, 0));
911
feed.record_missed_call(
912
"19:dm",
913
Actor {
914
user_id: Some("u1".into()),
915
name: "Cara".into(),
916
},
917
at(9, 0),
918
);
894
919
let record = feed.get(1).unwrap().to_record();
895
920
assert_eq!(record.kind, "missed_call");
896
921
let restored = Entry::from_record(record).unwrap();
@@ -28,9 +28,14 @@ impl Kind {28
}28
}29
29
30
fn from_key(key: &str) -> Option<Kind> {30
fn from_key(key: &str) -> Option<Kind> {31
[Kind::Messages, Kind::Mention, Kind::Reaction, Kind::MissedCall]31
[32
.into_iter()32
Kind::Messages,33
.find(|kind| kind.key() == key)33
Kind::Mention,34
Kind::Reaction,35
Kind::MissedCall,36
]37
.into_iter()38
.find(|kind| kind.key() == key)34
}39
}35
}40
}36
41
@@ -346,7 +351,10 @@ impl Feed {346
let open_row = self.entries.iter().position(|entry| {351
let open_row = self.entries.iter().position(|entry| {347
entry.kind == Kind::MissedCall352
entry.kind == Kind::MissedCall348
&& !entry.read353
&& !entry.read349
&& entry.actors.first().is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)354
&& entry355
.actors356
.first()357
.is_some_and(|known| known.user_id == actor.user_id && known.name == actor.name)350
});358
});351
match open_row {359
match open_row {352
Some(index) => {360
Some(index) => {@@ -872,7 +880,10 @@ mod tests {872
#[test]880
#[test]873
fn a_missed_call_is_one_row_per_caller_until_it_is_read() {881
fn a_missed_call_is_one_row_per_caller_until_it_is_read() {874
let mut feed = Feed::load(Vec::new());882
let mut feed = Feed::load(Vec::new());875
let caller = Actor { user_id: Some("u1".into()), name: "Cara".into() };883
let caller = Actor {884
user_id: Some("u1".into()),885
name: "Cara".into(),886
};876
feed.record_missed_call("19:dm", caller.clone(), at(9, 0));887
feed.record_missed_call("19:dm", caller.clone(), at(9, 0));877
feed.record_missed_call("19:dm", caller.clone(), at(9, 5));888
feed.record_missed_call("19:dm", caller.clone(), at(9, 5));878
assert_eq!(feed.unread_count(), 1);889
assert_eq!(feed.unread_count(), 1);@@ -883,14 +894,28 @@ mod tests {883
feed.mark_all_read();894
feed.mark_all_read();884
feed.record_missed_call("19:dm", caller, at(10, 0));895
feed.record_missed_call("19:dm", caller, at(10, 0));885
assert_eq!(feed.unread_count(), 1);896
assert_eq!(feed.unread_count(), 1);886
feed.record_missed_call("19:other", Actor { user_id: Some("u2".into()), name: "Dan".into() }, at(10, 1));897
feed.record_missed_call(898
"19:other",899
Actor {900
user_id: Some("u2".into()),901
name: "Dan".into(),902
},903
at(10, 1),904
);887
assert_eq!(feed.unread_count(), 2);905
assert_eq!(feed.unread_count(), 2);888
}906
}889
907
890
#[test]908
#[test]891
fn missed_calls_survive_the_store_round_trip() {909
fn missed_calls_survive_the_store_round_trip() {892
let mut feed = Feed::load(Vec::new());910
let mut feed = Feed::load(Vec::new());893
feed.record_missed_call("19:dm", Actor { user_id: Some("u1".into()), name: "Cara".into() }, at(9, 0));911
feed.record_missed_call(912
"19:dm",913
Actor {914
user_id: Some("u1".into()),915
name: "Cara".into(),916
},917
at(9, 0),918
);894
let record = feed.get(1).unwrap().to_record();919
let record = feed.get(1).unwrap().to_record();895
assert_eq!(record.kind, "missed_call");920
assert_eq!(record.kind, "missed_call");896
let restored = Entry::from_record(record).unwrap();921
let restored = Entry::from_record(record).unwrap();@@ -79,12 +79,20 @@ impl ActivityCenter {
79
79
}
80
80
81
81
fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {
82
let conversation_id = self.app.read(cx).conversation_of_missed_call(missed).unwrap_or_default();
82
let conversation_id = self
83
.app
84
.read(cx)
85
.conversation_of_missed_call(missed)
86
.unwrap_or_default();
83
87
let actor = Actor {
84
user_id: missed.caller_mri.strip_prefix("8:orgid:").map(str::to_owned),
88
user_id: missed
89
.caller_mri
90
.strip_prefix("8:orgid:")
91
.map(str::to_owned),
85
92
name: missed.caller_name.clone(),
86
93
};
87
self.feed.record_missed_call(&conversation_id, actor, missed.at);
94
self.feed
95
.record_missed_call(&conversation_id, actor, missed.at);
88
96
self.flush(cx);
89
97
}
90
98
@@ -79,12 +79,20 @@ impl ActivityCenter {79
}79
}80
80
81
fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {81
fn on_missed_call(&mut self, missed: &MissedCall, cx: &mut Context<Self>) {82
let conversation_id = self.app.read(cx).conversation_of_missed_call(missed).unwrap_or_default();82
let conversation_id = self83
.app84
.read(cx)85
.conversation_of_missed_call(missed)86
.unwrap_or_default();83
let actor = Actor {87
let actor = Actor {84
user_id: missed.caller_mri.strip_prefix("8:orgid:").map(str::to_owned),88
user_id: missed89
.caller_mri90
.strip_prefix("8:orgid:")91
.map(str::to_owned),85
name: missed.caller_name.clone(),92
name: missed.caller_name.clone(),86
};93
};87
self.feed.record_missed_call(&conversation_id, actor, missed.at);94
self.feed95
.record_missed_call(&conversation_id, actor, missed.at);88
self.flush(cx);96
self.flush(cx);89
}97
}90
98
@@ -6,6 +6,7 @@ use std::sync::Arc;
6
6
7
7
use chrono::{DateTime, Local};
8
8
use gpui_kit::*;
9
use mcp::install::{Homes, Location};
9
10
use mcp::{Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ServerHandle};
10
11
use store::Store;
11
12
@@ -45,6 +46,7 @@ pub struct AgentApi {
45
46
status: ServerStatus,
46
47
generation: u64,
47
48
reinstall_note: Option<String>,
49
demo: bool,
48
50
}
49
51
50
52
struct AgentApiHandle(Entity<AgentApi>);
@@ -57,6 +59,35 @@ pub fn endpoint_url(port: u16) -> String {
57
59
format!("http://127.0.0.1:{port}/mcp")
58
60
}
59
61
62
fn demo_port(configured: Option<String>) -> u16 {
63
configured
64
.and_then(|value| value.parse().ok())
65
.or_else(|| {
66
std::net::TcpListener::bind(("127.0.0.1", 0))
67
.and_then(|listener| listener.local_addr())
68
.map(|addr| addr.port())
69
.ok()
70
})
71
.unwrap_or_default()
72
}
73
74
pub fn is_demo(cx: &App) -> bool {
75
handle(cx).is_some_and(|api| api.read(cx).demo)
76
}
77
78
pub fn agent_homes(demo: bool) -> Homes {
79
if demo {
80
Homes {
81
entries: vec![(
82
Location::Native,
83
std::env::temp_dir().join("rusty-teams-demo-home"),
84
)],
85
}
86
} else {
87
Homes::detect()
88
}
89
}
90
60
91
pub fn agent_label(agent: Option<&str>) -> &'static str {
61
92
match agent.map(str::to_ascii_lowercase).as_deref() {
62
93
Some("claude") => "Claude",
@@ -69,18 +100,11 @@ pub fn agent_label(agent: Option<&str>) -> &'static str {
69
100
pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
70
101
let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();
71
102
let mut policy = mcp::load_policy(&store);
72
if demo
73
&& let Some(port) = std::env::var(DEMO_PORT_ENV)
74
.ok()
75
.and_then(|value| value.parse().ok())
76
{
77
policy.port = port;
103
if demo {
104
policy.port = demo_port(std::env::var(DEMO_PORT_ENV).ok());
78
105
}
79
106
let hub = AgentHub::new(store.clone(), policy, ui);
80
107
let token = mcp::load_or_create_token(&store).unwrap_or_default();
81
if demo {
82
println!("mcp: {} token={token}", endpoint_url(hub.policy().port));
83
}
84
108
let source = Arc::new(AppSource::new(store.clone()));
85
109
let api = cx.new(|_| AgentApi {
86
110
hub,
@@ -92,6 +116,7 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {
92
116
status: ServerStatus::Off,
93
117
generation: 0,
94
118
reinstall_note: None,
119
demo,
95
120
});
96
121
bridge::drain_ui_events(receiver, api.downgrade(), cx);
97
122
api.update(cx, |api, cx| {
@@ -281,8 +306,9 @@ impl AgentApi {
281
306
url: endpoint_url(self.hub.policy().port),
282
307
token: self.token.clone(),
283
308
};
309
let demo = self.demo;
284
310
let task = cx.background_spawn(async move {
285
mcp::install::reinstall_all(&endpoint, &mcp::install::Homes::detect())
311
mcp::install::reinstall_all(&endpoint, &agent_homes(demo))
286
312
});
287
313
cx.spawn(async move |this, cx| {
288
314
let results = task.await;
@@ -389,6 +415,9 @@ impl AgentApi {
389
415
}
390
416
match result {
391
417
Ok(server) => {
418
if self.demo {
419
println!("mcp: {} token={}", endpoint_url(port), self.token);
420
}
392
421
self.server = Some(server);
393
422
self.status = ServerStatus::Running(port);
394
423
}
@@ -403,7 +432,16 @@ impl AgentApi {
403
432
404
433
#[cfg(test)]
405
434
mod tests {
406
use super::agent_label;
435
use super::{agent_label, demo_port};
436
437
#[test]
438
fn demo_port_is_free_unless_configured() {
439
let picked = demo_port(None);
440
assert_ne!(picked, 0);
441
assert!(std::net::TcpListener::bind(("127.0.0.1", picked)).is_ok());
442
assert_ne!(demo_port(Some("not a port".into())), 0);
443
assert_eq!(demo_port(Some("48000".into())), 48000);
444
}
407
445
408
446
#[test]
409
447
fn agent_labels_know_the_common_agents() {
@@ -6,6 +6,7 @@ use std::sync::Arc;6
6
7
use chrono::{DateTime, Local};7
use chrono::{DateTime, Local};8
use gpui_kit::*;8
use gpui_kit::*;9
use mcp::install::{Homes, Location};9
use mcp::{Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ServerHandle};10
use mcp::{Access, AgentHub, AgentPolicy, McpEndpoint, Outcome, Proposal, ServerHandle};10
use store::Store;11
use store::Store;11
12
@@ -45,6 +46,7 @@ pub struct AgentApi {45
status: ServerStatus,46
status: ServerStatus,46
generation: u64,47
generation: u64,47
reinstall_note: Option<String>,48
reinstall_note: Option<String>,49
demo: bool,48
}50
}49
51
50
struct AgentApiHandle(Entity<AgentApi>);52
struct AgentApiHandle(Entity<AgentApi>);@@ -57,6 +59,35 @@ pub fn endpoint_url(port: u16) -> String {57
format!("http://127.0.0.1:{port}/mcp")59
format!("http://127.0.0.1:{port}/mcp")58
}60
}59
61
62
fn demo_port(configured: Option<String>) -> u16 {63
configured64
.and_then(|value| value.parse().ok())65
.or_else(|| {66
std::net::TcpListener::bind(("127.0.0.1", 0))67
.and_then(|listener| listener.local_addr())68
.map(|addr| addr.port())69
.ok()70
})71
.unwrap_or_default()72
}73
74
pub fn is_demo(cx: &App) -> bool {75
handle(cx).is_some_and(|api| api.read(cx).demo)76
}77
78
pub fn agent_homes(demo: bool) -> Homes {79
if demo {80
Homes {81
entries: vec![(82
Location::Native,83
std::env::temp_dir().join("rusty-teams-demo-home"),84
)],85
}86
} else {87
Homes::detect()88
}89
}90
60
pub fn agent_label(agent: Option<&str>) -> &'static str {91
pub fn agent_label(agent: Option<&str>) -> &'static str {61
match agent.map(str::to_ascii_lowercase).as_deref() {92
match agent.map(str::to_ascii_lowercase).as_deref() {62
Some("claude") => "Claude",93
Some("claude") => "Claude",@@ -69,18 +100,11 @@ pub fn agent_label(agent: Option<&str>) -> &'static str {69
pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {100
pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {70
let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();101
let (ui, receiver) = tokio::sync::mpsc::unbounded_channel();71
let mut policy = mcp::load_policy(&store);102
let mut policy = mcp::load_policy(&store);72
if demo103
if demo {73
&& let Some(port) = std::env::var(DEMO_PORT_ENV)104
policy.port = demo_port(std::env::var(DEMO_PORT_ENV).ok());74
.ok()75
.and_then(|value| value.parse().ok())76
{77
policy.port = port;78
}105
}79
let hub = AgentHub::new(store.clone(), policy, ui);106
let hub = AgentHub::new(store.clone(), policy, ui);80
let token = mcp::load_or_create_token(&store).unwrap_or_default();107
let token = mcp::load_or_create_token(&store).unwrap_or_default();81
if demo {82
println!("mcp: {} token={token}", endpoint_url(hub.policy().port));83
}84
let source = Arc::new(AppSource::new(store.clone()));108
let source = Arc::new(AppSource::new(store.clone()));85
let api = cx.new(|_| AgentApi {109
let api = cx.new(|_| AgentApi {86
hub,110
hub,@@ -92,6 +116,7 @@ pub fn init(store: Arc<Store>, demo: bool, cx: &mut App) {92
status: ServerStatus::Off,116
status: ServerStatus::Off,93
generation: 0,117
generation: 0,94
reinstall_note: None,118
reinstall_note: None,119
demo,95
});120
});96
bridge::drain_ui_events(receiver, api.downgrade(), cx);121
bridge::drain_ui_events(receiver, api.downgrade(), cx);97
api.update(cx, |api, cx| {122
api.update(cx, |api, cx| {@@ -281,8 +306,9 @@ impl AgentApi {281
url: endpoint_url(self.hub.policy().port),306
url: endpoint_url(self.hub.policy().port),282
token: self.token.clone(),307
token: self.token.clone(),283
};308
};309
let demo = self.demo;284
let task = cx.background_spawn(async move {310
let task = cx.background_spawn(async move {285
mcp::install::reinstall_all(&endpoint, &mcp::install::Homes::detect())311
mcp::install::reinstall_all(&endpoint, &agent_homes(demo))286
});312
});287
cx.spawn(async move |this, cx| {313
cx.spawn(async move |this, cx| {288
let results = task.await;314
let results = task.await;@@ -389,6 +415,9 @@ impl AgentApi {389
}415
}390
match result {416
match result {391
Ok(server) => {417
Ok(server) => {418
if self.demo {419
println!("mcp: {} token={}", endpoint_url(port), self.token);420
}392
self.server = Some(server);421
self.server = Some(server);393
self.status = ServerStatus::Running(port);422
self.status = ServerStatus::Running(port);394
}423
}@@ -403,7 +432,16 @@ impl AgentApi {403
432
404
#[cfg(test)]433
#[cfg(test)]405
mod tests {434
mod tests {406
use super::agent_label;435
use super::{agent_label, demo_port};436
437
#[test]438
fn demo_port_is_free_unless_configured() {439
let picked = demo_port(None);440
assert_ne!(picked, 0);441
assert!(std::net::TcpListener::bind(("127.0.0.1", picked)).is_ok());442
assert_ne!(demo_port(Some("not a port".into())), 0);443
assert_eq!(demo_port(Some("48000".into())), 48000);444
}407
445
408
#[test]446
#[test]409
fn agent_labels_know_the_common_agents() {447
fn agent_labels_know_the_common_agents() {@@ -13,7 +13,6 @@ use teams_core::{
13
13
14
14
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};
15
15
use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16
use calling::meeting::LiveMeeting;
17
16
use crate::card_state::{CardState, TaskDialogState};
18
17
use crate::data::{self, Directory};
19
18
use crate::image_view_gallery::ViewerRequest;
@@ -23,6 +22,7 @@ use crate::notice::Notice;
23
22
use crate::profile_state::{ProfileCache, ProfileRequest};
24
23
use crate::translation::TranslationState;
25
24
use crate::typing::TypingState;
25
use calling::meeting::LiveMeeting;
26
26
27
27
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";
28
28
const RECENT_MESSAGES_FOR_TYPING: usize = 5;
@@ -781,7 +781,9 @@ impl AppState {
781
781
BackendEvent::Calendar(events) => self.apply_calendar(events, cx),
782
782
BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),
783
783
BackendEvent::Ring(event) => self.on_engine_event(event, cx),
784
BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),
784
BackendEvent::ThreadChanged(conversation_id) => {
785
self.on_thread_changed(&conversation_id, cx)
786
}
785
787
BackendEvent::Engine(engine) => {
786
788
crate::agent_api::engine_ready(engine.clone(), cx);
787
789
self.engine = Some(engine);
@@ -13,7 +13,6 @@ use teams_core::{13
13
14
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};14
use crate::backend::{BackendEvent, ConnectionState, Engine, LiveState};15
use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};15
use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};16
use calling::meeting::LiveMeeting;17
use crate::card_state::{CardState, TaskDialogState};16
use crate::card_state::{CardState, TaskDialogState};18
use crate::data::{self, Directory};17
use crate::data::{self, Directory};19
use crate::image_view_gallery::ViewerRequest;18
use crate::image_view_gallery::ViewerRequest;@@ -23,6 +22,7 @@ use crate::notice::Notice;23
use crate::profile_state::{ProfileCache, ProfileRequest};22
use crate::profile_state::{ProfileCache, ProfileRequest};24
use crate::translation::TranslationState;23
use crate::translation::TranslationState;25
use crate::typing::TypingState;24
use crate::typing::TypingState;25
use calling::meeting::LiveMeeting;26
26
27
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";27
const COLLAPSED_META_KEY: &str = "ui.collapsed_sections";28
const RECENT_MESSAGES_FOR_TYPING: usize = 5;28
const RECENT_MESSAGES_FOR_TYPING: usize = 5;@@ -781,7 +781,9 @@ impl AppState {781
BackendEvent::Calendar(events) => self.apply_calendar(events, cx),781
BackendEvent::Calendar(events) => self.apply_calendar(events, cx),782
BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),782
BackendEvent::CalendarNudge(nudge) => self.calendar_nudge = Some(nudge),783
BackendEvent::Ring(event) => self.on_engine_event(event, cx),783
BackendEvent::Ring(event) => self.on_engine_event(event, cx),784
BackendEvent::ThreadChanged(conversation_id) => self.on_thread_changed(&conversation_id, cx),784
BackendEvent::ThreadChanged(conversation_id) => {785
self.on_thread_changed(&conversation_id, cx)786
}785
BackendEvent::Engine(engine) => {787
BackendEvent::Engine(engine) => {786
crate::agent_api::engine_ready(engine.clone(), cx);788
crate::agent_api::engine_ready(engine.clone(), cx);787
self.engine = Some(engine);789
self.engine = Some(engine);@@ -2,7 +2,10 @@ use std::sync::Arc;
2
2
use std::time::Duration;
3
3
4
4
use calling::EngineEvent;
5
use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent};
5
use chatsvc::{
6
Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig,
7
RealtimeEvent, StatusKind, TypingEvent,
8
};
6
9
use chrono::{DateTime, Local, Offset, Utc};
7
10
use graph::Graph;
8
11
use session::{Session, SessionConfig, Transport};
@@ -410,7 +413,10 @@ async fn calendar_loop(session: Session, events: EventSender) {
410
413
return;
411
414
}
412
415
}
413
Err(error) => crate::diagnostics::record(format!("calls: calendar not loaded: {}", shorten(&error.to_string()))),
416
Err(error) => crate::diagnostics::record(format!(
417
"calls: calendar not loaded: {}",
418
shorten(&error.to_string())
419
)),
414
420
}
415
421
}
416
422
}
@@ -486,8 +492,14 @@ mod tests {
486
492
thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),
487
493
Some("c")
488
494
);
489
assert_eq!(thread_signal(&event(EventKind::Typing, Some("c"), None)), None);
490
assert_eq!(thread_signal(&event(EventKind::ThreadUpdate, None, None)), None);
495
assert_eq!(
496
thread_signal(&event(EventKind::Typing, Some("c"), None)),
497
None
498
);
499
assert_eq!(
500
thread_signal(&event(EventKind::ThreadUpdate, None, None)),
501
None
502
);
491
503
}
492
504
493
505
#[test]
@@ -517,8 +529,14 @@ mod tests {
517
529
518
530
#[test]
519
531
fn only_connect_and_disconnect_move_the_link() {
520
assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected));
521
assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected));
532
assert_eq!(
533
link_signal_for(StatusKind::Connected),
534
Some(LinkSignal::Connected)
535
);
536
assert_eq!(
537
link_signal_for(StatusKind::Disconnected),
538
Some(LinkSignal::Disconnected)
539
);
522
540
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
523
541
assert_eq!(link_signal_for(StatusKind::Error), None);
524
542
}
@@ -2,7 +2,10 @@ use std::sync::Arc;2
use std::time::Duration;2
use std::time::Duration;3
3
4
use calling::EngineEvent;4
use calling::EngineEvent;5
use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent};5
use chatsvc::{6
Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig,7
RealtimeEvent, StatusKind, TypingEvent,8
};6
use chrono::{DateTime, Local, Offset, Utc};9
use chrono::{DateTime, Local, Offset, Utc};7
use graph::Graph;10
use graph::Graph;8
use session::{Session, SessionConfig, Transport};11
use session::{Session, SessionConfig, Transport};@@ -410,7 +413,10 @@ async fn calendar_loop(session: Session, events: EventSender) {410
return;413
return;411
}414
}412
}415
}413
Err(error) => crate::diagnostics::record(format!("calls: calendar not loaded: {}", shorten(&error.to_string()))),416
Err(error) => crate::diagnostics::record(format!(417
"calls: calendar not loaded: {}",418
shorten(&error.to_string())419
)),414
}420
}415
}421
}416
}422
}@@ -486,8 +492,14 @@ mod tests {486
thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),492
thread_signal(&event(EventKind::NewMessage, Some("c"), Some("m"))).as_deref(),487
Some("c")493
Some("c")488
);494
);489
assert_eq!(thread_signal(&event(EventKind::Typing, Some("c"), None)), None);495
assert_eq!(490
assert_eq!(thread_signal(&event(EventKind::ThreadUpdate, None, None)), None);496
thread_signal(&event(EventKind::Typing, Some("c"), None)),497
None498
);499
assert_eq!(500
thread_signal(&event(EventKind::ThreadUpdate, None, None)),501
None502
);491
}503
}492
504
493
#[test]505
#[test]@@ -517,8 +529,14 @@ mod tests {517
529
518
#[test]530
#[test]519
fn only_connect_and_disconnect_move_the_link() {531
fn only_connect_and_disconnect_move_the_link() {520
assert_eq!(link_signal_for(StatusKind::Connected), Some(LinkSignal::Connected));532
assert_eq!(521
assert_eq!(link_signal_for(StatusKind::Disconnected), Some(LinkSignal::Disconnected));533
link_signal_for(StatusKind::Connected),534
Some(LinkSignal::Connected)535
);536
assert_eq!(537
link_signal_for(StatusKind::Disconnected),538
Some(LinkSignal::Disconnected)539
);522
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);540
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);523
assert_eq!(link_signal_for(StatusKind::Error), None);541
assert_eq!(link_signal_for(StatusKind::Error), None);524
}542
}@@ -2,13 +2,18 @@ use std::time::{Duration, Instant};
2
2
3
3
use calling::meeting::LiveMeeting;
4
4
use calling::{
5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice, EndReason, EngineEvent, MuteCommand, Reaction, RingSignal,
6
ShareSource, VideoKey,
5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice,
6
EndReason, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7
7
};
8
8
use gpui_kit::*;
9
9
10
use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};
11
use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};
10
use super::background::{
11
BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds,
12
};
13
use super::demo::{
14
DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,
15
start_demo_scene_call,
16
};
12
17
use super::features::room_closed_move;
13
18
use super::media::CallMedia;
14
19
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
@@ -120,7 +125,11 @@ impl AppState {
120
125
self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
121
126
return;
122
127
};
123
let guests = if conversation_id == DEMO_LOBBY_MEETING { DEMO_SMALL_MEETING } else { DEMO_CROWD };
128
let guests = if conversation_id == DEMO_LOBBY_MEETING {
129
DEMO_SMALL_MEETING
130
} else {
131
DEMO_CROWD
132
};
124
133
let demo = DemoCall::Meeting {
125
134
guests: demo_guests(guests),
126
135
lobby: conversation_id == DEMO_LOBBY_MEETING,
@@ -139,7 +148,12 @@ impl AppState {
139
148
}
140
149
}
141
150
142
pub(super) fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {
151
pub(super) fn place_call(
152
&mut self,
153
spec: CallSpec,
154
demo: DemoCall,
155
cx: &mut Context<Self>,
156
) -> Option<CallHandle> {
143
157
if self.mode.demo {
144
158
return Some(start_demo_call(demo));
145
159
}
@@ -165,8 +179,18 @@ impl AppState {
165
179
) {
166
180
self.call_count += 1;
167
181
let call_id = self.call_count;
168
let CallHandle { commands, updates, video } = handle;
169
self.call = Some(ActiveCall::new(call_id, model, commands, conversation_id, video));
182
let CallHandle {
183
commands,
184
updates,
185
video,
186
} = handle;
187
self.call = Some(ActiveCall::new(
188
call_id,
189
model,
190
commands,
191
conversation_id,
192
video,
193
));
170
194
if self.call_share_sound {
171
195
self.send_call_command(CallCommand::SetShareSound(true));
172
196
}
@@ -195,7 +219,8 @@ impl AppState {
195
219
) {
196
220
cx.spawn(async move |this, cx| {
197
221
while let Some(update) = updates.recv().await {
198
let alive = this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
222
let alive =
223
this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));
199
224
if alive.is_err() {
200
225
return;
201
226
}
@@ -227,14 +252,22 @@ impl AppState {
227
252
}
228
253
229
254
fn end_orphaned_call(&mut self, call_id: u64, cx: &mut Context<Self>) {
230
let still_open = self.call.as_ref().is_some_and(|call| call.id == call_id && call.model.is_active());
255
let still_open = self
256
.call
257
.as_ref()
258
.is_some_and(|call| call.id == call_id && call.model.is_active());
231
259
if still_open {
232
260
let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
233
261
self.apply_call_update(call_id, CallUpdate::State(CallState::Ended { reason }), cx);
234
262
}
235
263
}
236
264
237
pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
265
pub(super) fn apply_call_update(
266
&mut self,
267
call_id: u64,
268
update: CallUpdate,
269
cx: &mut Context<Self>,
270
) {
238
271
let media = self.call_media.clone();
239
272
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
240
273
return;
@@ -291,7 +324,10 @@ impl AppState {
291
324
};
292
325
let elapsed = call.model.elapsed(Instant::now());
293
326
let notice = ended_notice(&reason, elapsed, &call.model.peer_name);
294
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));
327
let next_move = call
328
.pending_move
329
.take()
330
.or_else(|| room_closed_move(call, &reason));
295
331
let consult = call.consult.take();
296
332
call.pictures.clear(cx);
297
333
if let Some(thread) = call.chat_thread() {
@@ -317,14 +353,21 @@ impl AppState {
317
353
}
318
354
319
355
pub fn toggle_call_mute(&mut self, _cx: &mut Context<Self>) {
320
let can_toggle = self.call.as_ref().is_some_and(|call| call.model.can_unmute());
356
let can_toggle = self
357
.call
358
.as_ref()
359
.is_some_and(|call| call.model.can_unmute());
321
360
if can_toggle {
322
361
self.send_call_command(CallCommand::Mute(MuteCommand::Toggle));
323
362
}
324
363
}
325
364
326
365
pub fn toggle_call_camera(&mut self, _cx: &mut Context<Self>) {
327
let Some(call) = self.call.as_ref().filter(|call| call.model.can_use_camera()) else {
366
let Some(call) = self
367
.call
368
.as_ref()
369
.filter(|call| call.model.can_use_camera())
370
else {
328
371
return;
329
372
};
330
373
let on = !call.model.camera_on;
@@ -368,7 +411,10 @@ impl AppState {
368
411
}
369
412
370
413
pub fn refresh_share_sources(&self) {
371
let idle = self.call.as_ref().is_some_and(|call| call.model.local_share.is_none());
414
let idle = self
415
.call
416
.as_ref()
417
.is_some_and(|call| call.model.local_share.is_none());
372
418
if idle {
373
419
self.send_call_command(CallCommand::RefreshShareSources);
374
420
}
@@ -379,7 +425,10 @@ impl AppState {
379
425
}
380
426
381
427
pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {
382
let allowed = self.call.as_ref().is_some_and(|call| call.model.can_end_meeting);
428
let allowed = self
429
.call
430
.as_ref()
431
.is_some_and(|call| call.model.can_end_meeting);
383
432
if allowed {
384
433
self.send_call_command(CallCommand::EndMeeting);
385
434
}
@@ -406,7 +455,11 @@ impl AppState {
406
455
}
407
456
408
457
pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {
409
let Some(call) = self.call.as_mut().filter(|call| call.chat_thread().is_some()) else {
458
let Some(call) = self
459
.call
460
.as_mut()
461
.filter(|call| call.chat_thread().is_some())
462
else {
410
463
return;
411
464
};
412
465
call.chat_open = !call.chat_open;
@@ -420,15 +473,31 @@ impl AppState {
420
473
}
421
474
422
475
pub fn call_chat_unread(&self) -> u32 {
423
let Some(thread) = self.call.as_ref().filter(|call| !call.chat_open).and_then(|call| call.chat_thread()) else {
476
let Some(thread) = self
477
.call
478
.as_ref()
479
.filter(|call| !call.chat_open)
480
.and_then(|call| call.chat_thread())
481
else {
424
482
return 0;
425
483
};
426
484
let counted = self.directory.unread_counts.get(thread).copied();
427
counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))
485
counted.unwrap_or_else(|| {
486
u32::from(
487
self.sidebar
488
.chats
489
.iter()
490
.any(|chat| chat.id == thread && chat.unread),
491
)
492
})
428
493
}
429
494
430
495
pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {
431
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {
496
let Some(call) = self
497
.call
498
.as_mut()
499
.filter(|call| call.model.is_active() && call.model.has_reaction_controls())
500
else {
432
501
return;
433
502
};
434
503
let raised = call.model.own_hand.is_none();
@@ -442,21 +511,31 @@ impl AppState {
442
511
}
443
512
444
513
pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {
445
let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands());
514
let allowed = self
515
.call
516
.as_ref()
517
.is_some_and(|call| call.model.can_lower_hands());
446
518
if allowed {
447
519
self.send_call_command(CallCommand::LowerHand { mri });
448
520
}
449
521
}
450
522
451
523
pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {
452
let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
524
let allowed = self
525
.call
526
.as_ref()
527
.is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());
453
528
if allowed {
454
529
self.send_call_command(CallCommand::LowerAllHands);
455
530
}
456
531
}
457
532
458
533
pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {
459
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {
534
let Some(call) = self
535
.call
536
.as_mut()
537
.filter(|call| call.model.is_active() && call.model.has_reaction_controls())
538
else {
460
539
return;
461
540
};
462
541
if let Some(own_mri) = call.model.own_mri.clone() {
@@ -469,52 +548,86 @@ impl AppState {
469
548
470
549
pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {
471
550
self.call_share_sound = on;
472
let _ = self.store.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
551
let _ = self
552
.store
553
.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });
473
554
self.send_call_command(CallCommand::SetShareSound(on));
474
555
cx.notify();
475
556
}
476
557
477
558
pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
478
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {
559
if self
560
.call
561
.as_ref()
562
.is_some_and(|call| call.model.can_admit())
563
{
479
564
self.send_call_command(CallCommand::Admit { mri });
480
565
}
481
566
}
482
567
483
568
pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {
484
if self.call.as_ref().is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty()) {
569
if self
570
.call
571
.as_ref()
572
.is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty())
573
{
485
574
self.send_call_command(CallCommand::AdmitAll);
486
575
}
487
576
}
488
577
489
578
pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {
490
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {
579
if self
580
.call
581
.as_ref()
582
.is_some_and(|call| call.model.can_admit())
583
{
491
584
self.send_call_command(CallCommand::Deny { mri });
492
585
}
493
586
}
494
587
495
588
pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
496
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
589
if self
590
.call
591
.as_ref()
592
.is_some_and(|call| call.model.can_manage())
593
{
497
594
self.send_call_command(CallCommand::MuteParticipant { mri });
498
595
}
499
596
}
500
597
501
598
pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {
502
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
599
if self
600
.call
601
.as_ref()
602
.is_some_and(|call| call.model.can_manage())
603
{
503
604
self.send_call_command(CallCommand::MuteAll);
504
605
}
505
606
}
506
607
507
608
pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {
508
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {
609
if self
610
.call
611
.as_ref()
612
.is_some_and(|call| call.model.can_manage())
613
{
509
614
self.send_call_command(CallCommand::RemoveParticipant { mri });
510
615
}
511
616
}
512
617
513
618
pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {
514
let Some(call) = self.call.as_ref().filter(|call| call.model.can_manage() && call.model.is_active()) else {
619
let Some(call) = self
620
.call
621
.as_ref()
622
.filter(|call| call.model.can_manage() && call.model.is_active())
623
else {
515
624
return;
516
625
};
517
let command = if call.model.is_spotlighted(&mri) { CallCommand::StopSpotlight { mri } } else { CallCommand::Spotlight { mri } };
626
let command = if call.model.is_spotlighted(&mri) {
627
CallCommand::StopSpotlight { mri }
628
} else {
629
CallCommand::Spotlight { mri }
630
};
518
631
self.send_call_command(command);
519
632
}
520
633
@@ -526,7 +639,11 @@ impl AppState {
526
639
}
527
640
528
641
pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {
529
let Some(call) = self.call.as_ref().filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting) else {
642
let Some(call) = self
643
.call
644
.as_ref()
645
.filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting)
646
else {
530
647
return;
531
648
};
532
649
let on = !call.model.captions_on();
@@ -549,19 +666,34 @@ impl AppState {
549
666
self.send_call_command(CallCommand::SetBackground(choice));
550
667
return;
551
668
}
552
let BackgroundPick::Default(id) = pick else { return };
553
let Some(image) = self.call_backgrounds.find(&id).cloned() else { return };
554
let Some(launcher) = self.call_launcher.clone() else { return };
669
let BackgroundPick::Default(id) = pick else {
670
return;
671
};
672
let Some(image) = self.call_backgrounds.find(&id).cloned() else {
673
return;
674
};
675
let Some(launcher) = self.call_launcher.clone() else {
676
return;
677
};
555
678
let cache = self.call_backgrounds.cache.clone();
556
let receiver = crate::runtime::spawn(async move { launcher.download_background(&cache, &image).await });
679
let receiver =
680
crate::runtime::spawn(
681
async move { launcher.download_background(&cache, &image).await },
682
);
557
683
cx.spawn(async move |this, cx| {
558
684
let path = receiver.await.ok().flatten();
559
685
this.update(cx, |state, cx| match path {
560
686
Some(path) if state.call_background == BackgroundPick::Default(id) => {
561
state.send_call_command(CallCommand::SetBackground(calling::BackgroundChoice::Image(path)));
687
state.send_call_command(CallCommand::SetBackground(
688
calling::BackgroundChoice::Image(path),
689
));
562
690
}
563
691
Some(_) => {}
564
None => state.raise_notice("That background could not be downloaded".to_owned(), None, cx),
692
None => state.raise_notice(
693
"That background could not be downloaded".to_owned(),
694
None,
695
cx,
696
),
565
697
})
566
698
.ok();
567
699
})
@@ -572,11 +704,16 @@ impl AppState {
572
704
if self.mode.demo || !self.call_backgrounds.needs_refresh() {
573
705
return;
574
706
}
575
let Some(launcher) = self.call_launcher.clone() else { return };
707
let Some(launcher) = self.call_launcher.clone() else {
708
return;
709
};
576
710
self.call_backgrounds.refreshing = true;
577
711
let cache = self.call_backgrounds.cache.clone();
578
712
let wanted = SHOWN_IMAGES;
579
let receiver = crate::runtime::spawn(async move { launcher.refresh_backgrounds(&cache, wanted).await });
713
let receiver =
714
crate::runtime::spawn(
715
async move { launcher.refresh_backgrounds(&cache, wanted).await },
716
);
580
717
cx.spawn(async move |this, cx| {
581
718
let catalog = receiver.await.ok().flatten();
582
719
this.update(cx, |state, cx| {
@@ -592,9 +729,20 @@ impl AppState {
592
729
}
593
730
594
731
pub fn add_call_background(&mut self, cx: &mut Context<Self>) {
595
let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: None });
732
let receiver = cx.prompt_for_paths(PathPromptOptions {
733
files: true,
734
directories: false,
735
multiple: false,
736
prompt: None,
737
});
596
738
cx.spawn(async move |this, cx| {
597
let Some(path) = receiver.await.ok().and_then(Result::ok).flatten().and_then(|paths| paths.into_iter().next()) else {
739
let Some(path) = receiver
740
.await
741
.ok()
742
.and_then(Result::ok)
743
.flatten()
744
.and_then(|paths| paths.into_iter().next())
745
else {
598
746
return;
599
747
};
600
748
this.update(cx, |state, cx| {
@@ -612,7 +760,11 @@ impl AppState {
612
760
}
613
761
614
762
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {
615
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {
763
let Some(call) = self
764
.call
765
.as_mut()
766
.filter(|call| call.model.screen_sharer.is_some())
767
else {
616
768
return;
617
769
};
618
770
call.stage_fullscreen = !call.stage_fullscreen;
@@ -630,7 +782,9 @@ impl AppState {
630
782
}
631
783
632
784
pub fn stage_fullscreen(&self) -> bool {
633
self.call.as_ref().is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())
785
self.call
786
.as_ref()
787
.is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())
634
788
}
635
789
636
790
pub fn viewing_call(&self) -> bool {
@@ -649,7 +803,11 @@ impl AppState {
649
803
}
650
804
651
805
fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {
652
let caller_user_id = ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);
806
let caller_user_id = ring
807
.caller
808
.mri
809
.strip_prefix(ORGID_PREFIX)
810
.map(str::to_owned);
653
811
self.rings.push(ring, demo, Instant::now());
654
812
if let Some(user_id) = caller_user_id {
655
813
self.request_avatars(vec![user_id], cx);
@@ -671,10 +829,22 @@ impl AppState {
671
829
return;
672
830
}
673
831
let (script, model, conversation_id) = if scene.is_one_to_one() {
674
(DemoCall::People(vec![demo_caller()]), CallModel::people("Mara Lindqvist", &[demo_caller()]), "demo-chat-mara")
832
(
833
DemoCall::People(vec![demo_caller()]),
834
CallModel::people("Mara Lindqvist", &[demo_caller()]),
835
"demo-chat-mara",
836
)
675
837
} else {
676
let script = DemoCall::Meeting { guests: demo_guests(DEMO_SMALL_MEETING), lobby: false, organizer: true };
677
(script, CallModel::meeting("Standup", true), "demo-chat-meeting-standup")
838
let script = DemoCall::Meeting {
839
guests: demo_guests(DEMO_SMALL_MEETING),
840
lobby: false,
841
organizer: true,
842
};
843
(
844
script,
845
CallModel::meeting("Standup", true),
846
"demo-chat-meeting-standup",
847
)
678
848
};
679
849
let handle = start_demo_scene_call(script, scene);
680
850
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
@@ -754,7 +924,8 @@ impl AppState {
754
924
self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);
755
925
return;
756
926
};
757
let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
927
let receiver =
928
crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });
758
929
cx.spawn(async move |this, cx| {
759
930
let handle = receiver.await.ok().flatten();
760
931
this.update(cx, |state, cx| match handle {
@@ -778,7 +949,11 @@ impl AppState {
778
949
}
779
950
780
951
pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {
781
if let Some(thread_id) = missed.thread_id.as_ref().filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id)) {
952
if let Some(thread_id) = missed
953
.thread_id
954
.as_ref()
955
.filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id))
956
{
782
957
return Some(thread_id.clone());
783
958
}
784
959
let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;
@@ -787,7 +962,10 @@ impl AppState {
787
962
.iter()
788
963
.find(|chat| {
789
964
crate::data::is_one_on_one(chat)
790
&& chat.members.iter().any(|member| member.user_id.as_deref() == Some(user_id))
965
&& chat
966
.members
967
.iter()
968
.any(|member| member.user_id.as_deref() == Some(user_id))
791
969
})
792
970
.map(|chat| chat.id.clone())
793
971
}
@@ -818,12 +996,15 @@ impl AppState {
818
996
}
819
997
820
998
pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {
821
let meeting_chat = self
822
.sidebar
823
.chats
824
.iter()
825
.any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND));
826
meeting_chat || matches!(selection_for(&self.sidebar, conversation_id), Some(Selection::Channel(_)))
999
let meeting_chat =
1000
self.sidebar.chats.iter().any(|chat| {
1001
chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND)
1002
});
1003
meeting_chat
1004
|| matches!(
1005
selection_for(&self.sidebar, conversation_id),
1006
Some(Selection::Channel(_))
1007
)
827
1008
}
828
1009
829
1010
pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {
@@ -837,19 +1018,32 @@ impl AppState {
837
1018
return;
838
1019
}
839
1020
let thread_id = conversation_id.to_owned();
840
let receiver = crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
1021
let receiver =
1022
crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });
841
1023
let conversation_id = conversation_id.to_owned();
842
1024
cx.spawn(async move |this, cx| {
843
1025
let meeting = receiver.await.ok().flatten();
844
this.update(cx, |state, cx| state.apply_live_meeting(conversation_id, meeting, cx)).ok();
1026
this.update(cx, |state, cx| {
1027
state.apply_live_meeting(conversation_id, meeting, cx)
1028
})
1029
.ok();
845
1030
})
846
1031
.detach();
847
1032
}
848
1033
849
pub fn apply_live_meeting(&mut self, conversation_id: String, meeting: Option<LiveMeeting>, cx: &mut Context<Self>) {
1034
pub fn apply_live_meeting(
1035
&mut self,
1036
conversation_id: String,
1037
meeting: Option<LiveMeeting>,
1038
cx: &mut Context<Self>,
1039
) {
850
1040
self.live_refreshing.remove(&conversation_id);
851
1041
let changed = match meeting {
852
Some(meeting) => self.live_meetings.insert(conversation_id.clone(), meeting.clone()) != Some(meeting),
1042
Some(meeting) => {
1043
self.live_meetings
1044
.insert(conversation_id.clone(), meeting.clone())
1045
!= Some(meeting)
1046
}
853
1047
None => self.live_meetings.remove(&conversation_id).is_some(),
854
1048
};
855
1049
if changed {
@@ -870,7 +1064,10 @@ mod tests {
870
1064
871
1065
use std::path::PathBuf;
872
1066
873
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};
1067
use calling::{
1068
BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind,
1069
EndReason, EngineEvent, HoldState, Reaction, call_channel,
1070
};
874
1071
use gpui_kit::{AppContext as _, Entity, TestAppContext};
875
1072
use store::{ChatRecord, MemberRecord, Store};
876
1073
@@ -890,13 +1087,23 @@ mod tests {
890
1087
let (handle, _control) = call_channel();
891
1088
cx.update(|cx| {
892
1089
app.update(cx, |state, _| {
893
state.call = Some(ActiveCall::new(7, CallModel::test(), handle.commands, None, handle.video));
1090
state.call = Some(ActiveCall::new(
1091
7,
1092
CallModel::test(),
1093
handle.commands,
1094
None,
1095
handle.video,
1096
));
894
1097
})
895
1098
});
896
1099
app
897
1100
}
898
1101
899
fn app_with_commands(cx: &mut TestAppContext, model: CallModel, conversation_id: Option<&str>) -> (Entity<AppState>, CallControl) {
1102
fn app_with_commands(
1103
cx: &mut TestAppContext,
1104
model: CallModel,
1105
conversation_id: Option<&str>,
1106
) -> (Entity<AppState>, CallControl) {
900
1107
cx.update(gpui_kit::init);
901
1108
let store = Arc::new(Store::open_in_memory().unwrap());
902
1109
let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));
@@ -904,7 +1111,13 @@ mod tests {
904
1111
let conversation_id = conversation_id.map(str::to_owned);
905
1112
cx.update(|cx| {
906
1113
app.update(cx, |state, _| {
907
state.call = Some(ActiveCall::new(7, model, handle.commands, conversation_id, handle.video));
1114
state.call = Some(ActiveCall::new(
1115
7,
1116
model,
1117
handle.commands,
1118
conversation_id,
1119
handle.video,
1120
));
908
1121
})
909
1122
});
910
1123
(app, control)
@@ -912,8 +1125,12 @@ mod tests {
912
1125
913
1126
fn live_meeting(can_end: bool) -> CallModel {
914
1127
let mut model = CallModel::meeting("Standup", can_end);
915
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
916
model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
1128
model.apply(CallUpdate::State(CallState::Connected {
1129
since: Instant::now(),
1130
}));
1131
model.apply(CallUpdate::OwnIdentity {
1132
mri: "8:orgid:me".into(),
1133
});
917
1134
model
918
1135
}
919
1136
@@ -931,13 +1148,31 @@ mod tests {
931
1148
.detach();
932
1149
app.update(cx, |state, cx| {
933
1150
state.apply_call_update(7, CallUpdate::VideoReady, cx);
934
state.apply_call_update(7, CallUpdate::Levels { local: 0.5, remote: 0.5 }, cx);
935
state.apply_call_update(7, CallUpdate::Stats { inbound_packets: 1, outbound_packets: 1 }, cx);
1151
state.apply_call_update(
1152
7,
1153
CallUpdate::Levels {
1154
local: 0.5,
1155
remote: 0.5,
1156
},
1157
cx,
1158
);
1159
state.apply_call_update(
1160
7,
1161
CallUpdate::Stats {
1162
inbound_packets: 1,
1163
outbound_packets: 1,
1164
},
1165
cx,
1166
);
936
1167
});
937
1168
});
938
1169
assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);
939
1170
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));
940
cx.update(|cx| app.update(cx, |state, cx| state.apply_call_update(7, CallUpdate::Muted(true), cx)));
1171
cx.update(|cx| {
1172
app.update(cx, |state, cx| {
1173
state.apply_call_update(7, CallUpdate::Muted(true), cx)
1174
})
1175
});
941
1176
assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);
942
1177
}
943
1178
@@ -947,7 +1182,10 @@ mod tests {
947
1182
let store = cx.update(|cx| app.read(cx).store.clone());
948
1183
assert!(!cx.update(|cx| app.read(cx).call_share_sound));
949
1184
cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));
950
assert_eq!(control.try_recv_command(), Some(CallCommand::SetShareSound(true)));
1185
assert_eq!(
1186
control.try_recv_command(),
1187
Some(CallCommand::SetShareSound(true))
1188
);
951
1189
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
952
1190
assert!(cx.update(|cx| reopened.read(cx).call_share_sound));
953
1191
cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));
@@ -960,16 +1198,29 @@ mod tests {
960
1198
let (app, _control) = app_with_commands(cx, live_meeting(false), None);
961
1199
let store = cx.update(|cx| app.read(cx).store.clone());
962
1200
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
963
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)));
1201
cx.update(|cx| {
1202
app.update(cx, |state, cx| {
1203
state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)
1204
})
1205
});
964
1206
assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));
965
1207
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
966
assert_eq!(cx.update(|cx| reopened.read(cx).call_camera.clone()), DeviceChoice::Device("cam-2".into()));
967
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::SystemDefault, cx)));
1208
assert_eq!(
1209
cx.update(|cx| reopened.read(cx).call_camera.clone()),
1210
DeviceChoice::Device("cam-2".into())
1211
);
1212
cx.update(|cx| {
1213
app.update(cx, |state, cx| {
1214
state.select_call_camera(DeviceChoice::SystemDefault, cx)
1215
})
1216
});
968
1217
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);
969
1218
}
970
1219
971
1220
#[gpui_kit::test]
972
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {
1221
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(
1222
cx: &mut TestAppContext,
1223
) {
973
1224
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
974
1225
cx.update(|cx| {
975
1226
app.update(cx, |state, cx| {
@@ -980,28 +1231,46 @@ mod tests {
980
1231
})
981
1232
});
982
1233
assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));
983
assert_eq!(control.try_recv_command(), Some(CallCommand::SendReaction(Reaction::Heart)));
1234
assert_eq!(
1235
control.try_recv_command(),
1236
Some(CallCommand::SendReaction(Reaction::Heart))
1237
);
984
1238
assert_eq!(control.try_recv_command(), None);
985
1239
let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);
986
1240
cx.update(|cx| {
987
1241
organizer.update(cx, |state, cx| {
988
state.apply_call_update(7, CallUpdate::Roster(vec![calling::RosterEntry {
989
mri: "8:orgid:a".into(),
990
display_name: "Ana".into(),
991
muted: false,
992
in_lobby: false,
993
has_video: false,
994
sharing: false,
995
hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),
996
spotlight: None,
997
organizer: false,
998
}]), cx);
1242
state.apply_call_update(
1243
7,
1244
CallUpdate::Roster(vec![calling::RosterEntry {
1245
mri: "8:orgid:a".into(),
1246
display_name: "Ana".into(),
1247
muted: false,
1248
in_lobby: false,
1249
has_video: false,
1250
sharing: false,
1251
hand: Some(calling::RaisedHand {
1252
state_id: "s".into(),
1253
rank: 1,
1254
}),
1255
spotlight: None,
1256
organizer: false,
1257
}]),
1258
cx,
1259
);
999
1260
state.lower_call_hand("8:orgid:a".into(), cx);
1000
1261
state.lower_all_call_hands(cx);
1001
1262
})
1002
1263
});
1003
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerHand { mri: "8:orgid:a".into() }));
1004
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));
1264
assert_eq!(
1265
organizer_control.try_recv_command(),
1266
Some(CallCommand::LowerHand {
1267
mri: "8:orgid:a".into()
1268
})
1269
);
1270
assert_eq!(
1271
organizer_control.try_recv_command(),
1272
Some(CallCommand::LowerAllHands)
1273
);
1005
1274
}
1006
1275
1007
1276
fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {
@@ -1013,7 +1282,10 @@ mod tests {
1013
1282
has_video: false,
1014
1283
sharing: false,
1015
1284
hand: None,
1016
spotlight: spotlit.then(|| calling::Spotlight { state_id: "sp".into(), rank: 1 }),
1285
spotlight: spotlit.then(|| calling::Spotlight {
1286
state_id: "sp".into(),
1287
rank: 1,
1288
}),
1017
1289
organizer: false,
1018
1290
}
1019
1291
}
@@ -1036,7 +1308,14 @@ mod tests {
1036
1308
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);
1037
1309
cx.update(|cx| {
1038
1310
organizer.update(cx, |state, cx| {
1039
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, false), guest("8:orgid:g", "Gast", true, false)]), cx);
1311
state.apply_call_update(
1312
7,
1313
CallUpdate::Roster(vec![
1314
guest("8:orgid:a", "Ana", false, false),
1315
guest("8:orgid:g", "Gast", true, false),
1316
]),
1317
cx,
1318
);
1040
1319
state.admit_call_guest("8:orgid:g".into(), cx);
1041
1320
state.admit_all_call_guests(cx);
1042
1321
state.deny_call_guest("8:orgid:g".into(), cx);
@@ -1046,29 +1325,68 @@ mod tests {
1046
1325
state.toggle_call_spotlight("8:orgid:a".into(), cx);
1047
1326
})
1048
1327
});
1049
assert_eq!(control.try_recv_command(), Some(CallCommand::Admit { mri: "8:orgid:g".into() }));
1328
assert_eq!(
1329
control.try_recv_command(),
1330
Some(CallCommand::Admit {
1331
mri: "8:orgid:g".into()
1332
})
1333
);
1050
1334
assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));
1051
assert_eq!(control.try_recv_command(), Some(CallCommand::Deny { mri: "8:orgid:g".into() }));
1052
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteParticipant { mri: "8:orgid:a".into() }));
1335
assert_eq!(
1336
control.try_recv_command(),
1337
Some(CallCommand::Deny {
1338
mri: "8:orgid:g".into()
1339
})
1340
);
1341
assert_eq!(
1342
control.try_recv_command(),
1343
Some(CallCommand::MuteParticipant {
1344
mri: "8:orgid:a".into()
1345
})
1346
);
1053
1347
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));
1054
assert_eq!(control.try_recv_command(), Some(CallCommand::RemoveParticipant { mri: "8:orgid:a".into() }));
1055
assert_eq!(control.try_recv_command(), Some(CallCommand::Spotlight { mri: "8:orgid:a".into() }));
1348
assert_eq!(
1349
control.try_recv_command(),
1350
Some(CallCommand::RemoveParticipant {
1351
mri: "8:orgid:a".into()
1352
})
1353
);
1354
assert_eq!(
1355
control.try_recv_command(),
1356
Some(CallCommand::Spotlight {
1357
mri: "8:orgid:a".into()
1358
})
1359
);
1056
1360
}
1057
1361
1058
1362
#[gpui_kit::test]
1059
fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(cx: &mut TestAppContext) {
1363
fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(
1364
cx: &mut TestAppContext,
1365
) {
1060
1366
let (app, mut control) = app_with_commands(cx, live_meeting(true), None);
1061
1367
cx.update(|cx| {
1062
1368
app.update(cx, |state, cx| {
1063
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]), cx);
1369
state.apply_call_update(
1370
7,
1371
CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]),
1372
cx,
1373
);
1064
1374
state.toggle_call_spotlight("8:orgid:a".into(), cx);
1065
1375
state.toggle_call_pin("8:orgid:a", cx);
1066
assert_eq!(state.call.as_ref().unwrap().model.pinned.as_deref(), Some("8:orgid:a"));
1376
assert_eq!(
1377
state.call.as_ref().unwrap().model.pinned.as_deref(),
1378
Some("8:orgid:a")
1379
);
1067
1380
state.toggle_call_pin("8:orgid:a", cx);
1068
1381
assert_eq!(state.call.as_ref().unwrap().model.pinned, None);
1069
1382
})
1070
1383
});
1071
assert_eq!(control.try_recv_command(), Some(CallCommand::StopSpotlight { mri: "8:orgid:a".into() }));
1384
assert_eq!(
1385
control.try_recv_command(),
1386
Some(CallCommand::StopSpotlight {
1387
mri: "8:orgid:a".into()
1388
})
1389
);
1072
1390
assert_eq!(control.try_recv_command(), None);
1073
1391
}
1074
1392
@@ -1082,8 +1400,14 @@ mod tests {
1082
1400
state.toggle_call_captions(cx);
1083
1401
})
1084
1402
});
1085
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));
1086
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(false)));
1403
assert_eq!(
1404
control.try_recv_command(),
1405
Some(CallCommand::SetCaptions(true))
1406
);
1407
assert_eq!(
1408
control.try_recv_command(),
1409
Some(CallCommand::SetCaptions(false))
1410
);
1087
1411
let app = app_with_call(cx);
1088
1412
cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));
1089
1413
}
@@ -1092,30 +1416,71 @@ mod tests {
1092
1416
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {
1093
1417
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1094
1418
let store = cx.update(|cx| app.read(cx).store.clone());
1095
assert_eq!(cx.update(|cx| app.read(cx).call_background.clone()), BackgroundPick::None);
1096
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx)));
1097
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Blur)));
1098
assert_eq!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()), BackgroundPick::Blur);
1419
assert_eq!(
1420
cx.update(|cx| app.read(cx).call_background.clone()),
1421
BackgroundPick::None
1422
);
1423
cx.update(|cx| {
1424
app.update(cx, |state, cx| {
1425
state.set_call_background(BackgroundPick::Blur, cx)
1426
})
1427
});
1428
assert_eq!(
1429
control.try_recv_command(),
1430
Some(CallCommand::SetBackground(BackgroundChoice::Blur))
1431
);
1432
assert_eq!(
1433
cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()),
1434
BackgroundPick::Blur
1435
);
1099
1436
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1100
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Blur);
1437
assert_eq!(
1438
cx.update(|cx| reopened.read(cx).call_background.clone()),
1439
BackgroundPick::Blur
1440
);
1101
1441
let picture = PathBuf::from("/pictures/wall.jpg");
1102
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)));
1103
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Image(picture.clone()))));
1442
cx.update(|cx| {
1443
app.update(cx, |state, cx| {
1444
state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)
1445
})
1446
});
1447
assert_eq!(
1448
control.try_recv_command(),
1449
Some(CallCommand::SetBackground(BackgroundChoice::Image(
1450
picture.clone()
1451
)))
1452
);
1104
1453
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));
1105
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Custom(picture));
1106
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx)));
1107
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::None)));
1454
assert_eq!(
1455
cx.update(|cx| reopened.read(cx).call_background.clone()),
1456
BackgroundPick::Custom(picture)
1457
);
1458
cx.update(|cx| {
1459
app.update(cx, |state, cx| {
1460
state.set_call_background(BackgroundPick::None, cx)
1461
})
1462
});
1463
assert_eq!(
1464
control.try_recv_command(),
1465
Some(CallCommand::SetBackground(BackgroundChoice::None))
1466
);
1108
1467
}
1109
1468
1110
1469
#[gpui_kit::test]
1111
1470
fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {
1112
1471
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1113
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Default("office_01".into()), cx)));
1472
cx.update(|cx| {
1473
app.update(cx, |state, cx| {
1474
state.set_call_background(BackgroundPick::Default("office_01".into()), cx)
1475
})
1476
});
1114
1477
assert_eq!(control.try_recv_command(), None);
1115
1478
}
1116
1479
1117
1480
#[gpui_kit::test]
1118
fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(cx: &mut TestAppContext) {
1481
fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(
1482
cx: &mut TestAppContext,
1483
) {
1119
1484
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);
1120
1485
cx.update(|cx| {
1121
1486
attendee.update(cx, |state, cx| {
@@ -1135,15 +1500,32 @@ mod tests {
1135
1500
state.accept_recording_notice(cx);
1136
1501
})
1137
1502
});
1138
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: true, title: "Standup".into() }));
1139
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: false, title: "Standup".into() }));
1140
assert_eq!(control.try_recv_command(), Some(CallCommand::ConsentToRecording));
1503
assert_eq!(
1504
control.try_recv_command(),
1505
Some(CallCommand::SetRecording {
1506
on: true,
1507
title: "Standup".into()
1508
})
1509
);
1510
assert_eq!(
1511
control.try_recv_command(),
1512
Some(CallCommand::SetRecording {
1513
on: false,
1514
title: "Standup".into()
1515
})
1516
);
1517
assert_eq!(
1518
control.try_recv_command(),
1519
Some(CallCommand::ConsentToRecording)
1520
);
1141
1521
assert_eq!(control.try_recv_command(), None);
1142
1522
}
1143
1523
1144
1524
fn live_one_to_one() -> CallModel {
1145
1525
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1146
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1526
model.apply(CallUpdate::State(CallState::Connected {
1527
since: Instant::now(),
1528
}));
1147
1529
model
1148
1530
}
1149
1531
@@ -1168,16 +1550,33 @@ mod tests {
1168
1550
}
1169
1551
1170
1552
fn candidate(name: &str) -> TransferCandidate {
1171
TransferCandidate { mri: format!("8:orgid:{name}"), name: name.into(), user_id: Some(name.into()), chat_id: format!("19:{name}") }
1553
TransferCandidate {
1554
mri: format!("8:orgid:{name}"),
1555
name: name.into(),
1556
user_id: Some(name.into()),
1557
chat_id: format!("19:{name}"),
1558
}
1172
1559
}
1173
1560
1174
1561
#[gpui_kit::test]
1175
fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(cx: &mut TestAppContext) {
1562
fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(
1563
cx: &mut TestAppContext,
1564
) {
1176
1565
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);
1177
cx.update(|cx| app.update(cx, |state, cx| state.transfer_call_blind(candidate("ana"), cx)));
1566
cx.update(|cx| {
1567
app.update(cx, |state, cx| {
1568
state.transfer_call_blind(candidate("ana"), cx)
1569
})
1570
});
1178
1571
assert_eq!(
1179
1572
control.try_recv_command(),
1180
Some(CallCommand::Transfer { target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "ana".into() }, replaces: None })
1573
Some(CallCommand::Transfer {
1574
target: calling::Callee {
1575
mri: "8:orgid:ana".into(),
1576
display_name: "ana".into()
1577
},
1578
replaces: None
1579
})
1181
1580
);
1182
1581
let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);
1183
1582
let (consult_handle, _consult_updates) = call_channel();
@@ -1192,14 +1591,20 @@ mod tests {
1192
1591
transferring: false,
1193
1592
});
1194
1593
state.transfer_consulted(cx);
1195
state.call.as_mut().unwrap().consult.as_mut().unwrap().state = CallState::Connected { since: Instant::now() };
1594
state.call.as_mut().unwrap().consult.as_mut().unwrap().state =
1595
CallState::Connected {
1596
since: Instant::now(),
1597
};
1196
1598
state.transfer_consulted(cx);
1197
1599
})
1198
1600
});
1199
1601
assert_eq!(
1200
1602
consult_control.try_recv_command(),
1201
1603
Some(CallCommand::Transfer {
1202
target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() },
1604
target: calling::Callee {
1605
mri: "8:orgid:ana".into(),
1606
display_name: "Ana".into()
1607
},
1203
1608
replaces: Some("https://cc.skype.com/replacement".into()),
1204
1609
})
1205
1610
);
@@ -1207,16 +1612,31 @@ mod tests {
1207
1612
}
1208
1613
1209
1614
#[gpui_kit::test]
1210
fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(cx: &mut TestAppContext) {
1615
fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(
1616
cx: &mut TestAppContext,
1617
) {
1211
1618
let app = app_with_chats(cx);
1212
1619
cx.update(|cx| {
1213
1620
app.update(cx, |state, cx| {
1214
let names: Vec<String> = state.transfer_candidates().into_iter().map(|candidate| candidate.name).collect();
1621
let names: Vec<String> = state
1622
.transfer_candidates()
1623
.into_iter()
1624
.map(|candidate| candidate.name)
1625
.collect();
1215
1626
assert_eq!(names, vec!["Bea".to_owned()]);
1216
1627
let (handle, _control) = call_channel();
1217
let mut on_the_call = CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
1218
on_the_call.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1219
state.call = Some(ActiveCall::new(9, on_the_call, handle.commands, None, handle.video));
1628
let mut on_the_call =
1629
CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);
1630
on_the_call.apply(CallUpdate::State(CallState::Connected {
1631
since: Instant::now(),
1632
}));
1633
state.call = Some(ActiveCall::new(
1634
9,
1635
on_the_call,
1636
handle.commands,
1637
None,
1638
handle.video,
1639
));
1220
1640
assert!(state.transfer_candidates().is_empty());
1221
1641
cx.notify();
1222
1642
})
@@ -1226,13 +1646,23 @@ mod tests {
1226
1646
fn room_move(returning: bool) -> calling::BreakoutMove {
1227
1647
calling::BreakoutMove {
1228
1648
room_name: "Room 1".into(),
1229
target: calling::MeetingTarget { thread_id: "19:meeting_room@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None },
1649
target: calling::MeetingTarget {
1650
thread_id: "19:meeting_room@thread.v2".into(),
1651
tenant_id: "t".into(),
1652
organizer_id: "o".into(),
1653
meeting_data: None,
1654
},
1230
1655
returning,
1231
1656
}
1232
1657
}
1233
1658
1234
1659
fn main_target() -> calling::MeetingTarget {
1235
calling::MeetingTarget { thread_id: "19:meeting_main@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None }
1660
calling::MeetingTarget {
1661
thread_id: "19:meeting_main@thread.v2".into(),
1662
tenant_id: "t".into(),
1663
organizer_id: "o".into(),
1664
meeting_data: None,
1665
}
1236
1666
}
1237
1667
1238
1668
#[gpui_kit::test]
@@ -1242,13 +1672,22 @@ mod tests {
1242
1672
app.update(cx, |state, cx| {
1243
1673
state.call.as_mut().unwrap().meeting_target = Some(main_target());
1244
1674
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1245
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");
1675
let pending = state
1676
.call
1677
.as_ref()
1678
.unwrap()
1679
.pending_move
1680
.clone()
1681
.expect("a move is pending");
1246
1682
assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");
1247
1683
assert_eq!(pending.title, "Room 1");
1248
1684
let room = pending.breakout.expect("a room");
1249
1685
assert_eq!(room.main, Some(main_target()));
1250
1686
assert_eq!(room.main_title, "Standup");
1251
assert_eq!(state.notice.as_ref().map(|notice| notice.text.as_str()), Some("Moving you to Room 1"));
1687
assert_eq!(
1688
state.notice.as_ref().map(|notice| notice.text.as_str()),
1689
Some("Moving you to Room 1")
1690
);
1252
1691
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);
1253
1692
})
1254
1693
});
@@ -1257,14 +1696,26 @@ mod tests {
1257
1696
}
1258
1697
1259
1698
#[gpui_kit::test]
1260
fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(cx: &mut TestAppContext) {
1699
fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(
1700
cx: &mut TestAppContext,
1701
) {
1261
1702
let mut room = live_meeting(false);
1262
room.breakout = Some(BreakoutState { room_name: "Room 1".into(), main: Some(main_target()), main_title: "Standup".into() });
1703
room.breakout = Some(BreakoutState {
1704
room_name: "Room 1".into(),
1705
main: Some(main_target()),
1706
main_title: "Standup".into(),
1707
});
1263
1708
let (app, mut control) = app_with_commands(cx, room.clone(), None);
1264
1709
cx.update(|cx| {
1265
1710
app.update(cx, |state, cx| {
1266
1711
state.return_to_main_meeting(cx);
1267
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");
1712
let pending = state
1713
.call
1714
.as_ref()
1715
.unwrap()
1716
.pending_move
1717
.clone()
1718
.expect("a move is pending");
1268
1719
assert_eq!(pending.target, main_target());
1269
1720
assert_eq!(pending.title, "Standup");
1270
1721
assert!(pending.breakout.is_none());
@@ -1275,18 +1726,31 @@ mod tests {
1275
1726
cx.update(|cx| {
1276
1727
closed.update(cx, |state, _| {
1277
1728
let call = state.call.as_ref().unwrap();
1278
let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed)).expect("goes back");
1729
let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed))
1730
.expect("goes back");
1279
1731
assert_eq!(moved.target, main_target());
1280
1732
assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());
1281
1733
assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());
1282
1734
})
1283
1735
});
1284
1736
let (plain, _control) = app_with_commands(cx, live_meeting(false), None);
1285
cx.update(|cx| plain.update(cx, |state, _| assert!(room_closed_move(state.call.as_ref().unwrap(), &EndReason::Remote(EndKind::RoomClosed)).is_none())));
1737
cx.update(|cx| {
1738
plain.update(cx, |state, _| {
1739
assert!(
1740
room_closed_move(
1741
state.call.as_ref().unwrap(),
1742
&EndReason::Remote(EndKind::RoomClosed)
1743
)
1744
.is_none()
1745
)
1746
})
1747
});
1286
1748
}
1287
1749
1288
1750
#[gpui_kit::test]
1289
fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(cx: &mut TestAppContext) {
1751
fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(
1752
cx: &mut TestAppContext,
1753
) {
1290
1754
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);
1291
1755
cx.update(|cx| {
1292
1756
app.update(cx, |state, cx| {
@@ -1305,22 +1769,39 @@ mod tests {
1305
1769
state.open_call_whiteboard(cx);
1306
1770
})
1307
1771
});
1308
assert_eq!(control.try_recv_command(), Some(CallCommand::OpenWhiteboard { title: "Standup".into() }));
1772
assert_eq!(
1773
control.try_recv_command(),
1774
Some(CallCommand::OpenWhiteboard {
1775
title: "Standup".into()
1776
})
1777
);
1309
1778
assert_eq!(control.try_recv_command(), None);
1310
1779
}
1311
1780
1312
1781
#[gpui_kit::test]
1313
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {
1782
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(
1783
cx: &mut TestAppContext,
1784
) {
1314
1785
let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));
1315
1786
cx.update(|cx| {
1316
1787
app.update(cx, |state, cx| {
1317
state.directory.unread_counts.insert("19:meeting_x@thread.v2".into(), 3);
1788
state
1789
.directory
1790
.unread_counts
1791
.insert("19:meeting_x@thread.v2".into(), 3);
1318
1792
assert_eq!(state.call_chat_thread(), None);
1319
1793
assert_eq!(state.call_chat_unread(), 0);
1320
state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);
1794
state.apply_call_update(
1795
7,
1796
CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),
1797
cx,
1798
);
1321
1799
assert_eq!(state.call_chat_unread(), 3);
1322
1800
state.toggle_call_chat(cx);
1323
assert_eq!(state.call_chat_thread().as_deref(), Some("19:meeting_x@thread.v2"));
1801
assert_eq!(
1802
state.call_chat_thread().as_deref(),
1803
Some("19:meeting_x@thread.v2")
1804
);
1324
1805
assert_eq!(state.call_chat_unread(), 0);
1325
1806
state.toggle_call_chat(cx);
1326
1807
assert_eq!(state.call_chat_thread(), None);
@@ -1353,15 +1834,24 @@ mod tests {
1353
1834
ChatRecord {
1354
1835
id: "19:meeting@thread.v2".into(),
1355
1836
kind: "meeting".into(),
1356
members: vec![MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() }],
1837
members: vec![MemberRecord {
1838
user_id: Some("bea-id".into()),
1839
display_name: "Bea".into(),
1840
}],
1357
1841
..Default::default()
1358
1842
},
1359
1843
ChatRecord {
1360
1844
id: "19:dm@unq.gbl.spaces".into(),
1361
1845
kind: "oneOnOne".into(),
1362
1846
members: vec![
1363
MemberRecord { user_id: Some("me-id".into()), display_name: "Me".into() },
1364
MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() },
1847
MemberRecord {
1848
user_id: Some("me-id".into()),
1849
display_name: "Me".into(),
1850
},
1851
MemberRecord {
1852
user_id: Some("bea-id".into()),
1853
display_name: "Bea".into(),
1854
},
1365
1855
],
1366
1856
..Default::default()
1367
1857
},
@@ -1508,7 +1998,10 @@ mod tests {
1508
1998
app.update(cx, |state, cx| {
1509
1999
state.start_chat_call("19:meeting@thread.v2", cx);
1510
2000
assert!(state.call.is_none());
1511
assert_eq!(state.notice.as_ref().unwrap().text, "This chat cannot be called");
2001
assert_eq!(
2002
state.notice.as_ref().unwrap().text,
2003
"This chat cannot be called"
2004
);
1512
2005
state.start_chat_call("19:unknown", cx);
1513
2006
assert!(state.call.is_none());
1514
2007
})
@@ -1526,9 +2019,18 @@ mod tests {
1526
2019
thread_id: None,
1527
2020
at: chrono::Utc::now(),
1528
2021
};
1529
assert_eq!(state.conversation_of_missed_call(&missed).as_deref(), Some("19:dm@unq.gbl.spaces"));
1530
let direct = super::MissedCall { thread_id: Some("19:dm@unq.gbl.spaces".into()), ..missed.clone() };
1531
assert_eq!(state.conversation_of_missed_call(&direct).as_deref(), Some("19:dm@unq.gbl.spaces"));
2022
assert_eq!(
2023
state.conversation_of_missed_call(&missed).as_deref(),
2024
Some("19:dm@unq.gbl.spaces")
2025
);
2026
let direct = super::MissedCall {
2027
thread_id: Some("19:dm@unq.gbl.spaces".into()),
2028
..missed.clone()
2029
};
2030
assert_eq!(
2031
state.conversation_of_missed_call(&direct).as_deref(),
2032
Some("19:dm@unq.gbl.spaces")
2033
);
1532
2034
})
1533
2035
});
1534
2036
}
@@ -2,13 +2,18 @@ use std::time::{Duration, Instant};2
2
3
use calling::meeting::LiveMeeting;3
use calling::meeting::LiveMeeting;4
use calling::{4
use calling::{5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice, EndReason, EngineEvent, MuteCommand, Reaction, RingSignal,5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice,6
ShareSource, VideoKey,6
EndReason, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,7
};7
};8
use gpui_kit::*;8
use gpui_kit::*;9
9
10
use super::background::{BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds};10
use super::background::{11
use super::demo::{DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call, start_demo_scene_call};11
BACKGROUND_META_KEY, BackgroundPick, SHOWN_IMAGES, is_image_file, save_custom_backgrounds,12
};13
use super::demo::{14
DemoCall, DemoScene, demo_caller, demo_guests, demo_ring, demo_video_ring, start_demo_call,15
start_demo_scene_call,16
};12
use super::features::room_closed_move;17
use super::features::room_closed_move;13
use super::media::CallMedia;18
use super::media::CallMedia;14
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};19
use super::model::{ActiveCall, CallKind, CallModel, ended_notice};@@ -120,7 +125,11 @@ impl AppState {120
self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);125
self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);121
return;126
return;122
};127
};123
let guests = if conversation_id == DEMO_LOBBY_MEETING { DEMO_SMALL_MEETING } else { DEMO_CROWD };128
let guests = if conversation_id == DEMO_LOBBY_MEETING {129
DEMO_SMALL_MEETING130
} else {131
DEMO_CROWD132
};124
let demo = DemoCall::Meeting {133
let demo = DemoCall::Meeting {125
guests: demo_guests(guests),134
guests: demo_guests(guests),126
lobby: conversation_id == DEMO_LOBBY_MEETING,135
lobby: conversation_id == DEMO_LOBBY_MEETING,@@ -139,7 +148,12 @@ impl AppState {139
}148
}140
}149
}141
150
142
pub(super) fn place_call(&mut self, spec: CallSpec, demo: DemoCall, cx: &mut Context<Self>) -> Option<CallHandle> {151
pub(super) fn place_call(152
&mut self,153
spec: CallSpec,154
demo: DemoCall,155
cx: &mut Context<Self>,156
) -> Option<CallHandle> {143
if self.mode.demo {157
if self.mode.demo {144
return Some(start_demo_call(demo));158
return Some(start_demo_call(demo));145
}159
}@@ -165,8 +179,18 @@ impl AppState {165
) {179
) {166
self.call_count += 1;180
self.call_count += 1;167
let call_id = self.call_count;181
let call_id = self.call_count;168
let CallHandle { commands, updates, video } = handle;182
let CallHandle {169
self.call = Some(ActiveCall::new(call_id, model, commands, conversation_id, video));183
commands,184
updates,185
video,186
} = handle;187
self.call = Some(ActiveCall::new(188
call_id,189
model,190
commands,191
conversation_id,192
video,193
));170
if self.call_share_sound {194
if self.call_share_sound {171
self.send_call_command(CallCommand::SetShareSound(true));195
self.send_call_command(CallCommand::SetShareSound(true));172
}196
}@@ -195,7 +219,8 @@ impl AppState {195
) {219
) {196
cx.spawn(async move |this, cx| {220
cx.spawn(async move |this, cx| {197
while let Some(update) = updates.recv().await {221
while let Some(update) = updates.recv().await {198
let alive = this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));222
let alive =223
this.update(cx, |state, cx| state.apply_call_update(call_id, update, cx));199
if alive.is_err() {224
if alive.is_err() {200
return;225
return;201
}226
}@@ -227,14 +252,22 @@ impl AppState {227
}252
}228
253
229
fn end_orphaned_call(&mut self, call_id: u64, cx: &mut Context<Self>) {254
fn end_orphaned_call(&mut self, call_id: u64, cx: &mut Context<Self>) {230
let still_open = self.call.as_ref().is_some_and(|call| call.id == call_id && call.model.is_active());255
let still_open = self256
.call257
.as_ref()258
.is_some_and(|call| call.id == call_id && call.model.is_active());231
if still_open {259
if still_open {232
let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());260
let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());233
self.apply_call_update(call_id, CallUpdate::State(CallState::Ended { reason }), cx);261
self.apply_call_update(call_id, CallUpdate::State(CallState::Ended { reason }), cx);234
}262
}235
}263
}236
264
237
pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {265
pub(super) fn apply_call_update(266
&mut self,267
call_id: u64,268
update: CallUpdate,269
cx: &mut Context<Self>,270
) {238
let media = self.call_media.clone();271
let media = self.call_media.clone();239
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {272
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {240
return;273
return;@@ -291,7 +324,10 @@ impl AppState {291
};324
};292
let elapsed = call.model.elapsed(Instant::now());325
let elapsed = call.model.elapsed(Instant::now());293
let notice = ended_notice(&reason, elapsed, &call.model.peer_name);326
let notice = ended_notice(&reason, elapsed, &call.model.peer_name);294
let next_move = call.pending_move.take().or_else(|| room_closed_move(call, &reason));327
let next_move = call328
.pending_move329
.take()330
.or_else(|| room_closed_move(call, &reason));295
let consult = call.consult.take();331
let consult = call.consult.take();296
call.pictures.clear(cx);332
call.pictures.clear(cx);297
if let Some(thread) = call.chat_thread() {333
if let Some(thread) = call.chat_thread() {@@ -317,14 +353,21 @@ impl AppState {317
}353
}318
354
319
pub fn toggle_call_mute(&mut self, _cx: &mut Context<Self>) {355
pub fn toggle_call_mute(&mut self, _cx: &mut Context<Self>) {320
let can_toggle = self.call.as_ref().is_some_and(|call| call.model.can_unmute());356
let can_toggle = self357
.call358
.as_ref()359
.is_some_and(|call| call.model.can_unmute());321
if can_toggle {360
if can_toggle {322
self.send_call_command(CallCommand::Mute(MuteCommand::Toggle));361
self.send_call_command(CallCommand::Mute(MuteCommand::Toggle));323
}362
}324
}363
}325
364
326
pub fn toggle_call_camera(&mut self, _cx: &mut Context<Self>) {365
pub fn toggle_call_camera(&mut self, _cx: &mut Context<Self>) {327
let Some(call) = self.call.as_ref().filter(|call| call.model.can_use_camera()) else {366
let Some(call) = self367
.call368
.as_ref()369
.filter(|call| call.model.can_use_camera())370
else {328
return;371
return;329
};372
};330
let on = !call.model.camera_on;373
let on = !call.model.camera_on;@@ -368,7 +411,10 @@ impl AppState {368
}411
}369
412
370
pub fn refresh_share_sources(&self) {413
pub fn refresh_share_sources(&self) {371
let idle = self.call.as_ref().is_some_and(|call| call.model.local_share.is_none());414
let idle = self415
.call416
.as_ref()417
.is_some_and(|call| call.model.local_share.is_none());372
if idle {418
if idle {373
self.send_call_command(CallCommand::RefreshShareSources);419
self.send_call_command(CallCommand::RefreshShareSources);374
}420
}@@ -379,7 +425,10 @@ impl AppState {379
}425
}380
426
381
pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {427
pub fn end_meeting_for_all(&mut self, _cx: &mut Context<Self>) {382
let allowed = self.call.as_ref().is_some_and(|call| call.model.can_end_meeting);428
let allowed = self429
.call430
.as_ref()431
.is_some_and(|call| call.model.can_end_meeting);383
if allowed {432
if allowed {384
self.send_call_command(CallCommand::EndMeeting);433
self.send_call_command(CallCommand::EndMeeting);385
}434
}@@ -406,7 +455,11 @@ impl AppState {406
}455
}407
456
408
pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {457
pub fn toggle_call_chat(&mut self, cx: &mut Context<Self>) {409
let Some(call) = self.call.as_mut().filter(|call| call.chat_thread().is_some()) else {458
let Some(call) = self459
.call460
.as_mut()461
.filter(|call| call.chat_thread().is_some())462
else {410
return;463
return;411
};464
};412
call.chat_open = !call.chat_open;465
call.chat_open = !call.chat_open;@@ -420,15 +473,31 @@ impl AppState {420
}473
}421
474
422
pub fn call_chat_unread(&self) -> u32 {475
pub fn call_chat_unread(&self) -> u32 {423
let Some(thread) = self.call.as_ref().filter(|call| !call.chat_open).and_then(|call| call.chat_thread()) else {476
let Some(thread) = self477
.call478
.as_ref()479
.filter(|call| !call.chat_open)480
.and_then(|call| call.chat_thread())481
else {424
return 0;482
return 0;425
};483
};426
let counted = self.directory.unread_counts.get(thread).copied();484
let counted = self.directory.unread_counts.get(thread).copied();427
counted.unwrap_or_else(|| u32::from(self.sidebar.chats.iter().any(|chat| chat.id == thread && chat.unread)))485
counted.unwrap_or_else(|| {486
u32::from(487
self.sidebar488
.chats489
.iter()490
.any(|chat| chat.id == thread && chat.unread),491
)492
})428
}493
}429
494
430
pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {495
pub fn toggle_call_hand(&mut self, cx: &mut Context<Self>) {431
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {496
let Some(call) = self497
.call498
.as_mut()499
.filter(|call| call.model.is_active() && call.model.has_reaction_controls())500
else {432
return;501
return;433
};502
};434
let raised = call.model.own_hand.is_none();503
let raised = call.model.own_hand.is_none();@@ -442,21 +511,31 @@ impl AppState {442
}511
}443
512
444
pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {513
pub fn lower_call_hand(&mut self, mri: String, _cx: &mut Context<Self>) {445
let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands());514
let allowed = self515
.call516
.as_ref()517
.is_some_and(|call| call.model.can_lower_hands());446
if allowed {518
if allowed {447
self.send_call_command(CallCommand::LowerHand { mri });519
self.send_call_command(CallCommand::LowerHand { mri });448
}520
}449
}521
}450
522
451
pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {523
pub fn lower_all_call_hands(&mut self, _cx: &mut Context<Self>) {452
let allowed = self.call.as_ref().is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());524
let allowed = self525
.call526
.as_ref()527
.is_some_and(|call| call.model.can_lower_hands() && call.model.any_hand_raised());453
if allowed {528
if allowed {454
self.send_call_command(CallCommand::LowerAllHands);529
self.send_call_command(CallCommand::LowerAllHands);455
}530
}456
}531
}457
532
458
pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {533
pub fn send_call_reaction(&mut self, reaction: Reaction, cx: &mut Context<Self>) {459
let Some(call) = self.call.as_mut().filter(|call| call.model.is_active() && call.model.has_reaction_controls()) else {534
let Some(call) = self535
.call536
.as_mut()537
.filter(|call| call.model.is_active() && call.model.has_reaction_controls())538
else {460
return;539
return;461
};540
};462
if let Some(own_mri) = call.model.own_mri.clone() {541
if let Some(own_mri) = call.model.own_mri.clone() {@@ -469,52 +548,86 @@ impl AppState {469
548
470
pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {549
pub fn set_call_share_sound(&mut self, on: bool, cx: &mut Context<Self>) {471
self.call_share_sound = on;550
self.call_share_sound = on;472
let _ = self.store.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });551
let _ = self552
.store553
.set_meta(SHARE_SOUND_META_KEY, if on { "1" } else { "0" });473
self.send_call_command(CallCommand::SetShareSound(on));554
self.send_call_command(CallCommand::SetShareSound(on));474
cx.notify();555
cx.notify();475
}556
}476
557
477
pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {558
pub fn admit_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {478
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {559
if self560
.call561
.as_ref()562
.is_some_and(|call| call.model.can_admit())563
{479
self.send_call_command(CallCommand::Admit { mri });564
self.send_call_command(CallCommand::Admit { mri });480
}565
}481
}566
}482
567
483
pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {568
pub fn admit_all_call_guests(&mut self, _cx: &mut Context<Self>) {484
if self.call.as_ref().is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty()) {569
if self570
.call571
.as_ref()572
.is_some_and(|call| call.model.can_admit() && !call.model.lobby_guests().is_empty())573
{485
self.send_call_command(CallCommand::AdmitAll);574
self.send_call_command(CallCommand::AdmitAll);486
}575
}487
}576
}488
577
489
pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {578
pub fn deny_call_guest(&mut self, mri: String, _cx: &mut Context<Self>) {490
if self.call.as_ref().is_some_and(|call| call.model.can_admit()) {579
if self580
.call581
.as_ref()582
.is_some_and(|call| call.model.can_admit())583
{491
self.send_call_command(CallCommand::Deny { mri });584
self.send_call_command(CallCommand::Deny { mri });492
}585
}493
}586
}494
587
495
pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {588
pub fn mute_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {496
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {589
if self590
.call591
.as_ref()592
.is_some_and(|call| call.model.can_manage())593
{497
self.send_call_command(CallCommand::MuteParticipant { mri });594
self.send_call_command(CallCommand::MuteParticipant { mri });498
}595
}499
}596
}500
597
501
pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {598
pub fn mute_all_call(&mut self, _cx: &mut Context<Self>) {502
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {599
if self600
.call601
.as_ref()602
.is_some_and(|call| call.model.can_manage())603
{503
self.send_call_command(CallCommand::MuteAll);604
self.send_call_command(CallCommand::MuteAll);504
}605
}505
}606
}506
607
507
pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {608
pub fn remove_call_participant(&mut self, mri: String, _cx: &mut Context<Self>) {508
if self.call.as_ref().is_some_and(|call| call.model.can_manage()) {609
if self610
.call611
.as_ref()612
.is_some_and(|call| call.model.can_manage())613
{509
self.send_call_command(CallCommand::RemoveParticipant { mri });614
self.send_call_command(CallCommand::RemoveParticipant { mri });510
}615
}511
}616
}512
617
513
pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {618
pub fn toggle_call_spotlight(&mut self, mri: String, _cx: &mut Context<Self>) {514
let Some(call) = self.call.as_ref().filter(|call| call.model.can_manage() && call.model.is_active()) else {619
let Some(call) = self620
.call621
.as_ref()622
.filter(|call| call.model.can_manage() && call.model.is_active())623
else {515
return;624
return;516
};625
};517
let command = if call.model.is_spotlighted(&mri) { CallCommand::StopSpotlight { mri } } else { CallCommand::Spotlight { mri } };626
let command = if call.model.is_spotlighted(&mri) {627
CallCommand::StopSpotlight { mri }628
} else {629
CallCommand::Spotlight { mri }630
};518
self.send_call_command(command);631
self.send_call_command(command);519
}632
}520
633
@@ -526,7 +639,11 @@ impl AppState {526
}639
}527
640
528
pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {641
pub fn toggle_call_captions(&mut self, _cx: &mut Context<Self>) {529
let Some(call) = self.call.as_ref().filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting) else {642
let Some(call) = self643
.call644
.as_ref()645
.filter(|call| call.model.is_active() && call.model.kind == CallKind::Meeting)646
else {530
return;647
return;531
};648
};532
let on = !call.model.captions_on();649
let on = !call.model.captions_on();@@ -549,19 +666,34 @@ impl AppState {549
self.send_call_command(CallCommand::SetBackground(choice));666
self.send_call_command(CallCommand::SetBackground(choice));550
return;667
return;551
}668
}552
let BackgroundPick::Default(id) = pick else { return };669
let BackgroundPick::Default(id) = pick else {553
let Some(image) = self.call_backgrounds.find(&id).cloned() else { return };670
return;554
let Some(launcher) = self.call_launcher.clone() else { return };671
};672
let Some(image) = self.call_backgrounds.find(&id).cloned() else {673
return;674
};675
let Some(launcher) = self.call_launcher.clone() else {676
return;677
};555
let cache = self.call_backgrounds.cache.clone();678
let cache = self.call_backgrounds.cache.clone();556
let receiver = crate::runtime::spawn(async move { launcher.download_background(&cache, &image).await });679
let receiver =680
crate::runtime::spawn(681
async move { launcher.download_background(&cache, &image).await },682
);557
cx.spawn(async move |this, cx| {683
cx.spawn(async move |this, cx| {558
let path = receiver.await.ok().flatten();684
let path = receiver.await.ok().flatten();559
this.update(cx, |state, cx| match path {685
this.update(cx, |state, cx| match path {560
Some(path) if state.call_background == BackgroundPick::Default(id) => {686
Some(path) if state.call_background == BackgroundPick::Default(id) => {561
state.send_call_command(CallCommand::SetBackground(calling::BackgroundChoice::Image(path)));687
state.send_call_command(CallCommand::SetBackground(688
calling::BackgroundChoice::Image(path),689
));562
}690
}563
Some(_) => {}691
Some(_) => {}564
None => state.raise_notice("That background could not be downloaded".to_owned(), None, cx),692
None => state.raise_notice(693
"That background could not be downloaded".to_owned(),694
None,695
cx,696
),565
})697
})566
.ok();698
.ok();567
})699
})@@ -572,11 +704,16 @@ impl AppState {572
if self.mode.demo || !self.call_backgrounds.needs_refresh() {704
if self.mode.demo || !self.call_backgrounds.needs_refresh() {573
return;705
return;574
}706
}575
let Some(launcher) = self.call_launcher.clone() else { return };707
let Some(launcher) = self.call_launcher.clone() else {708
return;709
};576
self.call_backgrounds.refreshing = true;710
self.call_backgrounds.refreshing = true;577
let cache = self.call_backgrounds.cache.clone();711
let cache = self.call_backgrounds.cache.clone();578
let wanted = SHOWN_IMAGES;712
let wanted = SHOWN_IMAGES;579
let receiver = crate::runtime::spawn(async move { launcher.refresh_backgrounds(&cache, wanted).await });713
let receiver =714
crate::runtime::spawn(715
async move { launcher.refresh_backgrounds(&cache, wanted).await },716
);580
cx.spawn(async move |this, cx| {717
cx.spawn(async move |this, cx| {581
let catalog = receiver.await.ok().flatten();718
let catalog = receiver.await.ok().flatten();582
this.update(cx, |state, cx| {719
this.update(cx, |state, cx| {@@ -592,9 +729,20 @@ impl AppState {592
}729
}593
730
594
pub fn add_call_background(&mut self, cx: &mut Context<Self>) {731
pub fn add_call_background(&mut self, cx: &mut Context<Self>) {595
let receiver = cx.prompt_for_paths(PathPromptOptions { files: true, directories: false, multiple: false, prompt: None });732
let receiver = cx.prompt_for_paths(PathPromptOptions {733
files: true,734
directories: false,735
multiple: false,736
prompt: None,737
});596
cx.spawn(async move |this, cx| {738
cx.spawn(async move |this, cx| {597
let Some(path) = receiver.await.ok().and_then(Result::ok).flatten().and_then(|paths| paths.into_iter().next()) else {739
let Some(path) = receiver740
.await741
.ok()742
.and_then(Result::ok)743
.flatten()744
.and_then(|paths| paths.into_iter().next())745
else {598
return;746
return;599
};747
};600
this.update(cx, |state, cx| {748
this.update(cx, |state, cx| {@@ -612,7 +760,11 @@ impl AppState {612
}760
}613
761
614
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {762
pub fn toggle_stage_fullscreen(&mut self, cx: &mut Context<Self>) {615
let Some(call) = self.call.as_mut().filter(|call| call.model.screen_sharer.is_some()) else {763
let Some(call) = self764
.call765
.as_mut()766
.filter(|call| call.model.screen_sharer.is_some())767
else {616
return;768
return;617
};769
};618
call.stage_fullscreen = !call.stage_fullscreen;770
call.stage_fullscreen = !call.stage_fullscreen;@@ -630,7 +782,9 @@ impl AppState {630
}782
}631
783
632
pub fn stage_fullscreen(&self) -> bool {784
pub fn stage_fullscreen(&self) -> bool {633
self.call.as_ref().is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())785
self.call786
.as_ref()787
.is_some_and(|call| call.stage_fullscreen && call.model.screen_sharer.is_some())634
}788
}635
789
636
pub fn viewing_call(&self) -> bool {790
pub fn viewing_call(&self) -> bool {@@ -649,7 +803,11 @@ impl AppState {649
}803
}650
804
651
fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {805
fn push_ring(&mut self, ring: calling::IncomingRing, demo: bool, cx: &mut Context<Self>) {652
let caller_user_id = ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned);806
let caller_user_id = ring807
.caller808
.mri809
.strip_prefix(ORGID_PREFIX)810
.map(str::to_owned);653
self.rings.push(ring, demo, Instant::now());811
self.rings.push(ring, demo, Instant::now());654
if let Some(user_id) = caller_user_id {812
if let Some(user_id) = caller_user_id {655
self.request_avatars(vec![user_id], cx);813
self.request_avatars(vec![user_id], cx);@@ -671,10 +829,22 @@ impl AppState {671
return;829
return;672
}830
}673
let (script, model, conversation_id) = if scene.is_one_to_one() {831
let (script, model, conversation_id) = if scene.is_one_to_one() {674
(DemoCall::People(vec![demo_caller()]), CallModel::people("Mara Lindqvist", &[demo_caller()]), "demo-chat-mara")832
(833
DemoCall::People(vec![demo_caller()]),834
CallModel::people("Mara Lindqvist", &[demo_caller()]),835
"demo-chat-mara",836
)675
} else {837
} else {676
let script = DemoCall::Meeting { guests: demo_guests(DEMO_SMALL_MEETING), lobby: false, organizer: true };838
let script = DemoCall::Meeting {677
(script, CallModel::meeting("Standup", true), "demo-chat-meeting-standup")839
guests: demo_guests(DEMO_SMALL_MEETING),840
lobby: false,841
organizer: true,842
};843
(844
script,845
CallModel::meeting("Standup", true),846
"demo-chat-meeting-standup",847
)678
};848
};679
let handle = start_demo_scene_call(script, scene);849
let handle = start_demo_scene_call(script, scene);680
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);850
self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);@@ -754,7 +924,8 @@ impl AppState {754
self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);924
self.raise_notice(ANSWER_FAILED_NOTICE.to_owned(), None, cx);755
return;925
return;756
};926
};757
let receiver = crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });927
let receiver =928
crate::runtime::spawn(async move { launcher.accept_ring(ring_id, mode).await });758
cx.spawn(async move |this, cx| {929
cx.spawn(async move |this, cx| {759
let handle = receiver.await.ok().flatten();930
let handle = receiver.await.ok().flatten();760
this.update(cx, |state, cx| match handle {931
this.update(cx, |state, cx| match handle {@@ -778,7 +949,11 @@ impl AppState {778
}949
}779
950
780
pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {951
pub fn conversation_of_missed_call(&self, missed: &MissedCall) -> Option<String> {781
if let Some(thread_id) = missed.thread_id.as_ref().filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id)) {952
if let Some(thread_id) = missed953
.thread_id954
.as_ref()955
.filter(|id| self.sidebar.chats.iter().any(|chat| &chat.id == *id))956
{782
return Some(thread_id.clone());957
return Some(thread_id.clone());783
}958
}784
let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;959
let user_id = missed.caller_mri.strip_prefix(ORGID_PREFIX)?;@@ -787,7 +962,10 @@ impl AppState {787
.iter()962
.iter()788
.find(|chat| {963
.find(|chat| {789
crate::data::is_one_on_one(chat)964
crate::data::is_one_on_one(chat)790
&& chat.members.iter().any(|member| member.user_id.as_deref() == Some(user_id))965
&& chat966
.members967
.iter()968
.any(|member| member.user_id.as_deref() == Some(user_id))791
})969
})792
.map(|chat| chat.id.clone())970
.map(|chat| chat.id.clone())793
}971
}@@ -818,12 +996,15 @@ impl AppState {818
}996
}819
997
820
pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {998
pub fn watches_live_meeting(&self, conversation_id: &str) -> bool {821
let meeting_chat = self999
let meeting_chat =822
.sidebar1000
self.sidebar.chats.iter().any(|chat| {823
.chats1001
chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND)824
.iter()1002
});825
.any(|chat| chat.id == conversation_id && chat.kind.eq_ignore_ascii_case(MEETING_KIND));1003
meeting_chat826
meeting_chat || matches!(selection_for(&self.sidebar, conversation_id), Some(Selection::Channel(_)))1004
|| matches!(1005
selection_for(&self.sidebar, conversation_id),1006
Some(Selection::Channel(_))1007
)827
}1008
}828
1009
829
pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {1010
pub fn refresh_live_meeting(&mut self, conversation_id: &str, cx: &mut Context<Self>) {@@ -837,19 +1018,32 @@ impl AppState {837
return;1018
return;838
}1019
}839
let thread_id = conversation_id.to_owned();1020
let thread_id = conversation_id.to_owned();840
let receiver = crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });1021
let receiver =1022
crate::runtime::spawn(async move { launcher.live_meeting(&thread_id).await });841
let conversation_id = conversation_id.to_owned();1023
let conversation_id = conversation_id.to_owned();842
cx.spawn(async move |this, cx| {1024
cx.spawn(async move |this, cx| {843
let meeting = receiver.await.ok().flatten();1025
let meeting = receiver.await.ok().flatten();844
this.update(cx, |state, cx| state.apply_live_meeting(conversation_id, meeting, cx)).ok();1026
this.update(cx, |state, cx| {1027
state.apply_live_meeting(conversation_id, meeting, cx)1028
})1029
.ok();845
})1030
})846
.detach();1031
.detach();847
}1032
}848
1033
849
pub fn apply_live_meeting(&mut self, conversation_id: String, meeting: Option<LiveMeeting>, cx: &mut Context<Self>) {1034
pub fn apply_live_meeting(1035
&mut self,1036
conversation_id: String,1037
meeting: Option<LiveMeeting>,1038
cx: &mut Context<Self>,1039
) {850
self.live_refreshing.remove(&conversation_id);1040
self.live_refreshing.remove(&conversation_id);851
let changed = match meeting {1041
let changed = match meeting {852
Some(meeting) => self.live_meetings.insert(conversation_id.clone(), meeting.clone()) != Some(meeting),1042
Some(meeting) => {1043
self.live_meetings1044
.insert(conversation_id.clone(), meeting.clone())1045
!= Some(meeting)1046
}853
None => self.live_meetings.remove(&conversation_id).is_some(),1047
None => self.live_meetings.remove(&conversation_id).is_some(),854
};1048
};855
if changed {1049
if changed {@@ -870,7 +1064,10 @@ mod tests {870
1064
871
use std::path::PathBuf;1065
use std::path::PathBuf;872
1066
873
use calling::{BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind, EndReason, EngineEvent, HoldState, Reaction, call_channel};1067
use calling::{1068
BackgroundChoice, CallCommand, CallControl, CallState, CallUpdate, DeviceChoice, EndKind,1069
EndReason, EngineEvent, HoldState, Reaction, call_channel,1070
};874
use gpui_kit::{AppContext as _, Entity, TestAppContext};1071
use gpui_kit::{AppContext as _, Entity, TestAppContext};875
use store::{ChatRecord, MemberRecord, Store};1072
use store::{ChatRecord, MemberRecord, Store};876
1073
@@ -890,13 +1087,23 @@ mod tests {890
let (handle, _control) = call_channel();1087
let (handle, _control) = call_channel();891
cx.update(|cx| {1088
cx.update(|cx| {892
app.update(cx, |state, _| {1089
app.update(cx, |state, _| {893
state.call = Some(ActiveCall::new(7, CallModel::test(), handle.commands, None, handle.video));1090
state.call = Some(ActiveCall::new(1091
7,1092
CallModel::test(),1093
handle.commands,1094
None,1095
handle.video,1096
));894
})1097
})895
});1098
});896
app1099
app897
}1100
}898
1101
899
fn app_with_commands(cx: &mut TestAppContext, model: CallModel, conversation_id: Option<&str>) -> (Entity<AppState>, CallControl) {1102
fn app_with_commands(1103
cx: &mut TestAppContext,1104
model: CallModel,1105
conversation_id: Option<&str>,1106
) -> (Entity<AppState>, CallControl) {900
cx.update(gpui_kit::init);1107
cx.update(gpui_kit::init);901
let store = Arc::new(Store::open_in_memory().unwrap());1108
let store = Arc::new(Store::open_in_memory().unwrap());902
let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));1109
let app = cx.update(|cx| cx.new(|_| AppState::new(store, Mode::default())));@@ -904,7 +1111,13 @@ mod tests {904
let conversation_id = conversation_id.map(str::to_owned);1111
let conversation_id = conversation_id.map(str::to_owned);905
cx.update(|cx| {1112
cx.update(|cx| {906
app.update(cx, |state, _| {1113
app.update(cx, |state, _| {907
state.call = Some(ActiveCall::new(7, model, handle.commands, conversation_id, handle.video));1114
state.call = Some(ActiveCall::new(1115
7,1116
model,1117
handle.commands,1118
conversation_id,1119
handle.video,1120
));908
})1121
})909
});1122
});910
(app, control)1123
(app, control)@@ -912,8 +1125,12 @@ mod tests {912
1125
913
fn live_meeting(can_end: bool) -> CallModel {1126
fn live_meeting(can_end: bool) -> CallModel {914
let mut model = CallModel::meeting("Standup", can_end);1127
let mut model = CallModel::meeting("Standup", can_end);915
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1128
model.apply(CallUpdate::State(CallState::Connected {916
model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });1129
since: Instant::now(),1130
}));1131
model.apply(CallUpdate::OwnIdentity {1132
mri: "8:orgid:me".into(),1133
});917
model1134
model918
}1135
}919
1136
@@ -931,13 +1148,31 @@ mod tests {931
.detach();1148
.detach();932
app.update(cx, |state, cx| {1149
app.update(cx, |state, cx| {933
state.apply_call_update(7, CallUpdate::VideoReady, cx);1150
state.apply_call_update(7, CallUpdate::VideoReady, cx);934
state.apply_call_update(7, CallUpdate::Levels { local: 0.5, remote: 0.5 }, cx);1151
state.apply_call_update(935
state.apply_call_update(7, CallUpdate::Stats { inbound_packets: 1, outbound_packets: 1 }, cx);1152
7,1153
CallUpdate::Levels {1154
local: 0.5,1155
remote: 0.5,1156
},1157
cx,1158
);1159
state.apply_call_update(1160
7,1161
CallUpdate::Stats {1162
inbound_packets: 1,1163
outbound_packets: 1,1164
},1165
cx,1166
);936
});1167
});937
});1168
});938
assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);1169
assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 0);939
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));1170
assert!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.remote_speaking));940
cx.update(|cx| app.update(cx, |state, cx| state.apply_call_update(7, CallUpdate::Muted(true), cx)));1171
cx.update(|cx| {1172
app.update(cx, |state, cx| {1173
state.apply_call_update(7, CallUpdate::Muted(true), cx)1174
})1175
});941
assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);1176
assert_eq!(emitted.load(std::sync::atomic::Ordering::SeqCst), 1);942
}1177
}943
1178
@@ -947,7 +1182,10 @@ mod tests {947
let store = cx.update(|cx| app.read(cx).store.clone());1182
let store = cx.update(|cx| app.read(cx).store.clone());948
assert!(!cx.update(|cx| app.read(cx).call_share_sound));1183
assert!(!cx.update(|cx| app.read(cx).call_share_sound));949
cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));1184
cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(true, cx)));950
assert_eq!(control.try_recv_command(), Some(CallCommand::SetShareSound(true)));1185
assert_eq!(1186
control.try_recv_command(),1187
Some(CallCommand::SetShareSound(true))1188
);951
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1189
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));952
assert!(cx.update(|cx| reopened.read(cx).call_share_sound));1190
assert!(cx.update(|cx| reopened.read(cx).call_share_sound));953
cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));1191
cx.update(|cx| app.update(cx, |state, cx| state.set_call_share_sound(false, cx)));@@ -960,16 +1198,29 @@ mod tests {960
let (app, _control) = app_with_commands(cx, live_meeting(false), None);1198
let (app, _control) = app_with_commands(cx, live_meeting(false), None);961
let store = cx.update(|cx| app.read(cx).store.clone());1199
let store = cx.update(|cx| app.read(cx).store.clone());962
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);1200
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);963
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)));1201
cx.update(|cx| {1202
app.update(cx, |state, cx| {1203
state.select_call_camera(DeviceChoice::Device("cam-2".into()), cx)1204
})1205
});964
assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));1206
assert_eq!(load_camera(&store), DeviceChoice::Device("cam-2".into()));965
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1207
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));966
assert_eq!(cx.update(|cx| reopened.read(cx).call_camera.clone()), DeviceChoice::Device("cam-2".into()));1208
assert_eq!(967
cx.update(|cx| app.update(cx, |state, cx| state.select_call_camera(DeviceChoice::SystemDefault, cx)));1209
cx.update(|cx| reopened.read(cx).call_camera.clone()),1210
DeviceChoice::Device("cam-2".into())1211
);1212
cx.update(|cx| {1213
app.update(cx, |state, cx| {1214
state.select_call_camera(DeviceChoice::SystemDefault, cx)1215
})1216
});968
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);1217
assert_eq!(load_camera(&store), DeviceChoice::SystemDefault);969
}1218
}970
1219
971
#[gpui_kit::test]1220
#[gpui_kit::test]972
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(cx: &mut TestAppContext) {1221
fn hands_and_reactions_become_call_commands_and_lowering_needs_the_organizer(1222
cx: &mut TestAppContext,1223
) {973
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1224
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);974
cx.update(|cx| {1225
cx.update(|cx| {975
app.update(cx, |state, cx| {1226
app.update(cx, |state, cx| {@@ -980,28 +1231,46 @@ mod tests {980
})1231
})981
});1232
});982
assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));1233
assert_eq!(control.try_recv_command(), Some(CallCommand::SetHand(true)));983
assert_eq!(control.try_recv_command(), Some(CallCommand::SendReaction(Reaction::Heart)));1234
assert_eq!(1235
control.try_recv_command(),1236
Some(CallCommand::SendReaction(Reaction::Heart))1237
);984
assert_eq!(control.try_recv_command(), None);1238
assert_eq!(control.try_recv_command(), None);985
let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);1239
let (organizer, mut organizer_control) = app_with_commands(cx, live_meeting(true), None);986
cx.update(|cx| {1240
cx.update(|cx| {987
organizer.update(cx, |state, cx| {1241
organizer.update(cx, |state, cx| {988
state.apply_call_update(7, CallUpdate::Roster(vec![calling::RosterEntry {1242
state.apply_call_update(989
mri: "8:orgid:a".into(),1243
7,990
display_name: "Ana".into(),1244
CallUpdate::Roster(vec![calling::RosterEntry {991
muted: false,1245
mri: "8:orgid:a".into(),992
in_lobby: false,1246
display_name: "Ana".into(),993
has_video: false,1247
muted: false,994
sharing: false,1248
in_lobby: false,995
hand: Some(calling::RaisedHand { state_id: "s".into(), rank: 1 }),1249
has_video: false,996
spotlight: None,1250
sharing: false,997
organizer: false,1251
hand: Some(calling::RaisedHand {998
}]), cx);1252
state_id: "s".into(),1253
rank: 1,1254
}),1255
spotlight: None,1256
organizer: false,1257
}]),1258
cx,1259
);999
state.lower_call_hand("8:orgid:a".into(), cx);1260
state.lower_call_hand("8:orgid:a".into(), cx);1000
state.lower_all_call_hands(cx);1261
state.lower_all_call_hands(cx);1001
})1262
})1002
});1263
});1003
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerHand { mri: "8:orgid:a".into() }));1264
assert_eq!(1004
assert_eq!(organizer_control.try_recv_command(), Some(CallCommand::LowerAllHands));1265
organizer_control.try_recv_command(),1266
Some(CallCommand::LowerHand {1267
mri: "8:orgid:a".into()1268
})1269
);1270
assert_eq!(1271
organizer_control.try_recv_command(),1272
Some(CallCommand::LowerAllHands)1273
);1005
}1274
}1006
1275
1007
fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {1276
fn guest(mri: &str, name: &str, in_lobby: bool, spotlit: bool) -> calling::RosterEntry {@@ -1013,7 +1282,10 @@ mod tests {1013
has_video: false,1282
has_video: false,1014
sharing: false,1283
sharing: false,1015
hand: None,1284
hand: None,1016
spotlight: spotlit.then(|| calling::Spotlight { state_id: "sp".into(), rank: 1 }),1285
spotlight: spotlit.then(|| calling::Spotlight {1286
state_id: "sp".into(),1287
rank: 1,1288
}),1017
organizer: false,1289
organizer: false,1018
}1290
}1019
}1291
}@@ -1036,7 +1308,14 @@ mod tests {1036
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);1308
let (organizer, mut control) = app_with_commands(cx, live_meeting(true), None);1037
cx.update(|cx| {1309
cx.update(|cx| {1038
organizer.update(cx, |state, cx| {1310
organizer.update(cx, |state, cx| {1039
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, false), guest("8:orgid:g", "Gast", true, false)]), cx);1311
state.apply_call_update(1312
7,1313
CallUpdate::Roster(vec![1314
guest("8:orgid:a", "Ana", false, false),1315
guest("8:orgid:g", "Gast", true, false),1316
]),1317
cx,1318
);1040
state.admit_call_guest("8:orgid:g".into(), cx);1319
state.admit_call_guest("8:orgid:g".into(), cx);1041
state.admit_all_call_guests(cx);1320
state.admit_all_call_guests(cx);1042
state.deny_call_guest("8:orgid:g".into(), cx);1321
state.deny_call_guest("8:orgid:g".into(), cx);@@ -1046,29 +1325,68 @@ mod tests {1046
state.toggle_call_spotlight("8:orgid:a".into(), cx);1325
state.toggle_call_spotlight("8:orgid:a".into(), cx);1047
})1326
})1048
});1327
});1049
assert_eq!(control.try_recv_command(), Some(CallCommand::Admit { mri: "8:orgid:g".into() }));1328
assert_eq!(1329
control.try_recv_command(),1330
Some(CallCommand::Admit {1331
mri: "8:orgid:g".into()1332
})1333
);1050
assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));1334
assert_eq!(control.try_recv_command(), Some(CallCommand::AdmitAll));1051
assert_eq!(control.try_recv_command(), Some(CallCommand::Deny { mri: "8:orgid:g".into() }));1335
assert_eq!(1052
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteParticipant { mri: "8:orgid:a".into() }));1336
control.try_recv_command(),1337
Some(CallCommand::Deny {1338
mri: "8:orgid:g".into()1339
})1340
);1341
assert_eq!(1342
control.try_recv_command(),1343
Some(CallCommand::MuteParticipant {1344
mri: "8:orgid:a".into()1345
})1346
);1053
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));1347
assert_eq!(control.try_recv_command(), Some(CallCommand::MuteAll));1054
assert_eq!(control.try_recv_command(), Some(CallCommand::RemoveParticipant { mri: "8:orgid:a".into() }));1348
assert_eq!(1055
assert_eq!(control.try_recv_command(), Some(CallCommand::Spotlight { mri: "8:orgid:a".into() }));1349
control.try_recv_command(),1350
Some(CallCommand::RemoveParticipant {1351
mri: "8:orgid:a".into()1352
})1353
);1354
assert_eq!(1355
control.try_recv_command(),1356
Some(CallCommand::Spotlight {1357
mri: "8:orgid:a".into()1358
})1359
);1056
}1360
}1057
1361
1058
#[gpui_kit::test]1362
#[gpui_kit::test]1059
fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(cx: &mut TestAppContext) {1363
fn the_spotlight_button_stops_an_existing_spotlight_and_pinning_stays_local(1364
cx: &mut TestAppContext,1365
) {1060
let (app, mut control) = app_with_commands(cx, live_meeting(true), None);1366
let (app, mut control) = app_with_commands(cx, live_meeting(true), None);1061
cx.update(|cx| {1367
cx.update(|cx| {1062
app.update(cx, |state, cx| {1368
app.update(cx, |state, cx| {1063
state.apply_call_update(7, CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]), cx);1369
state.apply_call_update(1370
7,1371
CallUpdate::Roster(vec![guest("8:orgid:a", "Ana", false, true)]),1372
cx,1373
);1064
state.toggle_call_spotlight("8:orgid:a".into(), cx);1374
state.toggle_call_spotlight("8:orgid:a".into(), cx);1065
state.toggle_call_pin("8:orgid:a", cx);1375
state.toggle_call_pin("8:orgid:a", cx);1066
assert_eq!(state.call.as_ref().unwrap().model.pinned.as_deref(), Some("8:orgid:a"));1376
assert_eq!(1377
state.call.as_ref().unwrap().model.pinned.as_deref(),1378
Some("8:orgid:a")1379
);1067
state.toggle_call_pin("8:orgid:a", cx);1380
state.toggle_call_pin("8:orgid:a", cx);1068
assert_eq!(state.call.as_ref().unwrap().model.pinned, None);1381
assert_eq!(state.call.as_ref().unwrap().model.pinned, None);1069
})1382
})1070
});1383
});1071
assert_eq!(control.try_recv_command(), Some(CallCommand::StopSpotlight { mri: "8:orgid:a".into() }));1384
assert_eq!(1385
control.try_recv_command(),1386
Some(CallCommand::StopSpotlight {1387
mri: "8:orgid:a".into()1388
})1389
);1072
assert_eq!(control.try_recv_command(), None);1390
assert_eq!(control.try_recv_command(), None);1073
}1391
}1074
1392
@@ -1082,8 +1400,14 @@ mod tests {1082
state.toggle_call_captions(cx);1400
state.toggle_call_captions(cx);1083
})1401
})1084
});1402
});1085
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(true)));1403
assert_eq!(1086
assert_eq!(control.try_recv_command(), Some(CallCommand::SetCaptions(false)));1404
control.try_recv_command(),1405
Some(CallCommand::SetCaptions(true))1406
);1407
assert_eq!(1408
control.try_recv_command(),1409
Some(CallCommand::SetCaptions(false))1410
);1087
let app = app_with_call(cx);1411
let app = app_with_call(cx);1088
cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));1412
cx.update(|cx| app.update(cx, |state, cx| state.toggle_call_captions(cx)));1089
}1413
}@@ -1092,30 +1416,71 @@ mod tests {1092
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {1416
fn the_background_choice_is_remembered_and_sent_to_the_call(cx: &mut TestAppContext) {1093
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1417
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1094
let store = cx.update(|cx| app.read(cx).store.clone());1418
let store = cx.update(|cx| app.read(cx).store.clone());1095
assert_eq!(cx.update(|cx| app.read(cx).call_background.clone()), BackgroundPick::None);1419
assert_eq!(1096
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx)));1420
cx.update(|cx| app.read(cx).call_background.clone()),1097
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Blur)));1421
BackgroundPick::None1098
assert_eq!(cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()), BackgroundPick::Blur);1422
);1423
cx.update(|cx| {1424
app.update(cx, |state, cx| {1425
state.set_call_background(BackgroundPick::Blur, cx)1426
})1427
});1428
assert_eq!(1429
control.try_recv_command(),1430
Some(CallCommand::SetBackground(BackgroundChoice::Blur))1431
);1432
assert_eq!(1433
cx.update(|cx| app.read(cx).call.as_ref().unwrap().model.background.clone()),1434
BackgroundPick::Blur1435
);1099
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1436
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1100
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Blur);1437
assert_eq!(1438
cx.update(|cx| reopened.read(cx).call_background.clone()),1439
BackgroundPick::Blur1440
);1101
let picture = PathBuf::from("/pictures/wall.jpg");1441
let picture = PathBuf::from("/pictures/wall.jpg");1102
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)));1442
cx.update(|cx| {1103
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::Image(picture.clone()))));1443
app.update(cx, |state, cx| {1444
state.set_call_background(BackgroundPick::Custom(picture.clone()), cx)1445
})1446
});1447
assert_eq!(1448
control.try_recv_command(),1449
Some(CallCommand::SetBackground(BackgroundChoice::Image(1450
picture.clone()1451
)))1452
);1104
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1453
let reopened = cx.update(|cx| cx.new(|_| AppState::new(store.clone(), Mode::default())));1105
assert_eq!(cx.update(|cx| reopened.read(cx).call_background.clone()), BackgroundPick::Custom(picture));1454
assert_eq!(1106
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx)));1455
cx.update(|cx| reopened.read(cx).call_background.clone()),1107
assert_eq!(control.try_recv_command(), Some(CallCommand::SetBackground(BackgroundChoice::None)));1456
BackgroundPick::Custom(picture)1457
);1458
cx.update(|cx| {1459
app.update(cx, |state, cx| {1460
state.set_call_background(BackgroundPick::None, cx)1461
})1462
});1463
assert_eq!(1464
control.try_recv_command(),1465
Some(CallCommand::SetBackground(BackgroundChoice::None))1466
);1108
}1467
}1109
1468
1110
#[gpui_kit::test]1469
#[gpui_kit::test]1111
fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {1470
fn a_default_image_that_is_not_downloaded_yet_sends_nothing(cx: &mut TestAppContext) {1112
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1471
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1113
cx.update(|cx| app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Default("office_01".into()), cx)));1472
cx.update(|cx| {1473
app.update(cx, |state, cx| {1474
state.set_call_background(BackgroundPick::Default("office_01".into()), cx)1475
})1476
});1114
assert_eq!(control.try_recv_command(), None);1477
assert_eq!(control.try_recv_command(), None);1115
}1478
}1116
1479
1117
#[gpui_kit::test]1480
#[gpui_kit::test]1118
fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(cx: &mut TestAppContext) {1481
fn only_the_organizer_starts_a_recording_and_the_notice_needs_a_consent_request(1482
cx: &mut TestAppContext,1483
) {1119
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);1484
let (attendee, mut attendee_control) = app_with_commands(cx, live_meeting(false), None);1120
cx.update(|cx| {1485
cx.update(|cx| {1121
attendee.update(cx, |state, cx| {1486
attendee.update(cx, |state, cx| {@@ -1135,15 +1500,32 @@ mod tests {1135
state.accept_recording_notice(cx);1500
state.accept_recording_notice(cx);1136
})1501
})1137
});1502
});1138
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: true, title: "Standup".into() }));1503
assert_eq!(1139
assert_eq!(control.try_recv_command(), Some(CallCommand::SetRecording { on: false, title: "Standup".into() }));1504
control.try_recv_command(),1140
assert_eq!(control.try_recv_command(), Some(CallCommand::ConsentToRecording));1505
Some(CallCommand::SetRecording {1506
on: true,1507
title: "Standup".into()1508
})1509
);1510
assert_eq!(1511
control.try_recv_command(),1512
Some(CallCommand::SetRecording {1513
on: false,1514
title: "Standup".into()1515
})1516
);1517
assert_eq!(1518
control.try_recv_command(),1519
Some(CallCommand::ConsentToRecording)1520
);1141
assert_eq!(control.try_recv_command(), None);1521
assert_eq!(control.try_recv_command(), None);1142
}1522
}1143
1523
1144
fn live_one_to_one() -> CallModel {1524
fn live_one_to_one() -> CallModel {1145
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);1525
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);1146
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1526
model.apply(CallUpdate::State(CallState::Connected {1527
since: Instant::now(),1528
}));1147
model1529
model1148
}1530
}1149
1531
@@ -1168,16 +1550,33 @@ mod tests {1168
}1550
}1169
1551
1170
fn candidate(name: &str) -> TransferCandidate {1552
fn candidate(name: &str) -> TransferCandidate {1171
TransferCandidate { mri: format!("8:orgid:{name}"), name: name.into(), user_id: Some(name.into()), chat_id: format!("19:{name}") }1553
TransferCandidate {1554
mri: format!("8:orgid:{name}"),1555
name: name.into(),1556
user_id: Some(name.into()),1557
chat_id: format!("19:{name}"),1558
}1172
}1559
}1173
1560
1174
#[gpui_kit::test]1561
#[gpui_kit::test]1175
fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(cx: &mut TestAppContext) {1562
fn a_blind_transfer_names_the_target_and_a_consulted_one_carries_the_replacement_link(1563
cx: &mut TestAppContext,1564
) {1176
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);1565
let (app, mut control) = app_with_commands(cx, live_one_to_one(), None);1177
cx.update(|cx| app.update(cx, |state, cx| state.transfer_call_blind(candidate("ana"), cx)));1566
cx.update(|cx| {1567
app.update(cx, |state, cx| {1568
state.transfer_call_blind(candidate("ana"), cx)1569
})1570
});1178
assert_eq!(1571
assert_eq!(1179
control.try_recv_command(),1572
control.try_recv_command(),1180
Some(CallCommand::Transfer { target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "ana".into() }, replaces: None })1573
Some(CallCommand::Transfer {1574
target: calling::Callee {1575
mri: "8:orgid:ana".into(),1576
display_name: "ana".into()1577
},1578
replaces: None1579
})1181
);1580
);1182
let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);1581
let (consulting, mut consult_control) = app_with_commands(cx, live_one_to_one(), None);1183
let (consult_handle, _consult_updates) = call_channel();1582
let (consult_handle, _consult_updates) = call_channel();@@ -1192,14 +1591,20 @@ mod tests {1192
transferring: false,1591
transferring: false,1193
});1592
});1194
state.transfer_consulted(cx);1593
state.transfer_consulted(cx);1195
state.call.as_mut().unwrap().consult.as_mut().unwrap().state = CallState::Connected { since: Instant::now() };1594
state.call.as_mut().unwrap().consult.as_mut().unwrap().state =1595
CallState::Connected {1596
since: Instant::now(),1597
};1196
state.transfer_consulted(cx);1598
state.transfer_consulted(cx);1197
})1599
})1198
});1600
});1199
assert_eq!(1601
assert_eq!(1200
consult_control.try_recv_command(),1602
consult_control.try_recv_command(),1201
Some(CallCommand::Transfer {1603
Some(CallCommand::Transfer {1202
target: calling::Callee { mri: "8:orgid:ana".into(), display_name: "Ana".into() },1604
target: calling::Callee {1605
mri: "8:orgid:ana".into(),1606
display_name: "Ana".into()1607
},1203
replaces: Some("https://cc.skype.com/replacement".into()),1608
replaces: Some("https://cc.skype.com/replacement".into()),1204
})1609
})1205
);1610
);@@ -1207,16 +1612,31 @@ mod tests {1207
}1612
}1208
1613
1209
#[gpui_kit::test]1614
#[gpui_kit::test]1210
fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(cx: &mut TestAppContext) {1615
fn the_transfer_list_holds_one_to_one_chats_without_the_person_on_the_call(1616
cx: &mut TestAppContext,1617
) {1211
let app = app_with_chats(cx);1618
let app = app_with_chats(cx);1212
cx.update(|cx| {1619
cx.update(|cx| {1213
app.update(cx, |state, cx| {1620
app.update(cx, |state, cx| {1214
let names: Vec<String> = state.transfer_candidates().into_iter().map(|candidate| candidate.name).collect();1621
let names: Vec<String> = state1622
.transfer_candidates()1623
.into_iter()1624
.map(|candidate| candidate.name)1625
.collect();1215
assert_eq!(names, vec!["Bea".to_owned()]);1626
assert_eq!(names, vec!["Bea".to_owned()]);1216
let (handle, _control) = call_channel();1627
let (handle, _control) = call_channel();1217
let mut on_the_call = CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);1628
let mut on_the_call =1218
on_the_call.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1629
CallModel::people("Bea", &[("8:orgid:bea-id".into(), "Bea".into())]);1219
state.call = Some(ActiveCall::new(9, on_the_call, handle.commands, None, handle.video));1630
on_the_call.apply(CallUpdate::State(CallState::Connected {1631
since: Instant::now(),1632
}));1633
state.call = Some(ActiveCall::new(1634
9,1635
on_the_call,1636
handle.commands,1637
None,1638
handle.video,1639
));1220
assert!(state.transfer_candidates().is_empty());1640
assert!(state.transfer_candidates().is_empty());1221
cx.notify();1641
cx.notify();1222
})1642
})@@ -1226,13 +1646,23 @@ mod tests {1226
fn room_move(returning: bool) -> calling::BreakoutMove {1646
fn room_move(returning: bool) -> calling::BreakoutMove {1227
calling::BreakoutMove {1647
calling::BreakoutMove {1228
room_name: "Room 1".into(),1648
room_name: "Room 1".into(),1229
target: calling::MeetingTarget { thread_id: "19:meeting_room@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None },1649
target: calling::MeetingTarget {1650
thread_id: "19:meeting_room@thread.v2".into(),1651
tenant_id: "t".into(),1652
organizer_id: "o".into(),1653
meeting_data: None,1654
},1230
returning,1655
returning,1231
}1656
}1232
}1657
}1233
1658
1234
fn main_target() -> calling::MeetingTarget {1659
fn main_target() -> calling::MeetingTarget {1235
calling::MeetingTarget { thread_id: "19:meeting_main@thread.v2".into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None }1660
calling::MeetingTarget {1661
thread_id: "19:meeting_main@thread.v2".into(),1662
tenant_id: "t".into(),1663
organizer_id: "o".into(),1664
meeting_data: None,1665
}1236
}1666
}1237
1667
1238
#[gpui_kit::test]1668
#[gpui_kit::test]@@ -1242,13 +1672,22 @@ mod tests {1242
app.update(cx, |state, cx| {1672
app.update(cx, |state, cx| {1243
state.call.as_mut().unwrap().meeting_target = Some(main_target());1673
state.call.as_mut().unwrap().meeting_target = Some(main_target());1244
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);1674
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);1245
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");1675
let pending = state1676
.call1677
.as_ref()1678
.unwrap()1679
.pending_move1680
.clone()1681
.expect("a move is pending");1246
assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");1682
assert_eq!(pending.target.thread_id, "19:meeting_room@thread.v2");1247
assert_eq!(pending.title, "Room 1");1683
assert_eq!(pending.title, "Room 1");1248
let room = pending.breakout.expect("a room");1684
let room = pending.breakout.expect("a room");1249
assert_eq!(room.main, Some(main_target()));1685
assert_eq!(room.main, Some(main_target()));1250
assert_eq!(room.main_title, "Standup");1686
assert_eq!(room.main_title, "Standup");1251
assert_eq!(state.notice.as_ref().map(|notice| notice.text.as_str()), Some("Moving you to Room 1"));1687
assert_eq!(1688
state.notice.as_ref().map(|notice| notice.text.as_str()),1689
Some("Moving you to Room 1")1690
);1252
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);1691
state.apply_call_update(7, CallUpdate::BreakoutMove(room_move(false)), cx);1253
})1692
})1254
});1693
});@@ -1257,14 +1696,26 @@ mod tests {1257
}1696
}1258
1697
1259
#[gpui_kit::test]1698
#[gpui_kit::test]1260
fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(cx: &mut TestAppContext) {1699
fn the_return_button_and_a_closed_room_both_lead_back_to_the_main_meeting(1700
cx: &mut TestAppContext,1701
) {1261
let mut room = live_meeting(false);1702
let mut room = live_meeting(false);1262
room.breakout = Some(BreakoutState { room_name: "Room 1".into(), main: Some(main_target()), main_title: "Standup".into() });1703
room.breakout = Some(BreakoutState {1704
room_name: "Room 1".into(),1705
main: Some(main_target()),1706
main_title: "Standup".into(),1707
});1263
let (app, mut control) = app_with_commands(cx, room.clone(), None);1708
let (app, mut control) = app_with_commands(cx, room.clone(), None);1264
cx.update(|cx| {1709
cx.update(|cx| {1265
app.update(cx, |state, cx| {1710
app.update(cx, |state, cx| {1266
state.return_to_main_meeting(cx);1711
state.return_to_main_meeting(cx);1267
let pending = state.call.as_ref().unwrap().pending_move.clone().expect("a move is pending");1712
let pending = state1713
.call1714
.as_ref()1715
.unwrap()1716
.pending_move1717
.clone()1718
.expect("a move is pending");1268
assert_eq!(pending.target, main_target());1719
assert_eq!(pending.target, main_target());1269
assert_eq!(pending.title, "Standup");1720
assert_eq!(pending.title, "Standup");1270
assert!(pending.breakout.is_none());1721
assert!(pending.breakout.is_none());@@ -1275,18 +1726,31 @@ mod tests {1275
cx.update(|cx| {1726
cx.update(|cx| {1276
closed.update(cx, |state, _| {1727
closed.update(cx, |state, _| {1277
let call = state.call.as_ref().unwrap();1728
let call = state.call.as_ref().unwrap();1278
let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed)).expect("goes back");1729
let moved = room_closed_move(call, &EndReason::Remote(EndKind::RoomClosed))1730
.expect("goes back");1279
assert_eq!(moved.target, main_target());1731
assert_eq!(moved.target, main_target());1280
assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());1732
assert!(room_closed_move(call, &EndReason::Remote(EndKind::Normal)).is_none());1281
assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());1733
assert!(room_closed_move(call, &EndReason::LocalHangup).is_none());1282
})1734
})1283
});1735
});1284
let (plain, _control) = app_with_commands(cx, live_meeting(false), None);1736
let (plain, _control) = app_with_commands(cx, live_meeting(false), None);1285
cx.update(|cx| plain.update(cx, |state, _| assert!(room_closed_move(state.call.as_ref().unwrap(), &EndReason::Remote(EndKind::RoomClosed)).is_none())));1737
cx.update(|cx| {1738
plain.update(cx, |state, _| {1739
assert!(1740
room_closed_move(1741
state.call.as_ref().unwrap(),1742
&EndReason::Remote(EndKind::RoomClosed)1743
)1744
.is_none()1745
)1746
})1747
});1286
}1748
}1287
1749
1288
#[gpui_kit::test]1750
#[gpui_kit::test]1289
fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(cx: &mut TestAppContext) {1751
fn the_whiteboard_menu_asks_for_the_board_unless_someone_already_shares_one(1752
cx: &mut TestAppContext,1753
) {1290
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1754
let (app, mut control) = app_with_commands(cx, live_meeting(false), None);1291
cx.update(|cx| {1755
cx.update(|cx| {1292
app.update(cx, |state, cx| {1756
app.update(cx, |state, cx| {@@ -1305,22 +1769,39 @@ mod tests {1305
state.open_call_whiteboard(cx);1769
state.open_call_whiteboard(cx);1306
})1770
})1307
});1771
});1308
assert_eq!(control.try_recv_command(), Some(CallCommand::OpenWhiteboard { title: "Standup".into() }));1772
assert_eq!(1773
control.try_recv_command(),1774
Some(CallCommand::OpenWhiteboard {1775
title: "Standup".into()1776
})1777
);1309
assert_eq!(control.try_recv_command(), None);1778
assert_eq!(control.try_recv_command(), None);1310
}1779
}1311
1780
1312
#[gpui_kit::test]1781
#[gpui_kit::test]1313
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(cx: &mut TestAppContext) {1782
fn the_chat_panel_opens_the_meeting_thread_and_the_badge_counts_only_while_closed(1783
cx: &mut TestAppContext,1784
) {1314
let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));1785
let (app, _control) = app_with_commands(cx, live_meeting(false), Some("19:list@thread.v2"));1315
cx.update(|cx| {1786
cx.update(|cx| {1316
app.update(cx, |state, cx| {1787
app.update(cx, |state, cx| {1317
state.directory.unread_counts.insert("19:meeting_x@thread.v2".into(), 3);1788
state1789
.directory1790
.unread_counts1791
.insert("19:meeting_x@thread.v2".into(), 3);1318
assert_eq!(state.call_chat_thread(), None);1792
assert_eq!(state.call_chat_thread(), None);1319
assert_eq!(state.call_chat_unread(), 0);1793
assert_eq!(state.call_chat_unread(), 0);1320
state.apply_call_update(7, CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()), cx);1794
state.apply_call_update(1795
7,1796
CallUpdate::MeetingChat("19:meeting_x@thread.v2".into()),1797
cx,1798
);1321
assert_eq!(state.call_chat_unread(), 3);1799
assert_eq!(state.call_chat_unread(), 3);1322
state.toggle_call_chat(cx);1800
state.toggle_call_chat(cx);1323
assert_eq!(state.call_chat_thread().as_deref(), Some("19:meeting_x@thread.v2"));1801
assert_eq!(1802
state.call_chat_thread().as_deref(),1803
Some("19:meeting_x@thread.v2")1804
);1324
assert_eq!(state.call_chat_unread(), 0);1805
assert_eq!(state.call_chat_unread(), 0);1325
state.toggle_call_chat(cx);1806
state.toggle_call_chat(cx);1326
assert_eq!(state.call_chat_thread(), None);1807
assert_eq!(state.call_chat_thread(), None);@@ -1353,15 +1834,24 @@ mod tests {1353
ChatRecord {1834
ChatRecord {1354
id: "19:meeting@thread.v2".into(),1835
id: "19:meeting@thread.v2".into(),1355
kind: "meeting".into(),1836
kind: "meeting".into(),1356
members: vec![MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() }],1837
members: vec![MemberRecord {1838
user_id: Some("bea-id".into()),1839
display_name: "Bea".into(),1840
}],1357
..Default::default()1841
..Default::default()1358
},1842
},1359
ChatRecord {1843
ChatRecord {1360
id: "19:dm@unq.gbl.spaces".into(),1844
id: "19:dm@unq.gbl.spaces".into(),1361
kind: "oneOnOne".into(),1845
kind: "oneOnOne".into(),1362
members: vec![1846
members: vec![1363
MemberRecord { user_id: Some("me-id".into()), display_name: "Me".into() },1847
MemberRecord {1364
MemberRecord { user_id: Some("bea-id".into()), display_name: "Bea".into() },1848
user_id: Some("me-id".into()),1849
display_name: "Me".into(),1850
},1851
MemberRecord {1852
user_id: Some("bea-id".into()),1853
display_name: "Bea".into(),1854
},1365
],1855
],1366
..Default::default()1856
..Default::default()1367
},1857
},@@ -1508,7 +1998,10 @@ mod tests {1508
app.update(cx, |state, cx| {1998
app.update(cx, |state, cx| {1509
state.start_chat_call("19:meeting@thread.v2", cx);1999
state.start_chat_call("19:meeting@thread.v2", cx);1510
assert!(state.call.is_none());2000
assert!(state.call.is_none());1511
assert_eq!(state.notice.as_ref().unwrap().text, "This chat cannot be called");2001
assert_eq!(2002
state.notice.as_ref().unwrap().text,2003
"This chat cannot be called"2004
);1512
state.start_chat_call("19:unknown", cx);2005
state.start_chat_call("19:unknown", cx);1513
assert!(state.call.is_none());2006
assert!(state.call.is_none());1514
})2007
})@@ -1526,9 +2019,18 @@ mod tests {1526
thread_id: None,2019
thread_id: None,1527
at: chrono::Utc::now(),2020
at: chrono::Utc::now(),1528
};2021
};1529
assert_eq!(state.conversation_of_missed_call(&missed).as_deref(), Some("19:dm@unq.gbl.spaces"));2022
assert_eq!(1530
let direct = super::MissedCall { thread_id: Some("19:dm@unq.gbl.spaces".into()), ..missed.clone() };2023
state.conversation_of_missed_call(&missed).as_deref(),1531
assert_eq!(state.conversation_of_missed_call(&direct).as_deref(), Some("19:dm@unq.gbl.spaces"));2024
Some("19:dm@unq.gbl.spaces")2025
);2026
let direct = super::MissedCall {2027
thread_id: Some("19:dm@unq.gbl.spaces".into()),2028
..missed.clone()2029
};2030
assert_eq!(2031
state.conversation_of_missed_call(&direct).as_deref(),2032
Some("19:dm@unq.gbl.spaces")2033
);1532
})2034
})1533
});2035
});1534
}2036
}@@ -32,7 +32,10 @@ impl BackgroundPick {
32
32
pub fn from_meta(value: &str) -> Self {
33
33
match value {
34
34
"blur" | "1" => BackgroundPick::Blur,
35
other => match (other.strip_prefix(DEFAULT_PREFIX), other.strip_prefix(FILE_PREFIX)) {
35
other => match (
36
other.strip_prefix(DEFAULT_PREFIX),
37
other.strip_prefix(FILE_PREFIX),
38
) {
36
39
(Some(id), _) if !id.is_empty() => BackgroundPick::Default(id.to_owned()),
37
40
(_, Some(path)) if !path.is_empty() => BackgroundPick::Custom(PathBuf::from(path)),
38
41
_ => BackgroundPick::None,
@@ -46,7 +49,14 @@ impl BackgroundPick {
46
49
}
47
50
48
51
pub fn load_background(store: &store::Store) -> BackgroundPick {
49
store.meta(BACKGROUND_META_KEY).ok().flatten().or_else(|| store.meta("call_background_blur").ok().flatten()).map_or(BackgroundPick::None, |value| BackgroundPick::from_meta(&value))
52
store
53
.meta(BACKGROUND_META_KEY)
54
.ok()
55
.flatten()
56
.or_else(|| store.meta("call_background_blur").ok().flatten())
57
.map_or(BackgroundPick::None, |value| {
58
BackgroundPick::from_meta(&value)
59
})
50
60
}
51
61
52
62
pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {
@@ -54,12 +64,21 @@ pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {
54
64
.meta(CUSTOM_BACKGROUNDS_META_KEY)
55
65
.ok()
56
66
.flatten()
57
.map(|value| value.lines().filter(|line| !line.is_empty()).map(PathBuf::from).collect())
67
.map(|value| {
68
value
69
.lines()
70
.filter(|line| !line.is_empty())
71
.map(PathBuf::from)
72
.collect()
73
})
58
74
.unwrap_or_default()
59
75
}
60
76
61
77
pub fn save_custom_backgrounds(store: &store::Store, customs: &[PathBuf]) {
62
let joined: Vec<String> = customs.iter().map(|path| path.display().to_string()).collect();
78
let joined: Vec<String> = customs
79
.iter()
80
.map(|path| path.display().to_string())
81
.collect();
63
82
let _ = store.set_meta(CUSTOM_BACKGROUNDS_META_KEY, &joined.join("\n"));
64
83
}
65
84
@@ -80,7 +99,12 @@ impl BackgroundLibrary {
80
99
pub fn new(directory: PathBuf) -> Self {
81
100
let cache = BackgroundCache::new(directory);
82
101
let images = cache.cached_catalog();
83
BackgroundLibrary { cache, images, customs: Vec::new(), refreshing: false }
102
BackgroundLibrary {
103
cache,
104
images,
105
customs: Vec::new(),
106
refreshing: false,
107
}
84
108
}
85
109
86
110
pub fn shown(&self) -> &[DefaultBackground] {
@@ -107,7 +131,12 @@ impl BackgroundLibrary {
107
131
}
108
132
109
133
pub fn needs_refresh(&self) -> bool {
110
!self.refreshing && (self.images.is_empty() || self.shown().iter().any(|image| self.thumbnail(image).is_none()))
134
!self.refreshing
135
&& (self.images.is_empty()
136
|| self
137
.shown()
138
.iter()
139
.any(|image| self.thumbnail(image).is_none()))
111
140
}
112
141
113
142
pub fn choice_for(&self, pick: &BackgroundPick) -> Option<BackgroundChoice> {
@@ -121,22 +150,41 @@ impl BackgroundLibrary {
121
150
}
122
151
123
152
const DEMO_NAMES: [&str; SHOWN_IMAGES] = [
124
"Office", "Loft", "Library", "Beach", "Forest", "Sunset", "Studio", "Garden", "Cafe", "Mountains", "Cabin", "City",
153
"Office",
154
"Loft",
155
"Library",
156
"Beach",
157
"Forest",
158
"Sunset",
159
"Studio",
160
"Garden",
161
"Cafe",
162
"Mountains",
163
"Cabin",
164
"City",
125
165
];
126
166
const DEMO_THUMBNAIL: (u32, u32) = (96, 54);
127
167
const DEMO_IMAGE: (u32, u32) = (640, 360);
128
168
129
169
fn demo_gradient(index: usize, (width, height): (u32, u32)) -> image::RgbaImage {
130
170
let hue = index as f32 / SHOWN_IMAGES as f32;
131
let channel = |offset: f32, row: f32| (((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8;
171
let channel = |offset: f32, row: f32| {
172
(((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8
173
};
132
174
image::RgbaImage::from_fn(width, height, |_, row| {
133
175
let row = row as f32 / height as f32;
134
image::Rgba([channel(0., row), channel(0.33, row), channel(0.66, 1. - row), 255])
176
image::Rgba([
177
channel(0., row),
178
channel(0.33, row),
179
channel(0.66, 1. - row),
180
255,
181
])
135
182
})
136
183
}
137
184
138
185
pub fn demo_library() -> BackgroundLibrary {
139
let directory = std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));
186
let directory =
187
std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));
140
188
let mut library = BackgroundLibrary::new(directory);
141
189
library.images = DEMO_NAMES
142
190
.iter()
@@ -149,7 +197,10 @@ pub fn demo_library() -> BackgroundLibrary {
149
197
})
150
198
.collect();
151
199
for (index, image) in library.images.iter().enumerate() {
152
for (path, size) in [(library.cache.thumbnail_path(image), DEMO_THUMBNAIL), (library.cache.image_path(image), DEMO_IMAGE)] {
200
for (path, size) in [
201
(library.cache.thumbnail_path(image), DEMO_THUMBNAIL),
202
(library.cache.image_path(image), DEMO_IMAGE),
203
] {
153
204
if let Some(parent) = path.parent() {
154
205
let _ = std::fs::create_dir_all(parent);
155
206
}
@@ -162,7 +213,11 @@ pub fn demo_library() -> BackgroundLibrary {
162
213
pub fn is_image_file(path: &Path) -> bool {
163
214
path.extension()
164
215
.and_then(|extension| extension.to_str())
165
.is_some_and(|extension| ["jpg", "jpeg", "png"].iter().any(|known| extension.eq_ignore_ascii_case(known)))
216
.is_some_and(|extension| {
217
["jpg", "jpeg", "png"]
218
.iter()
219
.any(|known| extension.eq_ignore_ascii_case(known))
220
})
166
221
}
167
222
168
223
#[cfg(test)]
@@ -193,10 +248,21 @@ mod tests {
193
248
fn the_store_keeps_the_choice_and_the_own_images() {
194
249
let store = store::Store::open_in_memory().unwrap();
195
250
assert_eq!(load_background(&store), BackgroundPick::None);
196
store.set_meta(BACKGROUND_META_KEY, &BackgroundPick::Default("beach".into()).to_meta()).unwrap();
197
assert_eq!(load_background(&store), BackgroundPick::Default("beach".into()));
251
store
252
.set_meta(
253
BACKGROUND_META_KEY,
254
&BackgroundPick::Default("beach".into()).to_meta(),
255
)
256
.unwrap();
257
assert_eq!(
258
load_background(&store),
259
BackgroundPick::Default("beach".into())
260
);
198
261
save_custom_backgrounds(&store, &[PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);
199
assert_eq!(load_custom_backgrounds(&store), vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);
262
assert_eq!(
263
load_custom_backgrounds(&store),
264
vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]
265
);
200
266
}
201
267
202
268
#[test]
@@ -208,21 +274,35 @@ mod tests {
208
274
209
275
#[test]
210
276
fn own_images_come_first_without_duplicates_and_stay_few() {
211
let mut library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
277
let mut library =
278
BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
212
279
for index in 0..8 {
213
280
library.add_custom(PathBuf::from(format!("/pictures/{index}.png")));
214
281
}
215
282
library.add_custom(PathBuf::from("/pictures/3.png"));
216
283
assert_eq!(library.customs.len(), MAX_CUSTOM);
217
284
assert_eq!(library.customs[0], PathBuf::from("/pictures/3.png"));
218
assert_eq!(library.customs.iter().filter(|path| path.as_path() == Path::new("/pictures/3.png")).count(), 1);
285
assert_eq!(
286
library
287
.customs
288
.iter()
289
.filter(|path| path.as_path() == Path::new("/pictures/3.png"))
290
.count(),
291
1
292
);
219
293
}
220
294
221
295
#[test]
222
296
fn a_default_image_is_only_usable_once_it_is_cached() {
223
297
let library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));
224
assert_eq!(library.choice_for(&BackgroundPick::Default("office_01".into())), None);
225
assert_eq!(library.choice_for(&BackgroundPick::Blur), Some(BackgroundChoice::Blur));
298
assert_eq!(
299
library.choice_for(&BackgroundPick::Default("office_01".into())),
300
None
301
);
302
assert_eq!(
303
library.choice_for(&BackgroundPick::Blur),
304
Some(BackgroundChoice::Blur)
305
);
226
306
assert!(library.needs_refresh());
227
307
}
228
308
@@ -32,7 +32,10 @@ impl BackgroundPick {32
pub fn from_meta(value: &str) -> Self {32
pub fn from_meta(value: &str) -> Self {33
match value {33
match value {34
"blur" | "1" => BackgroundPick::Blur,34
"blur" | "1" => BackgroundPick::Blur,35
other => match (other.strip_prefix(DEFAULT_PREFIX), other.strip_prefix(FILE_PREFIX)) {35
other => match (36
other.strip_prefix(DEFAULT_PREFIX),37
other.strip_prefix(FILE_PREFIX),38
) {36
(Some(id), _) if !id.is_empty() => BackgroundPick::Default(id.to_owned()),39
(Some(id), _) if !id.is_empty() => BackgroundPick::Default(id.to_owned()),37
(_, Some(path)) if !path.is_empty() => BackgroundPick::Custom(PathBuf::from(path)),40
(_, Some(path)) if !path.is_empty() => BackgroundPick::Custom(PathBuf::from(path)),38
_ => BackgroundPick::None,41
_ => BackgroundPick::None,@@ -46,7 +49,14 @@ impl BackgroundPick {46
}49
}47
50
48
pub fn load_background(store: &store::Store) -> BackgroundPick {51
pub fn load_background(store: &store::Store) -> BackgroundPick {49
store.meta(BACKGROUND_META_KEY).ok().flatten().or_else(|| store.meta("call_background_blur").ok().flatten()).map_or(BackgroundPick::None, |value| BackgroundPick::from_meta(&value))52
store53
.meta(BACKGROUND_META_KEY)54
.ok()55
.flatten()56
.or_else(|| store.meta("call_background_blur").ok().flatten())57
.map_or(BackgroundPick::None, |value| {58
BackgroundPick::from_meta(&value)59
})50
}60
}51
61
52
pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {62
pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {@@ -54,12 +64,21 @@ pub fn load_custom_backgrounds(store: &store::Store) -> Vec<PathBuf> {54
.meta(CUSTOM_BACKGROUNDS_META_KEY)64
.meta(CUSTOM_BACKGROUNDS_META_KEY)55
.ok()65
.ok()56
.flatten()66
.flatten()57
.map(|value| value.lines().filter(|line| !line.is_empty()).map(PathBuf::from).collect())67
.map(|value| {68
value69
.lines()70
.filter(|line| !line.is_empty())71
.map(PathBuf::from)72
.collect()73
})58
.unwrap_or_default()74
.unwrap_or_default()59
}75
}60
76
61
pub fn save_custom_backgrounds(store: &store::Store, customs: &[PathBuf]) {77
pub fn save_custom_backgrounds(store: &store::Store, customs: &[PathBuf]) {62
let joined: Vec<String> = customs.iter().map(|path| path.display().to_string()).collect();78
let joined: Vec<String> = customs79
.iter()80
.map(|path| path.display().to_string())81
.collect();63
let _ = store.set_meta(CUSTOM_BACKGROUNDS_META_KEY, &joined.join("\n"));82
let _ = store.set_meta(CUSTOM_BACKGROUNDS_META_KEY, &joined.join("\n"));64
}83
}65
84
@@ -80,7 +99,12 @@ impl BackgroundLibrary {80
pub fn new(directory: PathBuf) -> Self {99
pub fn new(directory: PathBuf) -> Self {81
let cache = BackgroundCache::new(directory);100
let cache = BackgroundCache::new(directory);82
let images = cache.cached_catalog();101
let images = cache.cached_catalog();83
BackgroundLibrary { cache, images, customs: Vec::new(), refreshing: false }102
BackgroundLibrary {103
cache,104
images,105
customs: Vec::new(),106
refreshing: false,107
}84
}108
}85
109
86
pub fn shown(&self) -> &[DefaultBackground] {110
pub fn shown(&self) -> &[DefaultBackground] {@@ -107,7 +131,12 @@ impl BackgroundLibrary {107
}131
}108
132
109
pub fn needs_refresh(&self) -> bool {133
pub fn needs_refresh(&self) -> bool {110
!self.refreshing && (self.images.is_empty() || self.shown().iter().any(|image| self.thumbnail(image).is_none()))134
!self.refreshing135
&& (self.images.is_empty()136
|| self137
.shown()138
.iter()139
.any(|image| self.thumbnail(image).is_none()))111
}140
}112
141
113
pub fn choice_for(&self, pick: &BackgroundPick) -> Option<BackgroundChoice> {142
pub fn choice_for(&self, pick: &BackgroundPick) -> Option<BackgroundChoice> {@@ -121,22 +150,41 @@ impl BackgroundLibrary {121
}150
}122
151
123
const DEMO_NAMES: [&str; SHOWN_IMAGES] = [152
const DEMO_NAMES: [&str; SHOWN_IMAGES] = [124
"Office", "Loft", "Library", "Beach", "Forest", "Sunset", "Studio", "Garden", "Cafe", "Mountains", "Cabin", "City",153
"Office",154
"Loft",155
"Library",156
"Beach",157
"Forest",158
"Sunset",159
"Studio",160
"Garden",161
"Cafe",162
"Mountains",163
"Cabin",164
"City",125
];165
];126
const DEMO_THUMBNAIL: (u32, u32) = (96, 54);166
const DEMO_THUMBNAIL: (u32, u32) = (96, 54);127
const DEMO_IMAGE: (u32, u32) = (640, 360);167
const DEMO_IMAGE: (u32, u32) = (640, 360);128
168
129
fn demo_gradient(index: usize, (width, height): (u32, u32)) -> image::RgbaImage {169
fn demo_gradient(index: usize, (width, height): (u32, u32)) -> image::RgbaImage {130
let hue = index as f32 / SHOWN_IMAGES as f32;170
let hue = index as f32 / SHOWN_IMAGES as f32;131
let channel = |offset: f32, row: f32| (((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8;171
let channel = |offset: f32, row: f32| {172
(((hue + offset).fract() * 0.55 + 0.25 + row * 0.2) * 255.).min(255.) as u8173
};132
image::RgbaImage::from_fn(width, height, |_, row| {174
image::RgbaImage::from_fn(width, height, |_, row| {133
let row = row as f32 / height as f32;175
let row = row as f32 / height as f32;134
image::Rgba([channel(0., row), channel(0.33, row), channel(0.66, 1. - row), 255])176
image::Rgba([177
channel(0., row),178
channel(0.33, row),179
channel(0.66, 1. - row),180
255,181
])135
})182
})136
}183
}137
184
138
pub fn demo_library() -> BackgroundLibrary {185
pub fn demo_library() -> BackgroundLibrary {139
let directory = std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));186
let directory =187
std::env::temp_dir().join(format!("teams-demo-backgrounds-{}", std::process::id()));140
let mut library = BackgroundLibrary::new(directory);188
let mut library = BackgroundLibrary::new(directory);141
library.images = DEMO_NAMES189
library.images = DEMO_NAMES142
.iter()190
.iter()@@ -149,7 +197,10 @@ pub fn demo_library() -> BackgroundLibrary {149
})197
})150
.collect();198
.collect();151
for (index, image) in library.images.iter().enumerate() {199
for (index, image) in library.images.iter().enumerate() {152
for (path, size) in [(library.cache.thumbnail_path(image), DEMO_THUMBNAIL), (library.cache.image_path(image), DEMO_IMAGE)] {200
for (path, size) in [201
(library.cache.thumbnail_path(image), DEMO_THUMBNAIL),202
(library.cache.image_path(image), DEMO_IMAGE),203
] {153
if let Some(parent) = path.parent() {204
if let Some(parent) = path.parent() {154
let _ = std::fs::create_dir_all(parent);205
let _ = std::fs::create_dir_all(parent);155
}206
}@@ -162,7 +213,11 @@ pub fn demo_library() -> BackgroundLibrary {162
pub fn is_image_file(path: &Path) -> bool {213
pub fn is_image_file(path: &Path) -> bool {163
path.extension()214
path.extension()164
.and_then(|extension| extension.to_str())215
.and_then(|extension| extension.to_str())165
.is_some_and(|extension| ["jpg", "jpeg", "png"].iter().any(|known| extension.eq_ignore_ascii_case(known)))216
.is_some_and(|extension| {217
["jpg", "jpeg", "png"]218
.iter()219
.any(|known| extension.eq_ignore_ascii_case(known))220
})166
}221
}167
222
168
#[cfg(test)]223
#[cfg(test)]@@ -193,10 +248,21 @@ mod tests {193
fn the_store_keeps_the_choice_and_the_own_images() {248
fn the_store_keeps_the_choice_and_the_own_images() {194
let store = store::Store::open_in_memory().unwrap();249
let store = store::Store::open_in_memory().unwrap();195
assert_eq!(load_background(&store), BackgroundPick::None);250
assert_eq!(load_background(&store), BackgroundPick::None);196
store.set_meta(BACKGROUND_META_KEY, &BackgroundPick::Default("beach".into()).to_meta()).unwrap();251
store197
assert_eq!(load_background(&store), BackgroundPick::Default("beach".into()));252
.set_meta(253
BACKGROUND_META_KEY,254
&BackgroundPick::Default("beach".into()).to_meta(),255
)256
.unwrap();257
assert_eq!(258
load_background(&store),259
BackgroundPick::Default("beach".into())260
);198
save_custom_backgrounds(&store, &[PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);261
save_custom_backgrounds(&store, &[PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);199
assert_eq!(load_custom_backgrounds(&store), vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]);262
assert_eq!(263
load_custom_backgrounds(&store),264
vec![PathBuf::from("/a.png"), PathBuf::from("/b.jpg")]265
);200
}266
}201
267
202
#[test]268
#[test]@@ -208,21 +274,35 @@ mod tests {208
274
209
#[test]275
#[test]210
fn own_images_come_first_without_duplicates_and_stay_few() {276
fn own_images_come_first_without_duplicates_and_stay_few() {211
let mut library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));277
let mut library =278
BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));212
for index in 0..8 {279
for index in 0..8 {213
library.add_custom(PathBuf::from(format!("/pictures/{index}.png")));280
library.add_custom(PathBuf::from(format!("/pictures/{index}.png")));214
}281
}215
library.add_custom(PathBuf::from("/pictures/3.png"));282
library.add_custom(PathBuf::from("/pictures/3.png"));216
assert_eq!(library.customs.len(), MAX_CUSTOM);283
assert_eq!(library.customs.len(), MAX_CUSTOM);217
assert_eq!(library.customs[0], PathBuf::from("/pictures/3.png"));284
assert_eq!(library.customs[0], PathBuf::from("/pictures/3.png"));218
assert_eq!(library.customs.iter().filter(|path| path.as_path() == Path::new("/pictures/3.png")).count(), 1);285
assert_eq!(286
library287
.customs288
.iter()289
.filter(|path| path.as_path() == Path::new("/pictures/3.png"))290
.count(),291
1292
);219
}293
}220
294
221
#[test]295
#[test]222
fn a_default_image_is_only_usable_once_it_is_cached() {296
fn a_default_image_is_only_usable_once_it_is_cached() {223
let library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));297
let library = BackgroundLibrary::new(std::env::temp_dir().join("calls-test-no-such-cache"));224
assert_eq!(library.choice_for(&BackgroundPick::Default("office_01".into())), None);298
assert_eq!(225
assert_eq!(library.choice_for(&BackgroundPick::Blur), Some(BackgroundChoice::Blur));299
library.choice_for(&BackgroundPick::Default("office_01".into())),300
None301
);302
assert_eq!(303
library.choice_for(&BackgroundPick::Blur),304
Some(BackgroundChoice::Blur)305
);226
assert!(library.needs_refresh());306
assert!(library.needs_refresh());227
}307
}228
308
@@ -1,13 +1,14 @@
1
1
use std::time::{Duration, Instant};
2
2
3
use calling::CameraDevice;
3
4
use calling::video_frame::bgra_from_i420;
4
5
use calling::video_pattern::{PatternKind, pattern_frame};
5
6
use calling::{
6
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState,
7
ContentShare, DeviceChoice, DeviceLists, EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,
8
ShareKind, ShareSource, VideoKey, call_channel,
7
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState,
8
CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists,
9
EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand,
10
Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,
9
11
};
10
use calling::CameraDevice;
11
12
12
13
use super::demo_scene::self_view;
13
14
use tokio::time::{interval, sleep};
@@ -36,10 +37,22 @@ const DEMO_WAITING: [&str; 3] = ["Anja Vogel", "Matteo Conti", "Hannah Weiss"];
36
37
const CAPTION_WORDS_PER_TICK: usize = 2;
37
38
const CAPTION_HOLD_TICKS: usize = 14;
38
39
const DEMO_CAPTIONS: [(usize, &str); 4] = [
39
(0, "Thanks everyone for joining, let us start with the release status."),
40
(1, "The build is green and the new call controls are ready for review."),
41
(2, "Can we admit the two people from the lobby before we begin?"),
42
(0, "Yes, I am letting them in now and we will share the plan on screen."),
40
(
41
0,
42
"Thanks everyone for joining, let us start with the release status.",
43
),
44
(
45
1,
46
"The build is green and the new call controls are ready for review.",
47
),
48
(
49
2,
50
"Can we admit the two people from the lobby before we begin?",
51
),
52
(
53
0,
54
"Yes, I am letting them in now and we will share the plan on screen.",
55
),
43
56
];
44
57
const GUEST_PHASE: u32 = 37;
45
58
const SELF_PHASE: u32 = 211;
@@ -103,7 +116,11 @@ const DEMO_ROOM_THREAD: &str = "19:meeting_demo-room-1@thread.v2";
103
116
pub enum DemoCall {
104
117
Test,
105
118
People(Vec<Person>),
106
Meeting { guests: Vec<Person>, lobby: bool, organizer: bool },
119
Meeting {
120
guests: Vec<Person>,
121
lobby: bool,
122
organizer: bool,
123
},
107
124
Incoming(Person),
108
125
}
109
126
@@ -121,7 +138,10 @@ pub fn demo_caller() -> Person {
121
138
}
122
139
123
140
pub fn demo_video_ring() -> IncomingRing {
124
IncomingRing { video: true, ..demo_ring() }
141
IncomingRing {
142
video: true,
143
..demo_ring()
144
}
125
145
}
126
146
127
147
pub fn demo_ring() -> IncomingRing {
@@ -146,15 +166,29 @@ fn device(index: u16, name: &str) -> AudioDevice {
146
166
147
167
fn demo_cameras() -> Vec<CameraDevice> {
148
168
vec![
149
CameraDevice { key: "0".into(), name: "Integrated Camera".into() },
150
CameraDevice { key: "1".into(), name: "Studio Webcam".into() },
169
CameraDevice {
170
key: "0".into(),
171
name: "Integrated Camera".into(),
172
},
173
CameraDevice {
174
key: "1".into(),
175
name: "Studio Webcam".into(),
176
},
151
177
]
152
178
}
153
179
154
180
fn demo_share_sources() -> Vec<ShareSource> {
155
let window = |id: u64, title: &str| ShareSource { id, kind: ShareKind::Window, title: title.to_owned() };
181
let window = |id: u64, title: &str| ShareSource {
182
id,
183
kind: ShareKind::Window,
184
title: title.to_owned(),
185
};
156
186
vec![
157
ShareSource { id: 1, kind: ShareKind::Screen, title: String::new() },
187
ShareSource {
188
id: 1,
189
kind: ShareKind::Screen,
190
title: String::new(),
191
},
158
192
window(2, "Release notes - Docs"),
159
193
window(3, "Standup board"),
160
194
window(4, "Terminal"),
@@ -163,7 +197,10 @@ fn demo_share_sources() -> Vec<ShareSource> {
163
197
164
198
fn demo_devices() -> DeviceLists {
165
199
DeviceLists {
166
inputs: vec![device(0, "Headset Microphone"), device(1, "Built-in Microphone")],
200
inputs: vec![
201
device(0, "Headset Microphone"),
202
device(1, "Built-in Microphone"),
203
],
167
204
outputs: vec![device(0, "Headset"), device(1, "Speakers")],
168
205
}
169
206
}
@@ -233,11 +270,24 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoSc
233
270
}
234
271
let mut roster = roster_of(&people);
235
272
if matches!(script, DemoCall::People(_)) {
236
control.send(CallUpdate::ReplacementLink(DEMO_REPLACEMENT_LINK.to_owned()));
273
control.send(CallUpdate::ReplacementLink(
274
DEMO_REPLACEMENT_LINK.to_owned(),
275
));
237
276
}
238
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {
277
if matches!(
278
script,
279
DemoCall::Meeting {
280
organizer: true,
281
..
282
}
283
) {
239
284
roster.push(demo_organizer());
240
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));
285
roster.extend(
286
DEMO_WAITING
287
.iter()
288
.enumerate()
289
.map(|(index, name)| demo_waiting(index, name)),
290
);
241
291
}
242
292
if matches!(script, DemoCall::Meeting { .. }) {
243
293
for (index, rank) in DEMO_FIRST_HANDS {
@@ -248,7 +298,9 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoSc
248
298
}
249
299
control.send(CallUpdate::Roster(roster.clone()));
250
300
let video = !matches!(script, DemoCall::Test);
251
let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();
301
let sharer = matches!(script, DemoCall::Meeting { .. })
302
.then(|| people.get(1).map(|person| person.0.clone()))
303
.flatten();
252
304
start_scene(&control, scene);
253
305
speak_until_hangup(control, people, roster, video, sharer, scene).await;
254
306
}
@@ -273,16 +325,31 @@ async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bo
273
325
true
274
326
}
275
327
276
fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, sharing: bool, sharer: Option<&str>, camera: Option<bool>) {
328
fn publish_demo_video(
329
control: &CallControl,
330
people: &[Person],
331
tick: u32,
332
sharing: bool,
333
sharer: Option<&str>,
334
camera: Option<bool>,
335
) {
277
336
if let Some(blur) = camera {
278
control.video.publish(VideoKey::LocalCamera, self_view((tick + SELF_PHASE) as usize, blur));
337
control.video.publish(
338
VideoKey::LocalCamera,
339
self_view((tick + SELF_PHASE) as usize, blur),
340
);
279
341
}
280
342
for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {
281
343
let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);
282
control.video.publish(VideoKey::Person(mri.clone()), bgra_from_i420(frame));
344
control
345
.video
346
.publish(VideoKey::Person(mri.clone()), bgra_from_i420(frame));
283
347
}
284
348
if sharing && sharer.is_some() && tick.is_multiple_of(SCREEN_EVERY_TICKS) {
285
control.video.publish(VideoKey::Screen, bgra_from_i420(pattern_frame(PatternKind::Screen, tick)));
349
control.video.publish(
350
VideoKey::Screen,
351
bgra_from_i420(pattern_frame(PatternKind::Screen, tick)),
352
);
286
353
}
287
354
}
288
355
@@ -301,23 +368,39 @@ fn start_scene(control: &CallControl, scene: DemoScene) {
301
368
302
369
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {
303
370
match scene {
304
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => control.send(CallUpdate::BreakoutMove(BreakoutMove {
305
room_name: "Room 1".to_owned(),
306
target: MeetingTarget { thread_id: DEMO_ROOM_THREAD.to_owned(), tenant_id: "demo-tenant".to_owned(), organizer_id: "demo-me".to_owned(), meeting_data: None },
307
returning: false,
308
})),
309
DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => control.send(CallUpdate::Whiteboard(Some(ContentShare {
310
session_id: "demo-whiteboard".to_owned(),
311
presenter: people.first().map(|person| person.0.clone()),
312
subject: "Whiteboard".to_owned(),
313
url: Some(DEMO_BOARD_URL.to_owned()),
314
whiteboard: true,
315
}))),
371
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {
372
control.send(CallUpdate::BreakoutMove(BreakoutMove {
373
room_name: "Room 1".to_owned(),
374
target: MeetingTarget {
375
thread_id: DEMO_ROOM_THREAD.to_owned(),
376
tenant_id: "demo-tenant".to_owned(),
377
organizer_id: "demo-me".to_owned(),
378
meeting_data: None,
379
},
380
returning: false,
381
}))
382
}
383
DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => {
384
control.send(CallUpdate::Whiteboard(Some(ContentShare {
385
session_id: "demo-whiteboard".to_owned(),
386
presenter: people.first().map(|person| person.0.clone()),
387
subject: "Whiteboard".to_owned(),
388
url: Some(DEMO_BOARD_URL.to_owned()),
389
whiteboard: true,
390
})))
391
}
316
392
_ => {}
317
393
}
318
394
}
319
395
320
async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>, scene: DemoScene) {
396
async fn speak_until_hangup(
397
mut control: CallControl,
398
people: Vec<Person>,
399
mut roster: Vec<RosterEntry>,
400
video: bool,
401
sharer: Option<String>,
402
scene: DemoScene,
403
) {
321
404
let started = Instant::now();
322
405
let mut video_ticks = 0u32;
323
406
let mut sharing = false;
@@ -497,7 +580,10 @@ fn demo_waiting(index: usize, name: &str) -> RosterEntry {
497
580
}
498
581
499
582
fn demo_spotlight(rank: u64) -> PublishedState {
500
PublishedState { state_id: format!("demo-spotlight-{rank}"), rank }
583
PublishedState {
584
state_id: format!("demo-spotlight-{rank}"),
585
rank,
586
}
501
587
}
502
588
503
589
fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {
@@ -517,11 +603,19 @@ fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {
517
603
}
518
604
519
605
fn demo_hand(rank: u64) -> RaisedHand {
520
RaisedHand { state_id: format!("demo-hand-{rank}"), rank }
606
RaisedHand {
607
state_id: format!("demo-hand-{rank}"),
608
rank,
609
}
521
610
}
522
611
523
612
fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {
524
let next_rank = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).max().unwrap_or(0) + 1;
613
let next_rank = roster
614
.iter()
615
.filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))
616
.max()
617
.unwrap_or(0)
618
+ 1;
525
619
if !raised {
526
620
if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {
527
621
entry.hand = None;
@@ -568,7 +662,10 @@ mod tests {
568
662
let mut roster = roster_of(&demo_guests(3));
569
663
set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);
570
664
set_demo_hand(&mut roster, DEMO_OWN_MRI, true);
571
let ranks: Vec<u64> = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).collect();
665
let ranks: Vec<u64> = roster
666
.iter()
667
.filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))
668
.collect();
572
669
assert_eq!(ranks, vec![1, 2]);
573
670
set_demo_hand(&mut roster, DEMO_OWN_MRI, false);
574
671
assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));
@@ -1,13 +1,14 @@1
use std::time::{Duration, Instant};1
use std::time::{Duration, Instant};2
2
3
use calling::CameraDevice;3
use calling::video_frame::bgra_from_i420;4
use calling::video_frame::bgra_from_i420;4
use calling::video_pattern::{PatternKind, pattern_frame};5
use calling::video_pattern::{PatternKind, pattern_frame};5
use calling::{6
use calling::{6
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState, CallUpdate, Caller, CaptionEntry, CaptionState,7
AudioDevice, BackgroundChoice, BreakoutMove, CallCommand, CallControl, CallHandle, CallState,7
ContentShare, DeviceChoice, DeviceLists, EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand, Reaction, RosterEntry,8
CallUpdate, Caller, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists,8
ShareKind, ShareSource, VideoKey, call_channel,9
EndReason, HoldState, IncomingRing, MeetingTarget, Progress, PublishedState, RaisedHand,10
Reaction, RosterEntry, ShareKind, ShareSource, VideoKey, call_channel,9
};11
};10
use calling::CameraDevice;11
12
12
use super::demo_scene::self_view;13
use super::demo_scene::self_view;13
use tokio::time::{interval, sleep};14
use tokio::time::{interval, sleep};@@ -36,10 +37,22 @@ const DEMO_WAITING: [&str; 3] = ["Anja Vogel", "Matteo Conti", "Hannah Weiss"];36
const CAPTION_WORDS_PER_TICK: usize = 2;37
const CAPTION_WORDS_PER_TICK: usize = 2;37
const CAPTION_HOLD_TICKS: usize = 14;38
const CAPTION_HOLD_TICKS: usize = 14;38
const DEMO_CAPTIONS: [(usize, &str); 4] = [39
const DEMO_CAPTIONS: [(usize, &str); 4] = [39
(0, "Thanks everyone for joining, let us start with the release status."),40
(40
(1, "The build is green and the new call controls are ready for review."),41
0,41
(2, "Can we admit the two people from the lobby before we begin?"),42
"Thanks everyone for joining, let us start with the release status.",42
(0, "Yes, I am letting them in now and we will share the plan on screen."),43
),44
(45
1,46
"The build is green and the new call controls are ready for review.",47
),48
(49
2,50
"Can we admit the two people from the lobby before we begin?",51
),52
(53
0,54
"Yes, I am letting them in now and we will share the plan on screen.",55
),43
];56
];44
const GUEST_PHASE: u32 = 37;57
const GUEST_PHASE: u32 = 37;45
const SELF_PHASE: u32 = 211;58
const SELF_PHASE: u32 = 211;@@ -103,7 +116,11 @@ const DEMO_ROOM_THREAD: &str = "19:meeting_demo-room-1@thread.v2";103
pub enum DemoCall {116
pub enum DemoCall {104
Test,117
Test,105
People(Vec<Person>),118
People(Vec<Person>),106
Meeting { guests: Vec<Person>, lobby: bool, organizer: bool },119
Meeting {120
guests: Vec<Person>,121
lobby: bool,122
organizer: bool,123
},107
Incoming(Person),124
Incoming(Person),108
}125
}109
126
@@ -121,7 +138,10 @@ pub fn demo_caller() -> Person {121
}138
}122
139
123
pub fn demo_video_ring() -> IncomingRing {140
pub fn demo_video_ring() -> IncomingRing {124
IncomingRing { video: true, ..demo_ring() }141
IncomingRing {142
video: true,143
..demo_ring()144
}125
}145
}126
146
127
pub fn demo_ring() -> IncomingRing {147
pub fn demo_ring() -> IncomingRing {@@ -146,15 +166,29 @@ fn device(index: u16, name: &str) -> AudioDevice {146
166
147
fn demo_cameras() -> Vec<CameraDevice> {167
fn demo_cameras() -> Vec<CameraDevice> {148
vec![168
vec![149
CameraDevice { key: "0".into(), name: "Integrated Camera".into() },169
CameraDevice {150
CameraDevice { key: "1".into(), name: "Studio Webcam".into() },170
key: "0".into(),171
name: "Integrated Camera".into(),172
},173
CameraDevice {174
key: "1".into(),175
name: "Studio Webcam".into(),176
},151
]177
]152
}178
}153
179
154
fn demo_share_sources() -> Vec<ShareSource> {180
fn demo_share_sources() -> Vec<ShareSource> {155
let window = |id: u64, title: &str| ShareSource { id, kind: ShareKind::Window, title: title.to_owned() };181
let window = |id: u64, title: &str| ShareSource {182
id,183
kind: ShareKind::Window,184
title: title.to_owned(),185
};156
vec![186
vec![157
ShareSource { id: 1, kind: ShareKind::Screen, title: String::new() },187
ShareSource {188
id: 1,189
kind: ShareKind::Screen,190
title: String::new(),191
},158
window(2, "Release notes - Docs"),192
window(2, "Release notes - Docs"),159
window(3, "Standup board"),193
window(3, "Standup board"),160
window(4, "Terminal"),194
window(4, "Terminal"),@@ -163,7 +197,10 @@ fn demo_share_sources() -> Vec<ShareSource> {163
197
164
fn demo_devices() -> DeviceLists {198
fn demo_devices() -> DeviceLists {165
DeviceLists {199
DeviceLists {166
inputs: vec![device(0, "Headset Microphone"), device(1, "Built-in Microphone")],200
inputs: vec![201
device(0, "Headset Microphone"),202
device(1, "Built-in Microphone"),203
],167
outputs: vec![device(0, "Headset"), device(1, "Speakers")],204
outputs: vec![device(0, "Headset"), device(1, "Speakers")],168
}205
}169
}206
}@@ -233,11 +270,24 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoSc233
}270
}234
let mut roster = roster_of(&people);271
let mut roster = roster_of(&people);235
if matches!(script, DemoCall::People(_)) {272
if matches!(script, DemoCall::People(_)) {236
control.send(CallUpdate::ReplacementLink(DEMO_REPLACEMENT_LINK.to_owned()));273
control.send(CallUpdate::ReplacementLink(274
DEMO_REPLACEMENT_LINK.to_owned(),275
));237
}276
}238
if matches!(script, DemoCall::Meeting { organizer: true, .. }) {277
if matches!(278
script,279
DemoCall::Meeting {280
organizer: true,281
..282
}283
) {239
roster.push(demo_organizer());284
roster.push(demo_organizer());240
roster.extend(DEMO_WAITING.iter().enumerate().map(|(index, name)| demo_waiting(index, name)));285
roster.extend(286
DEMO_WAITING287
.iter()288
.enumerate()289
.map(|(index, name)| demo_waiting(index, name)),290
);241
}291
}242
if matches!(script, DemoCall::Meeting { .. }) {292
if matches!(script, DemoCall::Meeting { .. }) {243
for (index, rank) in DEMO_FIRST_HANDS {293
for (index, rank) in DEMO_FIRST_HANDS {@@ -248,7 +298,9 @@ async fn run_demo_call(mut control: CallControl, script: DemoCall, scene: DemoSc248
}298
}249
control.send(CallUpdate::Roster(roster.clone()));299
control.send(CallUpdate::Roster(roster.clone()));250
let video = !matches!(script, DemoCall::Test);300
let video = !matches!(script, DemoCall::Test);251
let sharer = matches!(script, DemoCall::Meeting { .. }).then(|| people.get(1).map(|person| person.0.clone())).flatten();301
let sharer = matches!(script, DemoCall::Meeting { .. })302
.then(|| people.get(1).map(|person| person.0.clone()))303
.flatten();252
start_scene(&control, scene);304
start_scene(&control, scene);253
speak_until_hangup(control, people, roster, video, sharer, scene).await;305
speak_until_hangup(control, people, roster, video, sharer, scene).await;254
}306
}@@ -273,16 +325,31 @@ async fn ring_until_answered(control: &mut CallControl, script: &DemoCall) -> bo273
true325
true274
}326
}275
327
276
fn publish_demo_video(control: &CallControl, people: &[Person], tick: u32, sharing: bool, sharer: Option<&str>, camera: Option<bool>) {328
fn publish_demo_video(329
control: &CallControl,330
people: &[Person],331
tick: u32,332
sharing: bool,333
sharer: Option<&str>,334
camera: Option<bool>,335
) {277
if let Some(blur) = camera {336
if let Some(blur) = camera {278
control.video.publish(VideoKey::LocalCamera, self_view((tick + SELF_PHASE) as usize, blur));337
control.video.publish(338
VideoKey::LocalCamera,339
self_view((tick + SELF_PHASE) as usize, blur),340
);279
}341
}280
for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {342
for (index, (mri, _)) in people.iter().take(DEMO_CAMERAS).enumerate() {281
let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);343
let frame = pattern_frame(PatternKind::Camera, tick + index as u32 * GUEST_PHASE);282
control.video.publish(VideoKey::Person(mri.clone()), bgra_from_i420(frame));344
control345
.video346
.publish(VideoKey::Person(mri.clone()), bgra_from_i420(frame));283
}347
}284
if sharing && sharer.is_some() && tick.is_multiple_of(SCREEN_EVERY_TICKS) {348
if sharing && sharer.is_some() && tick.is_multiple_of(SCREEN_EVERY_TICKS) {285
control.video.publish(VideoKey::Screen, bgra_from_i420(pattern_frame(PatternKind::Screen, tick)));349
control.video.publish(350
VideoKey::Screen,351
bgra_from_i420(pattern_frame(PatternKind::Screen, tick)),352
);286
}353
}287
}354
}288
355
@@ -301,23 +368,39 @@ fn start_scene(control: &CallControl, scene: DemoScene) {301
368
302
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {369
fn scene_tick(control: &CallControl, scene: DemoScene, ticks: u32, people: &[Person]) {303
match scene {370
match scene {304
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => control.send(CallUpdate::BreakoutMove(BreakoutMove {371
DemoScene::Breakout if ticks == BREAKOUT_AT_TICKS => {305
room_name: "Room 1".to_owned(),372
control.send(CallUpdate::BreakoutMove(BreakoutMove {306
target: MeetingTarget { thread_id: DEMO_ROOM_THREAD.to_owned(), tenant_id: "demo-tenant".to_owned(), organizer_id: "demo-me".to_owned(), meeting_data: None },373
room_name: "Room 1".to_owned(),307
returning: false,374
target: MeetingTarget {308
})),375
thread_id: DEMO_ROOM_THREAD.to_owned(),309
DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => control.send(CallUpdate::Whiteboard(Some(ContentShare {376
tenant_id: "demo-tenant".to_owned(),310
session_id: "demo-whiteboard".to_owned(),377
organizer_id: "demo-me".to_owned(),311
presenter: people.first().map(|person| person.0.clone()),378
meeting_data: None,312
subject: "Whiteboard".to_owned(),379
},313
url: Some(DEMO_BOARD_URL.to_owned()),380
returning: false,314
whiteboard: true,381
}))315
}))),382
}383
DemoScene::Whiteboard if ticks == WHITEBOARD_AT_TICKS => {384
control.send(CallUpdate::Whiteboard(Some(ContentShare {385
session_id: "demo-whiteboard".to_owned(),386
presenter: people.first().map(|person| person.0.clone()),387
subject: "Whiteboard".to_owned(),388
url: Some(DEMO_BOARD_URL.to_owned()),389
whiteboard: true,390
})))391
}316
_ => {}392
_ => {}317
}393
}318
}394
}319
395
320
async fn speak_until_hangup(mut control: CallControl, people: Vec<Person>, mut roster: Vec<RosterEntry>, video: bool, sharer: Option<String>, scene: DemoScene) {396
async fn speak_until_hangup(397
mut control: CallControl,398
people: Vec<Person>,399
mut roster: Vec<RosterEntry>,400
video: bool,401
sharer: Option<String>,402
scene: DemoScene,403
) {321
let started = Instant::now();404
let started = Instant::now();322
let mut video_ticks = 0u32;405
let mut video_ticks = 0u32;323
let mut sharing = false;406
let mut sharing = false;@@ -497,7 +580,10 @@ fn demo_waiting(index: usize, name: &str) -> RosterEntry {497
}580
}498
581
499
fn demo_spotlight(rank: u64) -> PublishedState {582
fn demo_spotlight(rank: u64) -> PublishedState {500
PublishedState { state_id: format!("demo-spotlight-{rank}"), rank }583
PublishedState {584
state_id: format!("demo-spotlight-{rank}"),585
rank,586
}501
}587
}502
588
503
fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {589
fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {@@ -517,11 +603,19 @@ fn demo_caption(people: &[Person], tick: usize) -> Option<CaptionEntry> {517
}603
}518
604
519
fn demo_hand(rank: u64) -> RaisedHand {605
fn demo_hand(rank: u64) -> RaisedHand {520
RaisedHand { state_id: format!("demo-hand-{rank}"), rank }606
RaisedHand {607
state_id: format!("demo-hand-{rank}"),608
rank,609
}521
}610
}522
611
523
fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {612
fn set_demo_hand(roster: &mut Vec<RosterEntry>, mri: &str, raised: bool) {524
let next_rank = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).max().unwrap_or(0) + 1;613
let next_rank = roster614
.iter()615
.filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))616
.max()617
.unwrap_or(0)618
+ 1;525
if !raised {619
if !raised {526
if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {620
if let Some(entry) = roster.iter_mut().find(|entry| entry.mri == mri) {527
entry.hand = None;621
entry.hand = None;@@ -568,7 +662,10 @@ mod tests {568
let mut roster = roster_of(&demo_guests(3));662
let mut roster = roster_of(&demo_guests(3));569
set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);663
set_demo_hand(&mut roster, "8:orgid:demo-guest-1", true);570
set_demo_hand(&mut roster, DEMO_OWN_MRI, true);664
set_demo_hand(&mut roster, DEMO_OWN_MRI, true);571
let ranks: Vec<u64> = roster.iter().filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank)).collect();665
let ranks: Vec<u64> = roster666
.iter()667
.filter_map(|entry| entry.hand.as_ref().map(|hand| hand.rank))668
.collect();572
assert_eq!(ranks, vec![1, 2]);669
assert_eq!(ranks, vec![1, 2]);573
set_demo_hand(&mut roster, DEMO_OWN_MRI, false);670
set_demo_hand(&mut roster, DEMO_OWN_MRI, false);574
assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));671
assert!(roster.iter().all(|entry| entry.mri != DEMO_OWN_MRI));@@ -27,14 +27,21 @@ fn person_at(x: f32, y: f32) -> Option<[u8; 3]> {
27
27
fn background_at(column: usize, row: usize, tick: usize) -> [u8; 3] {
28
28
let stripe = ((column + tick) / STRIPE + row / STRIPE).is_multiple_of(2);
29
29
let shade = (row * 60 / SCENE_HEIGHT) as u8;
30
if stripe { [214 - shade, 120 + shade, 60] } else { [48, 150 - shade, 168 + shade / 2] }
30
if stripe {
31
[214 - shade, 120 + shade, 60]
32
} else {
33
[48, 150 - shade, 168 + shade / 2]
34
}
31
35
}
32
36
33
37
fn scene(tick: usize) -> Vec<u8> {
34
38
let mut rgba = vec![255u8; SCENE_WIDTH * SCENE_HEIGHT * 4];
35
39
for row in 0..SCENE_HEIGHT {
36
40
for column in 0..SCENE_WIDTH {
37
let (x, y) = ((column as f32 + 0.5) / SCENE_WIDTH as f32, (row as f32 + 0.5) / SCENE_HEIGHT as f32);
41
let (x, y) = (
42
(column as f32 + 0.5) / SCENE_WIDTH as f32,
43
(row as f32 + 0.5) / SCENE_HEIGHT as f32,
44
);
38
45
let color = person_at(x, y).unwrap_or_else(|| background_at(column, row, tick));
39
46
rgba[(row * SCENE_WIDTH + column) * 4..][..3].copy_from_slice(&color);
40
47
}
@@ -45,7 +52,10 @@ fn scene(tick: usize) -> Vec<u8> {
45
52
fn person_mask() -> Vec<f32> {
46
53
(0..MASK_WIDTH * MASK_HEIGHT)
47
54
.map(|index| {
48
let (x, y) = (((index % MASK_WIDTH) as f32 + 0.5) / MASK_WIDTH as f32, ((index / MASK_WIDTH) as f32 + 0.5) / MASK_HEIGHT as f32);
55
let (x, y) = (
56
((index % MASK_WIDTH) as f32 + 0.5) / MASK_WIDTH as f32,
57
((index / MASK_WIDTH) as f32 + 0.5) / MASK_HEIGHT as f32,
58
);
49
59
if person_at(x, y).is_some() { 1. } else { 0. }
50
60
})
51
61
.collect()
@@ -57,8 +67,17 @@ pub fn self_view(tick: usize, blur: bool) -> VideoPicture {
57
67
if blur {
58
68
compose(&mut rgba, SCENE_WIDTH, SCENE_HEIGHT, &person_mask());
59
69
}
60
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|pixel| [pixel[2], pixel[1], pixel[0], pixel[3]]).collect();
61
VideoPicture { width: SCENE_WIDTH as u32, height: SCENE_HEIGHT as u32, bgra }
70
let bgra = rgba
71
.as_chunks::<4>()
72
.0
73
.iter()
74
.flat_map(|pixel| [pixel[2], pixel[1], pixel[0], pixel[3]])
75
.collect();
76
VideoPicture {
77
width: SCENE_WIDTH as u32,
78
height: SCENE_HEIGHT as u32,
79
bgra,
80
}
62
81
}
63
82
64
83
#[cfg(test)]
@@ -67,7 +86,9 @@ mod tests {
67
86
68
87
fn roughness(picture: &VideoPicture, x: usize, y: usize) -> i32 {
69
88
let at = |column: usize| i32::from(picture.bgra[(y * SCENE_WIDTH + column) * 4]);
70
(0..12).map(|step| (at(x + step + 1) - at(x + step)).abs()).sum()
89
(0..12)
90
.map(|step| (at(x + step + 1) - at(x + step)).abs())
91
.sum()
71
92
}
72
93
73
94
#[test]
@@ -76,6 +97,9 @@ mod tests {
76
97
let blurred = self_view(0, true);
77
98
assert!(roughness(&blurred, 30, 20) * 3 < roughness(&sharp, 30, 20));
78
99
let center = (SCENE_HEIGHT / 2 * SCENE_WIDTH + SCENE_WIDTH / 2) * 4;
79
assert_eq!(blurred.bgra[center..center + 3], sharp.bgra[center..center + 3]);
100
assert_eq!(
101
blurred.bgra[center..center + 3],
102
sharp.bgra[center..center + 3]
103
);
80
104
}
81
105
}
@@ -27,14 +27,21 @@ fn person_at(x: f32, y: f32) -> Option<[u8; 3]> {27
fn background_at(column: usize, row: usize, tick: usize) -> [u8; 3] {27
fn background_at(column: usize, row: usize, tick: usize) -> [u8; 3] {28
let stripe = ((column + tick) / STRIPE + row / STRIPE).is_multiple_of(2);28
let stripe = ((column + tick) / STRIPE + row / STRIPE).is_multiple_of(2);29
let shade = (row * 60 / SCENE_HEIGHT) as u8;29
let shade = (row * 60 / SCENE_HEIGHT) as u8;30
if stripe { [214 - shade, 120 + shade, 60] } else { [48, 150 - shade, 168 + shade / 2] }30
if stripe {31
[214 - shade, 120 + shade, 60]32
} else {33
[48, 150 - shade, 168 + shade / 2]34
}31
}35
}32
36
33
fn scene(tick: usize) -> Vec<u8> {37
fn scene(tick: usize) -> Vec<u8> {34
let mut rgba = vec![255u8; SCENE_WIDTH * SCENE_HEIGHT * 4];38
let mut rgba = vec![255u8; SCENE_WIDTH * SCENE_HEIGHT * 4];35
for row in 0..SCENE_HEIGHT {39
for row in 0..SCENE_HEIGHT {36
for column in 0..SCENE_WIDTH {40
for column in 0..SCENE_WIDTH {37
let (x, y) = ((column as f32 + 0.5) / SCENE_WIDTH as f32, (row as f32 + 0.5) / SCENE_HEIGHT as f32);41
let (x, y) = (42
(column as f32 + 0.5) / SCENE_WIDTH as f32,43
(row as f32 + 0.5) / SCENE_HEIGHT as f32,44
);38
let color = person_at(x, y).unwrap_or_else(|| background_at(column, row, tick));45
let color = person_at(x, y).unwrap_or_else(|| background_at(column, row, tick));39
rgba[(row * SCENE_WIDTH + column) * 4..][..3].copy_from_slice(&color);46
rgba[(row * SCENE_WIDTH + column) * 4..][..3].copy_from_slice(&color);40
}47
}@@ -45,7 +52,10 @@ fn scene(tick: usize) -> Vec<u8> {45
fn person_mask() -> Vec<f32> {52
fn person_mask() -> Vec<f32> {46
(0..MASK_WIDTH * MASK_HEIGHT)53
(0..MASK_WIDTH * MASK_HEIGHT)47
.map(|index| {54
.map(|index| {48
let (x, y) = (((index % MASK_WIDTH) as f32 + 0.5) / MASK_WIDTH as f32, ((index / MASK_WIDTH) as f32 + 0.5) / MASK_HEIGHT as f32);55
let (x, y) = (56
((index % MASK_WIDTH) as f32 + 0.5) / MASK_WIDTH as f32,57
((index / MASK_WIDTH) as f32 + 0.5) / MASK_HEIGHT as f32,58
);49
if person_at(x, y).is_some() { 1. } else { 0. }59
if person_at(x, y).is_some() { 1. } else { 0. }50
})60
})51
.collect()61
.collect()@@ -57,8 +67,17 @@ pub fn self_view(tick: usize, blur: bool) -> VideoPicture {57
if blur {67
if blur {58
compose(&mut rgba, SCENE_WIDTH, SCENE_HEIGHT, &person_mask());68
compose(&mut rgba, SCENE_WIDTH, SCENE_HEIGHT, &person_mask());59
}69
}60
let bgra = rgba.as_chunks::<4>().0.iter().flat_map(|pixel| [pixel[2], pixel[1], pixel[0], pixel[3]]).collect();70
let bgra = rgba61
VideoPicture { width: SCENE_WIDTH as u32, height: SCENE_HEIGHT as u32, bgra }71
.as_chunks::<4>()72
.073
.iter()74
.flat_map(|pixel| [pixel[2], pixel[1], pixel[0], pixel[3]])75
.collect();76
VideoPicture {77
width: SCENE_WIDTH as u32,78
height: SCENE_HEIGHT as u32,79
bgra,80
}62
}81
}63
82
64
#[cfg(test)]83
#[cfg(test)]@@ -67,7 +86,9 @@ mod tests {67
86
68
fn roughness(picture: &VideoPicture, x: usize, y: usize) -> i32 {87
fn roughness(picture: &VideoPicture, x: usize, y: usize) -> i32 {69
let at = |column: usize| i32::from(picture.bgra[(y * SCENE_WIDTH + column) * 4]);88
let at = |column: usize| i32::from(picture.bgra[(y * SCENE_WIDTH + column) * 4]);70
(0..12).map(|step| (at(x + step + 1) - at(x + step)).abs()).sum()89
(0..12)90
.map(|step| (at(x + step + 1) - at(x + step)).abs())91
.sum()71
}92
}72
93
73
#[test]94
#[test]@@ -76,6 +97,9 @@ mod tests {76
let blurred = self_view(0, true);97
let blurred = self_view(0, true);77
assert!(roughness(&blurred, 30, 20) * 3 < roughness(&sharp, 30, 20));98
assert!(roughness(&blurred, 30, 20) * 3 < roughness(&sharp, 30, 20));78
let center = (SCENE_HEIGHT / 2 * SCENE_WIDTH + SCENE_WIDTH / 2) * 4;99
let center = (SCENE_HEIGHT / 2 * SCENE_WIDTH + SCENE_WIDTH / 2) * 4;79
assert_eq!(blurred.bgra[center..center + 3], sharp.bgra[center..center + 3]);100
assert_eq!(101
blurred.bgra[center..center + 3],102
sharp.bgra[center..center + 3]103
);80
}104
}81
}105
}@@ -1,4 +1,6 @@
1
use calling::{CallCommand, CallHandle, CallSpec, CallState, Callee, EndKind, EndReason, HoldState};
1
use calling::{
2
CallCommand, CallHandle, CallSpec, CallState, Callee, EndKind, EndReason, HoldState,
3
};
2
4
use gpui_kit::*;
3
5
4
6
use super::demo::{DemoCall, start_demo_call};
@@ -26,7 +28,11 @@ pub fn room_closed_move(call: &ActiveCall, reason: &EndReason) -> Option<Pending
26
28
}
27
29
28
30
fn return_move(room: &BreakoutState) -> PendingMove {
29
PendingMove { target: room.main.clone().expect("a room with a way back"), title: room.main_title.clone(), breakout: None }
31
PendingMove {
32
target: room.main.clone().expect("a room with a way back"),
33
title: room.main_title.clone(),
34
breakout: None,
35
}
30
36
}
31
37
32
38
impl AppState {
@@ -39,7 +45,11 @@ impl AppState {
39
45
}
40
46
41
47
pub fn accept_recording_notice(&mut self, _cx: &mut Context<Self>) {
42
if self.call.as_ref().is_some_and(|call| call.model.consent_required) {
48
if self
49
.call
50
.as_ref()
51
.is_some_and(|call| call.model.consent_required)
52
{
43
53
self.send_call_command(CallCommand::ConsentToRecording);
44
54
}
45
55
}
@@ -57,7 +67,11 @@ impl AppState {
57
67
}
58
68
59
69
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {
60
let Some(call) = self.call.as_ref().filter(|call| call.model.can_open_whiteboard()) else {
70
let Some(call) = self
71
.call
72
.as_ref()
73
.filter(|call| call.model.can_open_whiteboard())
74
else {
61
75
return;
62
76
};
63
77
if let Some(url) = call.model.whiteboard_url() {
@@ -69,7 +83,10 @@ impl AppState {
69
83
}
70
84
71
85
pub fn transfer_candidates(&self) -> Vec<TransferCandidate> {
72
let peer = self.call.as_ref().and_then(|call| call.model.tiles.first().map(|tile| tile.mri.clone()));
86
let peer = self
87
.call
88
.as_ref()
89
.and_then(|call| call.model.tiles.first().map(|tile| tile.mri.clone()));
73
90
self.sidebar
74
91
.chats
75
92
.iter()
@@ -77,17 +94,28 @@ impl AppState {
77
94
.filter_map(|chat| {
78
95
let plan = plan_for_chat(chat, self.directory.me.as_ref())?;
79
96
let (mri, name) = plan.callees.into_iter().next()?;
80
Some(TransferCandidate { user_id: mri.strip_prefix("8:orgid:").map(str::to_owned), mri, name, chat_id: chat.id.clone() })
97
Some(TransferCandidate {
98
user_id: mri.strip_prefix("8:orgid:").map(str::to_owned),
99
mri,
100
name,
101
chat_id: chat.id.clone(),
102
})
81
103
})
82
104
.filter(|candidate| Some(&candidate.mri) != peer.as_ref())
83
105
.collect()
84
106
}
85
107
86
108
pub fn can_transfer_call(&self) -> bool {
87
self.call.as_ref().is_some_and(|call| call.model.can_transfer() && call.consult.is_none())
109
self.call
110
.as_ref()
111
.is_some_and(|call| call.model.can_transfer() && call.consult.is_none())
88
112
}
89
113
90
pub fn open_transfer_picker(&mut self, picker: Entity<crate::views::transfer_picker::TransferPicker>, cx: &mut Context<Self>) {
114
pub fn open_transfer_picker(
115
&mut self,
116
picker: Entity<crate::views::transfer_picker::TransferPicker>,
117
cx: &mut Context<Self>,
118
) {
91
119
if self.can_transfer_call() {
92
120
self.transfer_picker = Some(picker);
93
121
cx.notify();
@@ -105,8 +133,14 @@ impl AppState {
105
133
if !self.can_transfer_call() {
106
134
return;
107
135
}
108
let callee = Callee { mri: target.mri, display_name: target.name };
109
self.send_call_command(CallCommand::Transfer { target: callee, replaces: None });
136
let callee = Callee {
137
mri: target.mri,
138
display_name: target.name,
139
};
140
self.send_call_command(CallCommand::Transfer {
141
target: callee,
142
replaces: None,
143
});
110
144
}
111
145
112
146
pub fn start_consult(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {
@@ -115,15 +149,26 @@ impl AppState {
115
149
return;
116
150
}
117
151
let spec = CallSpec::People {
118
callees: vec![Callee { mri: target.mri.clone(), display_name: target.name.clone() }],
152
callees: vec![Callee {
153
mri: target.mri.clone(),
154
display_name: target.name.clone(),
155
}],
119
156
thread_id: target.chat_id.clone(),
120
157
};
121
158
let handle = if self.mode.demo {
122
Some(start_demo_call(DemoCall::People(vec![(target.mri.clone(), target.name.clone())])))
159
Some(start_demo_call(DemoCall::People(vec![(
160
target.mri.clone(),
161
target.name.clone(),
162
)])))
123
163
} else {
124
self.call_launcher.clone().map(|launcher| launcher.start_consult(spec))
164
self.call_launcher
165
.clone()
166
.map(|launcher| launcher.start_consult(spec))
125
167
};
126
let Some(CallHandle { commands, updates, .. }) = handle else {
168
let Some(CallHandle {
169
commands, updates, ..
170
}) = handle
171
else {
127
172
self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);
128
173
return;
129
174
};
@@ -146,10 +191,21 @@ impl AppState {
146
191
cx.notify();
147
192
}
148
193
149
fn follow_consult(&mut self, call_id: u64, consult_id: u64, mut updates: tokio::sync::mpsc::UnboundedReceiver<calling::CallUpdate>, cx: &mut Context<Self>) {
194
fn follow_consult(
195
&mut self,
196
call_id: u64,
197
consult_id: u64,
198
mut updates: tokio::sync::mpsc::UnboundedReceiver<calling::CallUpdate>,
199
cx: &mut Context<Self>,
200
) {
150
201
cx.spawn(async move |this, cx| {
151
202
while let Some(update) = updates.recv().await {
152
if this.update(cx, |state, cx| state.apply_consult_update(call_id, consult_id, update, cx)).is_err() {
203
if this
204
.update(cx, |state, cx| {
205
state.apply_consult_update(call_id, consult_id, update, cx)
206
})
207
.is_err()
208
{
153
209
return;
154
210
}
155
211
}
@@ -157,11 +213,21 @@ impl AppState {
157
213
.detach();
158
214
}
159
215
160
pub(super) fn apply_consult_update(&mut self, call_id: u64, consult_id: u64, update: calling::CallUpdate, cx: &mut Context<Self>) {
216
pub(super) fn apply_consult_update(
217
&mut self,
218
call_id: u64,
219
consult_id: u64,
220
update: calling::CallUpdate,
221
cx: &mut Context<Self>,
222
) {
161
223
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
162
224
return;
163
225
};
164
let Some(consult) = call.consult.as_mut().filter(|consult| consult.id == consult_id) else {
226
let Some(consult) = call
227
.consult
228
.as_mut()
229
.filter(|consult| consult.id == consult_id)
230
else {
165
231
return;
166
232
};
167
233
match update {
@@ -185,13 +251,24 @@ impl AppState {
185
251
}
186
252
187
253
pub fn transfer_consulted(&mut self, _cx: &mut Context<Self>) {
188
let Some(consult) = self.call.as_mut().and_then(|call| call.consult.as_mut()).filter(|consult| consult.ready_to_transfer()) else {
254
let Some(consult) = self
255
.call
256
.as_mut()
257
.and_then(|call| call.consult.as_mut())
258
.filter(|consult| consult.ready_to_transfer())
259
else {
189
260
return;
190
261
};
191
262
consult.transferring = true;
192
263
let (mri, name) = consult.target.clone();
193
264
let replaces = consult.replacement.clone();
194
self.send_call_command(CallCommand::Transfer { target: Callee { mri, display_name: name }, replaces });
265
self.send_call_command(CallCommand::Transfer {
266
target: Callee {
267
mri,
268
display_name: name,
269
},
270
replaces,
271
});
195
272
}
196
273
197
274
pub fn cancel_consult(&mut self, _cx: &mut Context<Self>) {
@@ -200,31 +277,69 @@ impl AppState {
200
277
}
201
278
}
202
279
203
pub(super) fn begin_breakout_move(&mut self, moved: calling::BreakoutMove, cx: &mut Context<Self>) {
204
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {
280
pub(super) fn begin_breakout_move(
281
&mut self,
282
moved: calling::BreakoutMove,
283
cx: &mut Context<Self>,
284
) {
285
let Some(call) = self
286
.call
287
.as_mut()
288
.filter(|call| call.pending_move.is_none())
289
else {
205
290
return;
206
291
};
207
292
let (main, main_title) = match &call.model.breakout {
208
Some(room) => (room.main.clone().or_else(|| call.model.main_meeting.clone()), room.main_title.clone()),
293
Some(room) => (
294
room.main
295
.clone()
296
.or_else(|| call.model.main_meeting.clone()),
297
room.main_title.clone(),
298
),
209
299
None => (call.meeting_target.clone(), call.model.title.clone()),
210
300
};
211
301
let pending = if moved.returning {
212
PendingMove { target: moved.target, title: main_title, breakout: None }
302
PendingMove {
303
target: moved.target,
304
title: main_title,
305
breakout: None,
306
}
213
307
} else {
214
let breakout = BreakoutState { room_name: moved.room_name.clone(), main, main_title };
215
PendingMove { target: moved.target, title: moved.room_name.clone(), breakout: Some(breakout) }
308
let breakout = BreakoutState {
309
room_name: moved.room_name.clone(),
310
main,
311
main_title,
312
};
313
PendingMove {
314
target: moved.target,
315
title: moved.room_name.clone(),
316
breakout: Some(breakout),
317
}
318
};
319
let notice = if moved.returning {
320
"Moving you back to the main meeting".to_owned()
321
} else {
322
format!("Moving you to {}", moved.room_name)
216
323
};
217
let notice = if moved.returning { "Moving you back to the main meeting".to_owned() } else { format!("Moving you to {}", moved.room_name) };
218
324
call.pending_move = Some(pending);
219
325
self.raise_notice(notice, None, cx);
220
326
self.send_call_command(CallCommand::Hangup);
221
327
}
222
328
223
329
pub fn return_to_main_meeting(&mut self, _cx: &mut Context<Self>) {
224
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {
330
let Some(call) = self
331
.call
332
.as_mut()
333
.filter(|call| call.pending_move.is_none())
334
else {
225
335
return;
226
336
};
227
let Some(room) = call.model.breakout.as_ref().filter(|room| room.main.is_some()) else {
337
let Some(room) = call
338
.model
339
.breakout
340
.as_ref()
341
.filter(|room| room.main.is_some())
342
else {
228
343
return;
229
344
};
230
345
call.pending_move = Some(return_move(room));
@@ -232,8 +347,13 @@ impl AppState {
232
347
}
233
348
234
349
pub(super) fn join_moved_call(&mut self, moved: PendingMove, cx: &mut Context<Self>) {
235
let demo = DemoCall::Meeting { guests: super::demo::demo_guests(DEMO_ROOM_GUESTS), lobby: false, organizer: false };
236
let Some(handle) = self.place_call(CallSpec::Meeting(moved.target.clone()), demo, cx) else {
350
let demo = DemoCall::Meeting {
351
guests: super::demo::demo_guests(DEMO_ROOM_GUESTS),
352
lobby: false,
353
organizer: false,
354
};
355
let Some(handle) = self.place_call(CallSpec::Meeting(moved.target.clone()), demo, cx)
356
else {
237
357
return;
238
358
};
239
359
let mut model = CallModel::meeting(&moved.title, false);
@@ -1,4 +1,6 @@1
use calling::{CallCommand, CallHandle, CallSpec, CallState, Callee, EndKind, EndReason, HoldState};1
use calling::{2
CallCommand, CallHandle, CallSpec, CallState, Callee, EndKind, EndReason, HoldState,3
};2
use gpui_kit::*;4
use gpui_kit::*;3
5
4
use super::demo::{DemoCall, start_demo_call};6
use super::demo::{DemoCall, start_demo_call};@@ -26,7 +28,11 @@ pub fn room_closed_move(call: &ActiveCall, reason: &EndReason) -> Option<Pending26
}28
}27
29
28
fn return_move(room: &BreakoutState) -> PendingMove {30
fn return_move(room: &BreakoutState) -> PendingMove {29
PendingMove { target: room.main.clone().expect("a room with a way back"), title: room.main_title.clone(), breakout: None }31
PendingMove {32
target: room.main.clone().expect("a room with a way back"),33
title: room.main_title.clone(),34
breakout: None,35
}30
}36
}31
37
32
impl AppState {38
impl AppState {@@ -39,7 +45,11 @@ impl AppState {39
}45
}40
46
41
pub fn accept_recording_notice(&mut self, _cx: &mut Context<Self>) {47
pub fn accept_recording_notice(&mut self, _cx: &mut Context<Self>) {42
if self.call.as_ref().is_some_and(|call| call.model.consent_required) {48
if self49
.call50
.as_ref()51
.is_some_and(|call| call.model.consent_required)52
{43
self.send_call_command(CallCommand::ConsentToRecording);53
self.send_call_command(CallCommand::ConsentToRecording);44
}54
}45
}55
}@@ -57,7 +67,11 @@ impl AppState {57
}67
}58
68
59
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {69
pub fn open_call_whiteboard(&mut self, cx: &mut Context<Self>) {60
let Some(call) = self.call.as_ref().filter(|call| call.model.can_open_whiteboard()) else {70
let Some(call) = self71
.call72
.as_ref()73
.filter(|call| call.model.can_open_whiteboard())74
else {61
return;75
return;62
};76
};63
if let Some(url) = call.model.whiteboard_url() {77
if let Some(url) = call.model.whiteboard_url() {@@ -69,7 +83,10 @@ impl AppState {69
}83
}70
84
71
pub fn transfer_candidates(&self) -> Vec<TransferCandidate> {85
pub fn transfer_candidates(&self) -> Vec<TransferCandidate> {72
let peer = self.call.as_ref().and_then(|call| call.model.tiles.first().map(|tile| tile.mri.clone()));86
let peer = self87
.call88
.as_ref()89
.and_then(|call| call.model.tiles.first().map(|tile| tile.mri.clone()));73
self.sidebar90
self.sidebar74
.chats91
.chats75
.iter()92
.iter()@@ -77,17 +94,28 @@ impl AppState {77
.filter_map(|chat| {94
.filter_map(|chat| {78
let plan = plan_for_chat(chat, self.directory.me.as_ref())?;95
let plan = plan_for_chat(chat, self.directory.me.as_ref())?;79
let (mri, name) = plan.callees.into_iter().next()?;96
let (mri, name) = plan.callees.into_iter().next()?;80
Some(TransferCandidate { user_id: mri.strip_prefix("8:orgid:").map(str::to_owned), mri, name, chat_id: chat.id.clone() })97
Some(TransferCandidate {98
user_id: mri.strip_prefix("8:orgid:").map(str::to_owned),99
mri,100
name,101
chat_id: chat.id.clone(),102
})81
})103
})82
.filter(|candidate| Some(&candidate.mri) != peer.as_ref())104
.filter(|candidate| Some(&candidate.mri) != peer.as_ref())83
.collect()105
.collect()84
}106
}85
107
86
pub fn can_transfer_call(&self) -> bool {108
pub fn can_transfer_call(&self) -> bool {87
self.call.as_ref().is_some_and(|call| call.model.can_transfer() && call.consult.is_none())109
self.call110
.as_ref()111
.is_some_and(|call| call.model.can_transfer() && call.consult.is_none())88
}112
}89
113
90
pub fn open_transfer_picker(&mut self, picker: Entity<crate::views::transfer_picker::TransferPicker>, cx: &mut Context<Self>) {114
pub fn open_transfer_picker(115
&mut self,116
picker: Entity<crate::views::transfer_picker::TransferPicker>,117
cx: &mut Context<Self>,118
) {91
if self.can_transfer_call() {119
if self.can_transfer_call() {92
self.transfer_picker = Some(picker);120
self.transfer_picker = Some(picker);93
cx.notify();121
cx.notify();@@ -105,8 +133,14 @@ impl AppState {105
if !self.can_transfer_call() {133
if !self.can_transfer_call() {106
return;134
return;107
}135
}108
let callee = Callee { mri: target.mri, display_name: target.name };136
let callee = Callee {109
self.send_call_command(CallCommand::Transfer { target: callee, replaces: None });137
mri: target.mri,138
display_name: target.name,139
};140
self.send_call_command(CallCommand::Transfer {141
target: callee,142
replaces: None,143
});110
}144
}111
145
112
pub fn start_consult(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {146
pub fn start_consult(&mut self, target: TransferCandidate, cx: &mut Context<Self>) {@@ -115,15 +149,26 @@ impl AppState {115
return;149
return;116
}150
}117
let spec = CallSpec::People {151
let spec = CallSpec::People {118
callees: vec![Callee { mri: target.mri.clone(), display_name: target.name.clone() }],152
callees: vec![Callee {153
mri: target.mri.clone(),154
display_name: target.name.clone(),155
}],119
thread_id: target.chat_id.clone(),156
thread_id: target.chat_id.clone(),120
};157
};121
let handle = if self.mode.demo {158
let handle = if self.mode.demo {122
Some(start_demo_call(DemoCall::People(vec![(target.mri.clone(), target.name.clone())])))159
Some(start_demo_call(DemoCall::People(vec![(160
target.mri.clone(),161
target.name.clone(),162
)])))123
} else {163
} else {124
self.call_launcher.clone().map(|launcher| launcher.start_consult(spec))164
self.call_launcher165
.clone()166
.map(|launcher| launcher.start_consult(spec))125
};167
};126
let Some(CallHandle { commands, updates, .. }) = handle else {168
let Some(CallHandle {169
commands, updates, ..170
}) = handle171
else {127
self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);172
self.raise_notice("Not connected to Teams yet".to_owned(), None, cx);128
return;173
return;129
};174
};@@ -146,10 +191,21 @@ impl AppState {146
cx.notify();191
cx.notify();147
}192
}148
193
149
fn follow_consult(&mut self, call_id: u64, consult_id: u64, mut updates: tokio::sync::mpsc::UnboundedReceiver<calling::CallUpdate>, cx: &mut Context<Self>) {194
fn follow_consult(195
&mut self,196
call_id: u64,197
consult_id: u64,198
mut updates: tokio::sync::mpsc::UnboundedReceiver<calling::CallUpdate>,199
cx: &mut Context<Self>,200
) {150
cx.spawn(async move |this, cx| {201
cx.spawn(async move |this, cx| {151
while let Some(update) = updates.recv().await {202
while let Some(update) = updates.recv().await {152
if this.update(cx, |state, cx| state.apply_consult_update(call_id, consult_id, update, cx)).is_err() {203
if this204
.update(cx, |state, cx| {205
state.apply_consult_update(call_id, consult_id, update, cx)206
})207
.is_err()208
{153
return;209
return;154
}210
}155
}211
}@@ -157,11 +213,21 @@ impl AppState {157
.detach();213
.detach();158
}214
}159
215
160
pub(super) fn apply_consult_update(&mut self, call_id: u64, consult_id: u64, update: calling::CallUpdate, cx: &mut Context<Self>) {216
pub(super) fn apply_consult_update(217
&mut self,218
call_id: u64,219
consult_id: u64,220
update: calling::CallUpdate,221
cx: &mut Context<Self>,222
) {161
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {223
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {162
return;224
return;163
};225
};164
let Some(consult) = call.consult.as_mut().filter(|consult| consult.id == consult_id) else {226
let Some(consult) = call227
.consult228
.as_mut()229
.filter(|consult| consult.id == consult_id)230
else {165
return;231
return;166
};232
};167
match update {233
match update {@@ -185,13 +251,24 @@ impl AppState {185
}251
}186
252
187
pub fn transfer_consulted(&mut self, _cx: &mut Context<Self>) {253
pub fn transfer_consulted(&mut self, _cx: &mut Context<Self>) {188
let Some(consult) = self.call.as_mut().and_then(|call| call.consult.as_mut()).filter(|consult| consult.ready_to_transfer()) else {254
let Some(consult) = self255
.call256
.as_mut()257
.and_then(|call| call.consult.as_mut())258
.filter(|consult| consult.ready_to_transfer())259
else {189
return;260
return;190
};261
};191
consult.transferring = true;262
consult.transferring = true;192
let (mri, name) = consult.target.clone();263
let (mri, name) = consult.target.clone();193
let replaces = consult.replacement.clone();264
let replaces = consult.replacement.clone();194
self.send_call_command(CallCommand::Transfer { target: Callee { mri, display_name: name }, replaces });265
self.send_call_command(CallCommand::Transfer {266
target: Callee {267
mri,268
display_name: name,269
},270
replaces,271
});195
}272
}196
273
197
pub fn cancel_consult(&mut self, _cx: &mut Context<Self>) {274
pub fn cancel_consult(&mut self, _cx: &mut Context<Self>) {@@ -200,31 +277,69 @@ impl AppState {200
}277
}201
}278
}202
279
203
pub(super) fn begin_breakout_move(&mut self, moved: calling::BreakoutMove, cx: &mut Context<Self>) {280
pub(super) fn begin_breakout_move(204
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {281
&mut self,282
moved: calling::BreakoutMove,283
cx: &mut Context<Self>,284
) {285
let Some(call) = self286
.call287
.as_mut()288
.filter(|call| call.pending_move.is_none())289
else {205
return;290
return;206
};291
};207
let (main, main_title) = match &call.model.breakout {292
let (main, main_title) = match &call.model.breakout {208
Some(room) => (room.main.clone().or_else(|| call.model.main_meeting.clone()), room.main_title.clone()),293
Some(room) => (294
room.main295
.clone()296
.or_else(|| call.model.main_meeting.clone()),297
room.main_title.clone(),298
),209
None => (call.meeting_target.clone(), call.model.title.clone()),299
None => (call.meeting_target.clone(), call.model.title.clone()),210
};300
};211
let pending = if moved.returning {301
let pending = if moved.returning {212
PendingMove { target: moved.target, title: main_title, breakout: None }302
PendingMove {303
target: moved.target,304
title: main_title,305
breakout: None,306
}213
} else {307
} else {214
let breakout = BreakoutState { room_name: moved.room_name.clone(), main, main_title };308
let breakout = BreakoutState {215
PendingMove { target: moved.target, title: moved.room_name.clone(), breakout: Some(breakout) }309
room_name: moved.room_name.clone(),310
main,311
main_title,312
};313
PendingMove {314
target: moved.target,315
title: moved.room_name.clone(),316
breakout: Some(breakout),317
}318
};319
let notice = if moved.returning {320
"Moving you back to the main meeting".to_owned()321
} else {322
format!("Moving you to {}", moved.room_name)216
};323
};217
let notice = if moved.returning { "Moving you back to the main meeting".to_owned() } else { format!("Moving you to {}", moved.room_name) };218
call.pending_move = Some(pending);324
call.pending_move = Some(pending);219
self.raise_notice(notice, None, cx);325
self.raise_notice(notice, None, cx);220
self.send_call_command(CallCommand::Hangup);326
self.send_call_command(CallCommand::Hangup);221
}327
}222
328
223
pub fn return_to_main_meeting(&mut self, _cx: &mut Context<Self>) {329
pub fn return_to_main_meeting(&mut self, _cx: &mut Context<Self>) {224
let Some(call) = self.call.as_mut().filter(|call| call.pending_move.is_none()) else {330
let Some(call) = self331
.call332
.as_mut()333
.filter(|call| call.pending_move.is_none())334
else {225
return;335
return;226
};336
};227
let Some(room) = call.model.breakout.as_ref().filter(|room| room.main.is_some()) else {337
let Some(room) = call338
.model339
.breakout340
.as_ref()341
.filter(|room| room.main.is_some())342
else {228
return;343
return;229
};344
};230
call.pending_move = Some(return_move(room));345
call.pending_move = Some(return_move(room));@@ -232,8 +347,13 @@ impl AppState {232
}347
}233
348
234
pub(super) fn join_moved_call(&mut self, moved: PendingMove, cx: &mut Context<Self>) {349
pub(super) fn join_moved_call(&mut self, moved: PendingMove, cx: &mut Context<Self>) {235
let demo = DemoCall::Meeting { guests: super::demo::demo_guests(DEMO_ROOM_GUESTS), lobby: false, organizer: false };350
let demo = DemoCall::Meeting {236
let Some(handle) = self.place_call(CallSpec::Meeting(moved.target.clone()), demo, cx) else {351
guests: super::demo::demo_guests(DEMO_ROOM_GUESTS),352
lobby: false,353
organizer: false,354
};355
let Some(handle) = self.place_call(CallSpec::Meeting(moved.target.clone()), demo, cx)356
else {237
return;357
return;238
};358
};239
let mut model = CallModel::meeting(&moved.title, false);359
let mut model = CallModel::meeting(&moved.title, false);@@ -237,7 +237,10 @@ impl AppState {
237
237
})
238
238
.ok();
239
239
}
240
Ok(Err(error)) => crate::diagnostics::record(format!("calls: history not loaded: {}", short_error(&error))),
240
Ok(Err(error)) => crate::diagnostics::record(format!(
241
"calls: history not loaded: {}",
242
short_error(&error)
243
)),
241
244
Err(_) => {}
242
245
})
243
246
.detach();
@@ -237,7 +237,10 @@ impl AppState {237
})237
})238
.ok();238
.ok();239
}239
}240
Ok(Err(error)) => crate::diagnostics::record(format!("calls: history not loaded: {}", short_error(&error))),240
Ok(Err(error)) => crate::diagnostics::record(format!(241
"calls: history not loaded: {}",242
short_error(&error)243
)),241
Err(_) => {}244
Err(_) => {}242
})245
})243
.detach();246
.detach();@@ -4,11 +4,17 @@ use std::time::Duration;
4
4
5
5
use calling::meeting::{LiveMeeting, fetch_live_meeting};
6
6
use calling::{
7
AcceptMode, BackgroundCache, CallEngine, DeviceChoice, CallHandle, CallSpec, CallState, CallUpdate, DefaultBackground, EndReason, EngineConfig, EngineEvent, MeetingTarget, call_channel,
7
AcceptMode, BackgroundCache, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,
8
DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,
9
call_channel,
8
10
};
9
11
use session::{Session, SessionConfig, Transport};
10
12
11
const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];
13
const START_RETRY_STEPS: [Duration; 3] = [
14
Duration::from_secs(1),
15
Duration::from_secs(2),
16
Duration::from_secs(5),
17
];
12
18
const START_RETRY_STEADY: Duration = Duration::from_secs(10);
13
19
const NOT_READY: &str = "Calls are not ready yet";
14
20
const CALL_DUMPS_DIR: &str = "call-dumps";
@@ -30,8 +36,12 @@ impl CallLauncher {
30
36
});
31
37
let running = launcher.clone();
32
38
crate::runtime::handle().spawn(async move {
33
let (engine, mut events) =
34
start_with_retry(|| start_engine(transport.clone(), ringable), &START_RETRY_STEPS, START_RETRY_STEADY).await;
39
let (engine, mut events) = start_with_retry(
40
|| start_engine(transport.clone(), ringable),
41
&START_RETRY_STEPS,
42
START_RETRY_STEADY,
43
)
44
.await;
35
45
crate::diagnostics::record("calls: engine ready, registered with the registrar");
36
46
engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());
37
47
*running.engine.lock().expect("engine lock") = Some(engine);
@@ -83,7 +93,11 @@ impl CallLauncher {
83
93
}
84
94
}
85
95
86
pub async fn refresh_backgrounds(&self, cache: &BackgroundCache, thumbnails: usize) -> Option<Vec<DefaultBackground>> {
96
pub async fn refresh_backgrounds(
97
&self,
98
cache: &BackgroundCache,
99
thumbnails: usize,
100
) -> Option<Vec<DefaultBackground>> {
87
101
let session = self.engine()?.session();
88
102
let catalog = cache.refresh_catalog(&session).await.ok()?;
89
103
for image in catalog.iter().take(thumbnails) {
@@ -92,12 +106,19 @@ impl CallLauncher {
92
106
Some(catalog)
93
107
}
94
108
95
pub async fn download_background(&self, cache: &BackgroundCache, image: &DefaultBackground) -> Option<std::path::PathBuf> {
109
pub async fn download_background(
110
&self,
111
cache: &BackgroundCache,
112
image: &DefaultBackground,
113
) -> Option<std::path::PathBuf> {
96
114
let session = self.engine()?.session();
97
115
cache.ensure_image(&session, image).await.ok()
98
116
}
99
117
100
pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget, String> {
118
pub async fn resolve_meeting(
119
&self,
120
meeting_data: &serde_json::Value,
121
) -> Result<MeetingTarget, String> {
101
122
self.engine()
102
123
.ok_or_else(|| NOT_READY.to_owned())?
103
124
.resolve_meeting(meeting_data)
@@ -137,7 +158,10 @@ where
137
158
let delay = steps.get(failures).copied().unwrap_or(steady);
138
159
failures += 1;
139
160
if failure != last_failure {
140
crate::diagnostics::record(format!("calls: engine start failed, retrying in {}s: {failure}", delay.as_secs()));
161
crate::diagnostics::record(format!(
162
"calls: engine start failed, retrying in {}s: {failure}",
163
delay.as_secs()
164
));
141
165
last_failure = failure;
142
166
}
143
167
tokio::time::sleep(delay).await;
@@ -147,7 +171,10 @@ where
147
171
async fn start_engine(
148
172
transport: Arc<dyn Transport>,
149
173
ringable: bool,
150
) -> calling::Result<(CallEngine, tokio::sync::mpsc::UnboundedReceiver<EngineEvent>)> {
174
) -> calling::Result<(
175
CallEngine,
176
tokio::sync::mpsc::UnboundedReceiver<EngineEvent>,
177
)> {
151
178
let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;
152
179
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
153
180
let config = EngineConfig {
@@ -174,7 +201,10 @@ mod tests {
174
201
175
202
#[test]
176
203
fn engine_start_survives_errors_and_panics() {
177
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();
204
let runtime = tokio::runtime::Builder::new_multi_thread()
205
.enable_all()
206
.build()
207
.unwrap();
178
208
let attempts = Arc::new(AtomicU32::new(0));
179
209
let counter = attempts.clone();
180
210
let started = runtime.block_on(start_with_retry(
@@ -4,11 +4,17 @@ use std::time::Duration;4
4
5
use calling::meeting::{LiveMeeting, fetch_live_meeting};5
use calling::meeting::{LiveMeeting, fetch_live_meeting};6
use calling::{6
use calling::{7
AcceptMode, BackgroundCache, CallEngine, DeviceChoice, CallHandle, CallSpec, CallState, CallUpdate, DefaultBackground, EndReason, EngineConfig, EngineEvent, MeetingTarget, call_channel,7
AcceptMode, BackgroundCache, CallEngine, CallHandle, CallSpec, CallState, CallUpdate,8
DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent, MeetingTarget,9
call_channel,8
};10
};9
use session::{Session, SessionConfig, Transport};11
use session::{Session, SessionConfig, Transport};10
12
11
const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];13
const START_RETRY_STEPS: [Duration; 3] = [14
Duration::from_secs(1),15
Duration::from_secs(2),16
Duration::from_secs(5),17
];12
const START_RETRY_STEADY: Duration = Duration::from_secs(10);18
const START_RETRY_STEADY: Duration = Duration::from_secs(10);13
const NOT_READY: &str = "Calls are not ready yet";19
const NOT_READY: &str = "Calls are not ready yet";14
const CALL_DUMPS_DIR: &str = "call-dumps";20
const CALL_DUMPS_DIR: &str = "call-dumps";@@ -30,8 +36,12 @@ impl CallLauncher {30
});36
});31
let running = launcher.clone();37
let running = launcher.clone();32
crate::runtime::handle().spawn(async move {38
crate::runtime::handle().spawn(async move {33
let (engine, mut events) =39
let (engine, mut events) = start_with_retry(34
start_with_retry(|| start_engine(transport.clone(), ringable), &START_RETRY_STEPS, START_RETRY_STEADY).await;40
|| start_engine(transport.clone(), ringable),41
&START_RETRY_STEPS,42
START_RETRY_STEADY,43
)44
.await;35
crate::diagnostics::record("calls: engine ready, registered with the registrar");45
crate::diagnostics::record("calls: engine ready, registered with the registrar");36
engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());46
engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());37
*running.engine.lock().expect("engine lock") = Some(engine);47
*running.engine.lock().expect("engine lock") = Some(engine);@@ -83,7 +93,11 @@ impl CallLauncher {83
}93
}84
}94
}85
95
86
pub async fn refresh_backgrounds(&self, cache: &BackgroundCache, thumbnails: usize) -> Option<Vec<DefaultBackground>> {96
pub async fn refresh_backgrounds(97
&self,98
cache: &BackgroundCache,99
thumbnails: usize,100
) -> Option<Vec<DefaultBackground>> {87
let session = self.engine()?.session();101
let session = self.engine()?.session();88
let catalog = cache.refresh_catalog(&session).await.ok()?;102
let catalog = cache.refresh_catalog(&session).await.ok()?;89
for image in catalog.iter().take(thumbnails) {103
for image in catalog.iter().take(thumbnails) {@@ -92,12 +106,19 @@ impl CallLauncher {92
Some(catalog)106
Some(catalog)93
}107
}94
108
95
pub async fn download_background(&self, cache: &BackgroundCache, image: &DefaultBackground) -> Option<std::path::PathBuf> {109
pub async fn download_background(110
&self,111
cache: &BackgroundCache,112
image: &DefaultBackground,113
) -> Option<std::path::PathBuf> {96
let session = self.engine()?.session();114
let session = self.engine()?.session();97
cache.ensure_image(&session, image).await.ok()115
cache.ensure_image(&session, image).await.ok()98
}116
}99
117
100
pub async fn resolve_meeting(&self, meeting_data: &serde_json::Value) -> Result<MeetingTarget, String> {118
pub async fn resolve_meeting(119
&self,120
meeting_data: &serde_json::Value,121
) -> Result<MeetingTarget, String> {101
self.engine()122
self.engine()102
.ok_or_else(|| NOT_READY.to_owned())?123
.ok_or_else(|| NOT_READY.to_owned())?103
.resolve_meeting(meeting_data)124
.resolve_meeting(meeting_data)@@ -137,7 +158,10 @@ where137
let delay = steps.get(failures).copied().unwrap_or(steady);158
let delay = steps.get(failures).copied().unwrap_or(steady);138
failures += 1;159
failures += 1;139
if failure != last_failure {160
if failure != last_failure {140
crate::diagnostics::record(format!("calls: engine start failed, retrying in {}s: {failure}", delay.as_secs()));161
crate::diagnostics::record(format!(162
"calls: engine start failed, retrying in {}s: {failure}",163
delay.as_secs()164
));141
last_failure = failure;165
last_failure = failure;142
}166
}143
tokio::time::sleep(delay).await;167
tokio::time::sleep(delay).await;@@ -147,7 +171,10 @@ where147
async fn start_engine(171
async fn start_engine(148
transport: Arc<dyn Transport>,172
transport: Arc<dyn Transport>,149
ringable: bool,173
ringable: bool,150
) -> calling::Result<(CallEngine, tokio::sync::mpsc::UnboundedReceiver<EngineEvent>)> {174
) -> calling::Result<(175
CallEngine,176
tokio::sync::mpsc::UnboundedReceiver<EngineEvent>,177
)> {151
let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;178
let session = Session::with_transport(transport.clone(), SessionConfig::default()).await?;152
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;179
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;153
let config = EngineConfig {180
let config = EngineConfig {@@ -174,7 +201,10 @@ mod tests {174
201
175
#[test]202
#[test]176
fn engine_start_survives_errors_and_panics() {203
fn engine_start_survives_errors_and_panics() {177
let runtime = tokio::runtime::Builder::new_multi_thread().enable_all().build().unwrap();204
let runtime = tokio::runtime::Builder::new_multi_thread()205
.enable_all()206
.build()207
.unwrap();178
let attempts = Arc::new(AtomicU32::new(0));208
let attempts = Arc::new(AtomicU32::new(0));179
let counter = attempts.clone();209
let counter = attempts.clone();180
let started = runtime.block_on(start_with_retry(210
let started = runtime.block_on(start_with_retry(@@ -19,19 +19,25 @@ mod ring;
19
19
mod target;
20
20
21
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};
23
pub use features::TransferCandidate;
24
pub use demo::DemoScene;
25
22
pub use agenda::{AgendaRow, fetch_window, join_available};
23
pub use background::{
24
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
25
load_custom_backgrounds,
26
};
27
pub use demo::DemoScene;
28
pub use features::TransferCandidate;
26
29
pub use history::CallRow;
27
30
pub use launcher::CallLauncher;
28
pub use list::{AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry, SECTION_HEIGHT};
31
pub use list::{
32
AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
33
SECTION_HEIGHT,
34
};
29
35
pub use media::CallMedia;
30
pub use overlay::CallWindows;
31
36
pub use model::{
32
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,
33
grid_layout, tile_size,
37
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES,
38
REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size,
34
39
};
40
pub use overlay::CallWindows;
35
41
pub use preview::{CameraPreview, preview_backgrounds};
36
42
pub use ring::{MissedCall, RingEntry, Rings};
37
43
pub use target::plan_for_chat;
@@ -19,19 +19,25 @@ mod ring;19
mod target;19
mod target;20
20
21
pub use actions::{load_camera, 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};23
pub use features::TransferCandidate;24
pub use demo::DemoScene;25
pub use agenda::{AgendaRow, fetch_window, join_available};22
pub use agenda::{AgendaRow, fetch_window, join_available};23
pub use background::{24
BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,25
load_custom_backgrounds,26
};27
pub use demo::DemoScene;28
pub use features::TransferCandidate;26
pub use history::CallRow;29
pub use history::CallRow;27
pub use launcher::CallLauncher;30
pub use launcher::CallLauncher;28
pub use list::{AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry, SECTION_HEIGHT};31
pub use list::{32
AGENDA_ROW_HEIGHT, CALL_ROW_HEIGHT, CallsList, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,33
SECTION_HEIGHT,34
};29
pub use media::CallMedia;35
pub use media::CallMedia;30
pub use overlay::CallWindows;31
pub use model::{36
pub use model::{32
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES, REACTION_SHOWN, Tile, TileSize, TileState,37
ActiveCall, CAPTION_SHOWN, CHAT_OPEN_TILES, CallKind, CallModel, Focus, GridLayout, MAX_TILES,33
grid_layout, tile_size,38
REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size,34
};39
};40
pub use overlay::CallWindows;35
pub use preview::{CameraPreview, preview_backgrounds};41
pub use preview::{CameraPreview, preview_backgrounds};36
pub use ring::{MissedCall, RingEntry, Rings};42
pub use ring::{MissedCall, RingEntry, Rings};37
pub use target::plan_for_chat;43
pub use target::plan_for_chat;@@ -2,8 +2,9 @@ use std::sync::Arc;
2
2
use std::time::{Duration, Instant};
3
3
4
4
use calling::{
5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists, EndKind, EndReason,
6
HoldState, MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,
6
DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,
7
RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,
7
8
};
8
9
use tokio::sync::mpsc::UnboundedSender;
9
10
@@ -73,7 +74,13 @@ impl ConsultCall {
73
74
}
74
75
75
76
impl ActiveCall {
76
pub fn new(id: u64, model: CallModel, commands: UnboundedSender<CallCommand>, conversation_id: Option<String>, video: Arc<VideoHub>) -> Self {
77
pub fn new(
78
id: u64,
79
model: CallModel,
80
commands: UnboundedSender<CallCommand>,
81
conversation_id: Option<String>,
82
video: Arc<VideoHub>,
83
) -> Self {
77
84
ActiveCall {
78
85
id,
79
86
model,
@@ -91,11 +98,19 @@ impl ActiveCall {
91
98
}
92
99
93
100
pub fn chat_thread(&self) -> Option<&str> {
94
chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())
101
chat_thread(
102
self.model.kind,
103
self.model.meeting_chat.as_deref(),
104
self.conversation_id.as_deref(),
105
)
95
106
}
96
107
}
97
108
98
pub fn chat_thread<'a>(kind: CallKind, meeting_chat: Option<&'a str>, conversation_id: Option<&'a str>) -> Option<&'a str> {
109
pub fn chat_thread<'a>(
110
kind: CallKind,
111
meeting_chat: Option<&'a str>,
112
conversation_id: Option<&'a str>,
113
) -> Option<&'a str> {
99
114
match kind {
100
115
CallKind::Meeting => meeting_chat.or(conversation_id),
101
116
CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,
@@ -336,12 +351,19 @@ impl CallModel {
336
351
}
337
352
338
353
pub fn people(title: &str, callees: &[(String, String)]) -> Self {
339
let kind = if callees.len() == 1 { CallKind::Direct } else { CallKind::Group };
354
let kind = if callees.len() == 1 {
355
CallKind::Direct
356
} else {
357
CallKind::Group
358
};
340
359
let peer_name = match callees {
341
360
[(_, name)] => name.clone(),
342
361
_ => title.to_owned(),
343
362
};
344
let tiles = callees.iter().map(|(mri, name)| Tile::invited(mri, name)).collect();
363
let tiles = callees
364
.iter()
365
.map(|(mri, name)| Tile::invited(mri, name))
366
.collect();
345
367
Self::base(kind, title, &peer_name, tiles)
346
368
}
347
369
@@ -412,7 +434,9 @@ impl CallModel {
412
434
CallUpdate::ShareSources(sources) => self.share_sources = sources,
413
435
CallUpdate::ShareSound(active) => self.share_sound = active,
414
436
CallUpdate::OwnHand(rank) => self.own_hand = rank,
415
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),
437
CallUpdate::Reaction { mri, reaction } => {
438
self.note_reaction(mri, reaction, Instant::now())
439
}
416
440
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),
417
441
CallUpdate::Captions(state) => {
418
442
if state != CaptionState::On {
@@ -438,8 +462,17 @@ impl CallModel {
438
462
if self.captions == CaptionState::Off {
439
463
return;
440
464
}
441
let speaker = if entry.display_name.is_empty() { "Someone".to_owned() } else { entry.display_name };
442
let line = CaptionLine { id: entry.id, speaker, text: entry.text, at };
465
let speaker = if entry.display_name.is_empty() {
466
"Someone".to_owned()
467
} else {
468
entry.display_name
469
};
470
let line = CaptionLine {
471
id: entry.id,
472
speaker,
473
text: entry.text,
474
at,
475
};
443
476
match self.caption_lines.last_mut() {
444
477
Some(last) if last.id == line.id => *last = line,
445
478
_ => self.caption_lines.push(line),
@@ -449,7 +482,10 @@ impl CallModel {
449
482
}
450
483
451
484
pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {
452
self.caption_lines.iter().filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN).collect()
485
self.caption_lines
486
.iter()
487
.filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN)
488
.collect()
453
489
}
454
490
455
491
pub fn captions_on(&self) -> bool {
@@ -467,20 +503,29 @@ impl CallModel {
467
503
pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {
468
504
let own_echo = Some(&mri) == self.own_mri.as_ref()
469
505
&& self.reactions.iter().any(|chip| {
470
chip.mri == mri && chip.reaction == reaction && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW
506
chip.mri == mri
507
&& chip.reaction == reaction
508
&& at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW
471
509
});
472
510
if own_echo {
473
511
return;
474
512
}
475
self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);
513
self.reactions.retain(|chip| {
514
chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN
515
});
476
516
self.reaction_serial += 1;
477
self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });
517
self.reactions.push(ReactionChip {
518
mri,
519
reaction,
520
since: at,
521
serial: self.reaction_serial,
522
});
478
523
}
479
524
480
525
pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {
481
self.reactions
482
.iter()
483
.find(|chip| chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN)
526
self.reactions.iter().find(|chip| {
527
chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN
528
})
484
529
}
485
530
486
531
pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {
@@ -488,7 +533,11 @@ impl CallModel {
488
533
}
489
534
490
535
pub fn hand_position(&self, rank: u64) -> usize {
491
let raised = self.tiles.iter().filter_map(|tile| tile.hand).chain(self.own_hand);
536
let raised = self
537
.tiles
538
.iter()
539
.filter_map(|tile| tile.hand)
540
.chain(self.own_hand);
492
541
1 + raised.filter(|other| *other < rank).count()
493
542
}
494
543
@@ -505,7 +554,10 @@ impl CallModel {
505
554
}
506
555
507
556
pub fn lobby_guests(&self) -> Vec<&Tile> {
508
self.tiles.iter().filter(|tile| tile.state == TileState::InLobby).collect()
557
self.tiles
558
.iter()
559
.filter(|tile| tile.state == TileState::InLobby)
560
.collect()
509
561
}
510
562
511
563
pub fn can_admit(&self) -> bool {
@@ -517,23 +569,52 @@ impl CallModel {
517
569
}
518
570
519
571
pub fn toggle_pin(&mut self, mri: &str) {
520
self.pinned = if self.is_pinned(mri) { None } else { Some(mri.to_owned()) };
572
self.pinned = if self.is_pinned(mri) {
573
None
574
} else {
575
Some(mri.to_owned())
576
};
521
577
}
522
578
523
579
pub fn is_spotlighted(&self, mri: &str) -> bool {
524
580
self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()
525
|| self.tiles.iter().any(|tile| tile.mri == mri && tile.spotlight.is_some())
581
|| self
582
.tiles
583
.iter()
584
.any(|tile| tile.mri == mri && tile.spotlight.is_some())
526
585
}
527
586
528
587
pub fn focus(&self) -> Option<Focus> {
529
588
let own = |mri: &str| self.own_mri.as_deref() == Some(mri);
530
let on_stage = |mri: &str| own(mri) || self.visible_tiles().iter().any(|tile| tile.mri == mri && tile.state == TileState::Present);
589
let on_stage = |mri: &str| {
590
own(mri)
591
|| self
592
.visible_tiles()
593
.iter()
594
.any(|tile| tile.mri == mri && tile.state == TileState::Present)
595
};
531
596
if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {
532
return Some(Focus { mri: pinned.to_owned(), own: own(pinned), spotlight: self.is_spotlighted(pinned), pinned: true });
597
return Some(Focus {
598
mri: pinned.to_owned(),
599
own: own(pinned),
600
spotlight: self.is_spotlighted(pinned),
601
pinned: true,
602
});
533
603
}
534
let remote = self.tiles.iter().filter(|tile| tile.state == TileState::Present).filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
535
let (_, mri) = remote.chain(self.own_spotlight.zip(self.own_mri.as_deref())).min_by_key(|(rank, _)| *rank)?;
536
Some(Focus { mri: mri.to_owned(), own: own(mri), spotlight: true, pinned: false })
604
let remote = self
605
.tiles
606
.iter()
607
.filter(|tile| tile.state == TileState::Present)
608
.filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));
609
let (_, mri) = remote
610
.chain(self.own_spotlight.zip(self.own_mri.as_deref()))
611
.min_by_key(|(rank, _)| *rank)?;
612
Some(Focus {
613
mri: mri.to_owned(),
614
own: own(mri),
615
spotlight: true,
616
pinned: false,
617
})
537
618
}
538
619
539
620
pub fn any_hand_raised(&self) -> bool {
@@ -541,22 +622,38 @@ impl CallModel {
541
622
}
542
623
543
624
pub fn own_cell_index(&self, remote_cells: usize) -> usize {
544
let Some(own) = self.own_hand else { return remote_cells };
545
let ahead = self.visible_tiles().iter().filter(|tile| tile.hand.is_some_and(|rank| rank < own)).count();
625
let Some(own) = self.own_hand else {
626
return remote_cells;
627
};
628
let ahead = self
629
.visible_tiles()
630
.iter()
631
.filter(|tile| tile.hand.is_some_and(|rank| rank < own))
632
.count();
546
633
ahead.min(remote_cells)
547
634
}
548
635
549
636
fn apply_roster(&mut self, entries: &[RosterEntry]) {
550
let own_entry = entries.iter().find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
637
let own_entry = entries
638
.iter()
639
.find(|entry| Some(&entry.mri) == self.own_mri.as_ref());
551
640
if let Some(entry) = own_entry {
552
641
self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);
553
642
}
554
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
643
self.own_spotlight =
644
own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));
555
645
if let Some(entry) = own_entry {
556
646
self.organizer = entry.organizer;
557
647
}
558
for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {
559
let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };
648
for entry in entries
649
.iter()
650
.filter(|entry| Some(&entry.mri) != self.own_mri.as_ref())
651
{
652
let state = if entry.in_lobby {
653
TileState::InLobby
654
} else {
655
TileState::Present
656
};
560
657
match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {
561
658
Some(tile) => {
562
659
tile.state = state;
@@ -583,7 +680,11 @@ impl CallModel {
583
680
}
584
681
let own_mri = self.own_mri.clone();
585
682
let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);
586
if self.pinned.as_deref().is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref()) {
683
if self
684
.pinned
685
.as_deref()
686
.is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref())
687
{
587
688
self.pinned = None;
588
689
}
589
690
self.tiles.retain_mut(|tile| {
@@ -602,21 +703,37 @@ impl CallModel {
602
703
}
603
704
604
705
pub fn visible_tiles(&self) -> Vec<&Tile> {
605
let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();
706
let mut tiles: Vec<&Tile> = self
707
.tiles
708
.iter()
709
.filter(|tile| tile.state != TileState::InLobby)
710
.collect();
606
711
tiles.sort_by_key(|tile| {
607
712
let state = match tile.state {
608
713
TileState::Present => 0,
609
714
TileState::Invited => 1,
610
715
_ => 2,
611
716
};
612
(!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), state)
717
(
718
!self.is_pinned(&tile.mri),
719
tile.hand.is_none(),
720
tile.hand.unwrap_or(0),
721
state,
722
)
613
723
});
614
724
tiles
615
725
}
616
726
617
727
pub fn strip_tiles(&self) -> Vec<&Tile> {
618
728
let mut tiles = self.visible_tiles();
619
tiles.sort_by_key(|tile| (!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));
729
tiles.sort_by_key(|tile| {
730
(
731
!self.is_pinned(&tile.mri),
732
tile.hand.is_none(),
733
tile.hand.unwrap_or(0),
734
!self.tile_speaking(tile),
735
)
736
});
620
737
tiles
621
738
}
622
739
@@ -744,15 +861,24 @@ impl CallModel {
744
861
}
745
862
746
863
fn is_live(&self) -> bool {
747
matches!(self.state, CallState::Connected { .. } | CallState::Reconnecting { .. })
864
matches!(
865
self.state,
866
CallState::Connected { .. } | CallState::Reconnecting { .. }
867
)
748
868
}
749
869
750
870
pub fn screens(&self) -> Vec<&ShareSource> {
751
self.share_sources.iter().filter(|source| source.kind == ShareKind::Screen).collect()
871
self.share_sources
872
.iter()
873
.filter(|source| source.kind == ShareKind::Screen)
874
.collect()
752
875
}
753
876
754
877
pub fn windows(&self) -> Vec<&ShareSource> {
755
self.share_sources.iter().filter(|source| source.kind == ShareKind::Window).collect()
878
self.share_sources
879
.iter()
880
.filter(|source| source.kind == ShareKind::Window)
881
.collect()
756
882
}
757
883
758
884
pub fn can_unmute(&self) -> bool {
@@ -815,25 +941,36 @@ mod tests {
815
941
816
942
fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {
817
943
RosterEntry {
818
spotlight: Some(calling::Spotlight { state_id: format!("sp-{rank}"), rank }),
944
spotlight: Some(calling::Spotlight {
945
state_id: format!("sp-{rank}"),
946
rank,
947
}),
819
948
..entry(mri, name, false, false)
820
949
}
821
950
}
822
951
823
952
fn organizer_entry(mri: &str) -> RosterEntry {
824
RosterEntry { organizer: true, ..entry(mri, "Me", false, false) }
953
RosterEntry {
954
organizer: true,
955
..entry(mri, "Me", false, false)
956
}
825
957
}
826
958
827
959
fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {
828
960
RosterEntry {
829
hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),
961
hand: Some(calling::RaisedHand {
962
state_id: format!("s-{rank}"),
963
rank,
964
}),
830
965
..entry(mri, name, false, false)
831
966
}
832
967
}
833
968
834
969
fn meeting_with_me() -> CallModel {
835
970
let mut model = CallModel::meeting("Standup", false);
836
model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });
971
model.apply(CallUpdate::OwnIdentity {
972
mri: "8:orgid:me".into(),
973
});
837
974
model
838
975
}
839
976
@@ -896,17 +1033,44 @@ mod tests {
896
1033
let elapsed = Some(Duration::from_secs(42));
897
1034
let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");
898
1035
assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");
899
assert_eq!(notice(EndReason::Remote(EndKind::Normal), elapsed), "Call ended 00:42");
900
assert_eq!(notice(EndReason::Remote(EndKind::Normal), None), "Call ended");
1036
assert_eq!(
1037
notice(EndReason::Remote(EndKind::Normal), elapsed),
1038
"Call ended 00:42"
1039
);
1040
assert_eq!(
1041
notice(EndReason::Remote(EndKind::Normal), None),
1042
"Call ended"
1043
);
901
1044
assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");
902
1045
assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");
903
assert_eq!(notice(EndReason::Failed("no route".into()), None), "Call failed: no route");
904
assert_eq!(notice(EndReason::Remote(EndKind::Declined), None), "Bea declined");
905
assert_eq!(notice(EndReason::Remote(EndKind::NoAnswer), None), "No answer");
906
assert_eq!(notice(EndReason::Remote(EndKind::Unavailable), None), "Bea is not available");
907
assert_eq!(notice(EndReason::Remote(EndKind::Cancelled), None), "Call ended");
908
assert_eq!(notice(EndReason::Remote(EndKind::Other), None), "Call ended");
909
assert_eq!(notice(EndReason::Remote(EndKind::AnsweredElsewhere), None), "Call ended");
1046
assert_eq!(
1047
notice(EndReason::Failed("no route".into()), None),
1048
"Call failed: no route"
1049
);
1050
assert_eq!(
1051
notice(EndReason::Remote(EndKind::Declined), None),
1052
"Bea declined"
1053
);
1054
assert_eq!(
1055
notice(EndReason::Remote(EndKind::NoAnswer), None),
1056
"No answer"
1057
);
1058
assert_eq!(
1059
notice(EndReason::Remote(EndKind::Unavailable), None),
1060
"Bea is not available"
1061
);
1062
assert_eq!(
1063
notice(EndReason::Remote(EndKind::Cancelled), None),
1064
"Call ended"
1065
);
1066
assert_eq!(
1067
notice(EndReason::Remote(EndKind::Other), None),
1068
"Call ended"
1069
);
1070
assert_eq!(
1071
notice(EndReason::Remote(EndKind::AnsweredElsewhere), None),
1072
"Call ended"
1073
);
910
1074
}
911
1075
912
1076
#[test]
@@ -915,8 +1079,14 @@ mod tests {
915
1079
assert_eq!(direct.connecting_text(), "Calling...");
916
1080
direct.apply(CallUpdate::Progress(Progress::Ringing));
917
1081
assert_eq!(direct.connecting_text(), "Ringing");
918
assert_eq!(CallModel::meeting("Standup", false).connecting_text(), "Joining...");
919
assert_eq!(CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(), "Connecting...");
1082
assert_eq!(
1083
CallModel::meeting("Standup", false).connecting_text(),
1084
"Joining..."
1085
);
1086
assert_eq!(
1087
CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(),
1088
"Connecting..."
1089
);
920
1090
assert_eq!(CallModel::test().connecting_text(), "Calling...");
921
1091
}
922
1092
@@ -936,7 +1106,12 @@ mod tests {
936
1106
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));
937
1107
model.apply(CallUpdate::Progress(Progress::Ringing));
938
1108
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));
939
model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
1109
model.apply(CallUpdate::Roster(vec![entry(
1110
"8:orgid:b",
1111
"Bea",
1112
false,
1113
false,
1114
)]));
940
1115
assert_eq!(model.tiles[0].state, TileState::Present);
941
1116
assert_eq!(model.tile_caption(&model.tiles[0]), None);
942
1117
}
@@ -945,7 +1120,10 @@ mod tests {
945
1120
fn several_callees_make_a_group_call_named_after_the_chat() {
946
1121
let model = CallModel::people(
947
1122
"Retro team",
948
&[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
1123
&[
1124
("8:orgid:b".into(), "Bea".into()),
1125
("8:orgid:c".into(), "Cy".into()),
1126
],
949
1127
);
950
1128
assert_eq!(model.kind, CallKind::Group);
951
1129
assert_eq!(model.peer_name, "Retro team");
@@ -961,8 +1139,18 @@ mod tests {
961
1139
entry("8:orgid:b", "Bo", false, false),
962
1140
]));
963
1141
assert_eq!(model.tiles.len(), 2);
964
assert!(model.tiles.iter().find(|tile| tile.name == "Ana").unwrap().muted);
965
model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false), entry("8:orgid:b", "Bo", false, false)]));
1142
assert!(
1143
model
1144
.tiles
1145
.iter()
1146
.find(|tile| tile.name == "Ana")
1147
.unwrap()
1148
.muted
1149
);
1150
model.apply(CallUpdate::Roster(vec![
1151
entry("8:orgid:me", "Me", false, false),
1152
entry("8:orgid:b", "Bo", false, false),
1153
]));
966
1154
assert_eq!(model.tiles.len(), 1);
967
1155
assert_eq!(model.tiles[0].name, "Bo");
968
1156
}
@@ -970,7 +1158,12 @@ mod tests {
970
1158
#[test]
971
1159
fn an_invited_callee_who_leaves_stays_as_left() {
972
1160
let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
973
model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));
1161
model.apply(CallUpdate::Roster(vec![entry(
1162
"8:orgid:b",
1163
"Bea",
1164
false,
1165
false,
1166
)]));
974
1167
model.apply(CallUpdate::Roster(Vec::new()));
975
1168
assert_eq!(model.tiles[0].state, TileState::Left);
976
1169
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));
@@ -983,7 +1176,11 @@ mod tests {
983
1176
entry("8:orgid:a", "Ana", false, false),
984
1177
entry("8:orgid:g", "Guest", false, true),
985
1178
]));
986
let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
1179
let names: Vec<&str> = model
1180
.visible_tiles()
1181
.iter()
1182
.map(|tile| tile.name.as_str())
1183
.collect();
987
1184
assert_eq!(names, vec!["Ana"]);
988
1185
}
989
1186
@@ -1003,29 +1200,72 @@ mod tests {
1003
1200
entry("8:orgid:a", "Ana", false, false),
1004
1201
entry("8:orgid:b", "Bo", false, false),
1005
1202
]));
1006
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1203
model.apply(CallUpdate::State(CallState::Connected {
1204
since: Instant::now(),
1205
}));
1007
1206
model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1008
1207
let tiles: Vec<Tile> = model.tiles.clone();
1009
1208
assert!(!model.tile_speaking(&tiles[0]));
1010
1209
assert!(model.tile_speaking(&tiles[1]));
1011
1210
let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1012
lone.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1013
lone.apply(CallUpdate::Levels { local: 0.0, remote: 0.5 });
1211
lone.apply(CallUpdate::State(CallState::Connected {
1212
since: Instant::now(),
1213
}));
1214
lone.apply(CallUpdate::Levels {
1215
local: 0.0,
1216
remote: 0.5,
1217
});
1014
1218
assert!(lone.tile_speaking(&lone.tiles[0].clone()));
1015
1219
}
1016
1220
1017
1221
#[test]
1018
1222
fn more_than_nine_cells_collapse_into_a_plus_n_tile() {
1019
assert_eq!(grid_layout(0, MAX_TILES), GridLayout { shown_others: 0, hidden: 0 });
1020
assert_eq!(grid_layout(8, MAX_TILES), GridLayout { shown_others: 8, hidden: 0 });
1021
assert_eq!(grid_layout(9, MAX_TILES), GridLayout { shown_others: 7, hidden: 2 });
1022
assert_eq!(grid_layout(30, MAX_TILES), GridLayout { shown_others: 7, hidden: 23 });
1223
assert_eq!(
1224
grid_layout(0, MAX_TILES),
1225
GridLayout {
1226
shown_others: 0,
1227
hidden: 0
1228
}
1229
);
1230
assert_eq!(
1231
grid_layout(8, MAX_TILES),
1232
GridLayout {
1233
shown_others: 8,
1234
hidden: 0
1235
}
1236
);
1237
assert_eq!(
1238
grid_layout(9, MAX_TILES),
1239
GridLayout {
1240
shown_others: 7,
1241
hidden: 2
1242
}
1243
);
1244
assert_eq!(
1245
grid_layout(30, MAX_TILES),
1246
GridLayout {
1247
shown_others: 7,
1248
hidden: 23
1249
}
1250
);
1023
1251
}
1024
1252
1025
1253
#[test]
1026
1254
fn an_open_chat_panel_leaves_room_for_fewer_tiles() {
1027
assert_eq!(grid_layout(5, CHAT_OPEN_TILES), GridLayout { shown_others: 5, hidden: 0 });
1028
assert_eq!(grid_layout(6, CHAT_OPEN_TILES), GridLayout { shown_others: 4, hidden: 2 });
1255
assert_eq!(
1256
grid_layout(5, CHAT_OPEN_TILES),
1257
GridLayout {
1258
shown_others: 5,
1259
hidden: 0
1260
}
1261
);
1262
assert_eq!(
1263
grid_layout(6, CHAT_OPEN_TILES),
1264
GridLayout {
1265
shown_others: 4,
1266
hidden: 2
1267
}
1268
);
1029
1269
}
1030
1270
1031
1271
#[test]
@@ -1045,9 +1285,15 @@ mod tests {
1045
1285
assert_eq!(model.sharing_label(), None);
1046
1286
model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));
1047
1287
assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));
1048
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1288
model.apply(CallUpdate::State(CallState::Connected {
1289
since: Instant::now(),
1290
}));
1049
1291
model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));
1050
let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1292
let names: Vec<&str> = model
1293
.strip_tiles()
1294
.iter()
1295
.map(|tile| tile.name.as_str())
1296
.collect();
1051
1297
assert_eq!(names, vec!["Bo", "Ana"]);
1052
1298
model.apply(CallUpdate::ScreenShare(None));
1053
1299
assert_eq!(model.sharing_label(), None);
@@ -1060,7 +1306,12 @@ mod tests {
1060
1306
with_camera.has_video = true;
1061
1307
model.apply(CallUpdate::Roster(vec![with_camera]));
1062
1308
assert!(model.tiles[0].has_video);
1063
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1309
model.apply(CallUpdate::Roster(vec![entry(
1310
"8:orgid:a",
1311
"Ana",
1312
false,
1313
false,
1314
)]));
1064
1315
assert!(!model.tiles[0].has_video);
1065
1316
}
1066
1317
@@ -1068,10 +1319,22 @@ mod tests {
1068
1319
fn present_guests_sort_before_waiting_ones() {
1069
1320
let mut model = CallModel::people(
1070
1321
"Group",
1071
&[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],
1322
&[
1323
("8:orgid:b".into(), "Bea".into()),
1324
("8:orgid:c".into(), "Cy".into()),
1325
],
1072
1326
);
1073
model.apply(CallUpdate::Roster(vec![entry("8:orgid:c", "Cy", false, false)]));
1074
let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
1327
model.apply(CallUpdate::Roster(vec![entry(
1328
"8:orgid:c",
1329
"Cy",
1330
false,
1331
false,
1332
)]));
1333
let names: Vec<&str> = model
1334
.visible_tiles()
1335
.iter()
1336
.map(|tile| tile.name.as_str())
1337
.collect();
1075
1338
assert_eq!(names, vec!["Cy", "Bea"]);
1076
1339
}
1077
1340
@@ -1086,12 +1349,23 @@ mod tests {
1086
1349
]));
1087
1350
assert_eq!(model.own_hand, Some(6));
1088
1351
assert!(model.any_hand_raised());
1089
let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();
1352
let names: Vec<&str> = model
1353
.visible_tiles()
1354
.iter()
1355
.map(|tile| tile.name.as_str())
1356
.collect();
1090
1357
assert_eq!(names, vec!["Cy", "Bo", "Ana"]);
1091
let positions: Vec<usize> = [4, 6, 9].into_iter().map(|rank| model.hand_position(rank)).collect();
1358
let positions: Vec<usize> = [4, 6, 9]
1359
.into_iter()
1360
.map(|rank| model.hand_position(rank))
1361
.collect();
1092
1362
assert_eq!(positions, vec![1, 2, 3]);
1093
1363
assert_eq!(model.own_cell_index(3), 1);
1094
let strip: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1364
let strip: Vec<&str> = model
1365
.strip_tiles()
1366
.iter()
1367
.map(|tile| tile.name.as_str())
1368
.collect();
1095
1369
assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);
1096
1370
}
1097
1371
@@ -1099,16 +1373,31 @@ mod tests {
1099
1373
fn a_roster_without_the_own_entry_keeps_the_own_hand() {
1100
1374
let mut model = meeting_with_me();
1101
1375
model.apply(CallUpdate::OwnHand(Some(5)));
1102
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1376
model.apply(CallUpdate::Roster(vec![entry(
1377
"8:orgid:a",
1378
"Ana",
1379
false,
1380
false,
1381
)]));
1103
1382
assert_eq!(model.own_hand, Some(5));
1104
model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false)]));
1383
model.apply(CallUpdate::Roster(vec![entry(
1384
"8:orgid:me",
1385
"Me",
1386
false,
1387
false,
1388
)]));
1105
1389
assert_eq!(model.own_hand, None);
1106
1390
}
1107
1391
1108
1392
#[test]
1109
1393
fn reaction_controls_show_in_group_calls_and_meetings_only() {
1110
1394
let mut model = CallModel::test();
1111
for (kind, expected) in [(CallKind::Test, false), (CallKind::Direct, false), (CallKind::Group, true), (CallKind::Meeting, true)] {
1395
for (kind, expected) in [
1396
(CallKind::Test, false),
1397
(CallKind::Direct, false),
1398
(CallKind::Group, true),
1399
(CallKind::Meeting, true),
1400
] {
1112
1401
model.kind = kind;
1113
1402
assert_eq!(model.has_reaction_controls(), expected);
1114
1403
}
@@ -1120,12 +1409,24 @@ mod tests {
1120
1409
let start = Instant::now();
1121
1410
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1122
1411
let serial = model.reactions[0].serial;
1123
model.note_reaction("8:orgid:me".into(), Reaction::Like, start + Duration::from_millis(1500));
1412
model.note_reaction(
1413
"8:orgid:me".into(),
1414
Reaction::Like,
1415
start + Duration::from_millis(1500),
1416
);
1124
1417
assert_eq!(model.reactions.len(), 1);
1125
1418
assert_eq!(model.reactions[0].serial, serial);
1126
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_millis(1600));
1419
model.note_reaction(
1420
"8:orgid:me".into(),
1421
Reaction::Heart,
1422
start + Duration::from_millis(1600),
1423
);
1127
1424
assert_eq!(model.reactions[0].reaction, Reaction::Heart);
1128
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_secs(4));
1425
model.note_reaction(
1426
"8:orgid:me".into(),
1427
Reaction::Heart,
1428
start + Duration::from_secs(4),
1429
);
1129
1430
assert_ne!(model.reactions[0].serial, serial);
1130
1431
}
1131
1432
@@ -1135,15 +1436,25 @@ mod tests {
1135
1436
let start = Instant::now();
1136
1437
model.note_reaction("8:orgid:a".into(), Reaction::Like, start);
1137
1438
let serial = model.reactions[0].serial;
1138
model.note_reaction("8:orgid:a".into(), Reaction::Like, start + Duration::from_secs(1));
1439
model.note_reaction(
1440
"8:orgid:a".into(),
1441
Reaction::Like,
1442
start + Duration::from_secs(1),
1443
);
1139
1444
assert_ne!(model.reactions[0].serial, serial);
1140
1445
}
1141
1446
1142
1447
#[test]
1143
1448
fn lowering_clears_the_hand_everywhere() {
1144
1449
let mut model = meeting_with_me();
1145
model.apply(CallUpdate::Roster(vec![raised("8:orgid:a", "Ana", 1), raised("8:orgid:me", "Me", 2)]));
1146
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), entry("8:orgid:me", "Me", false, false)]));
1450
model.apply(CallUpdate::Roster(vec![
1451
raised("8:orgid:a", "Ana", 1),
1452
raised("8:orgid:me", "Me", 2),
1453
]));
1454
model.apply(CallUpdate::Roster(vec![
1455
entry("8:orgid:a", "Ana", false, false),
1456
entry("8:orgid:me", "Me", false, false),
1457
]));
1147
1458
assert!(!model.any_hand_raised());
1148
1459
assert_eq!(model.own_cell_index(1), 1);
1149
1460
}
@@ -1161,22 +1472,45 @@ mod tests {
1161
1472
model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);
1162
1473
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);
1163
1474
let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {
1164
model.chip_of(mri, start + Duration::from_secs(seconds)).map(|chip| chip.reaction)
1475
model
1476
.chip_of(mri, start + Duration::from_secs(seconds))
1477
.map(|chip| chip.reaction)
1165
1478
};
1166
1479
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));
1167
assert_eq!(model.own_chip(start + Duration::from_secs(2)).map(|chip| chip.reaction), Some(Reaction::Like));
1480
assert_eq!(
1481
model
1482
.own_chip(start + Duration::from_secs(2))
1483
.map(|chip| chip.reaction),
1484
Some(Reaction::Like)
1485
);
1168
1486
assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);
1169
model.note_reaction("8:orgid:a".into(), Reaction::Laugh, start + Duration::from_secs(1));
1487
model.note_reaction(
1488
"8:orgid:a".into(),
1489
Reaction::Laugh,
1490
start + Duration::from_secs(1),
1491
);
1170
1492
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));
1171
1493
assert_eq!(model.reactions.len(), 2);
1172
1494
}
1173
1495
1174
1496
#[test]
1175
1497
fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {
1176
assert_eq!(chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")), Some("19:meeting_x"));
1177
assert_eq!(chat_thread(CallKind::Meeting, None, Some("19:list")), Some("19:list"));
1178
assert_eq!(chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")), Some("19:dm"));
1179
assert_eq!(chat_thread(CallKind::Group, None, Some("19:group")), Some("19:group"));
1498
assert_eq!(
1499
chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")),
1500
Some("19:meeting_x")
1501
);
1502
assert_eq!(
1503
chat_thread(CallKind::Meeting, None, Some("19:list")),
1504
Some("19:list")
1505
);
1506
assert_eq!(
1507
chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")),
1508
Some("19:dm")
1509
);
1510
assert_eq!(
1511
chat_thread(CallKind::Group, None, Some("19:group")),
1512
Some("19:group")
1513
);
1180
1514
assert_eq!(chat_thread(CallKind::Test, None, None), None);
1181
1515
}
1182
1516
@@ -1193,19 +1527,30 @@ mod tests {
1193
1527
#[test]
1194
1528
fn lobby_guests_are_listed_for_organizers_who_may_admit() {
1195
1529
let mut model = meeting_with_me();
1196
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1530
model.apply(CallUpdate::State(CallState::Connected {
1531
since: Instant::now(),
1532
}));
1197
1533
model.apply(CallUpdate::Roster(vec![
1198
1534
entry("8:orgid:a", "Ana", false, false),
1199
1535
entry("8:orgid:g1", "Gast Eins", false, true),
1200
1536
entry("8:orgid:g2", "Gast Zwei", false, true),
1201
1537
]));
1202
let waiting: Vec<&str> = model.lobby_guests().iter().map(|tile| tile.name.as_str()).collect();
1538
let waiting: Vec<&str> = model
1539
.lobby_guests()
1540
.iter()
1541
.map(|tile| tile.name.as_str())
1542
.collect();
1203
1543
assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);
1204
1544
assert!(!model.can_admit());
1205
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me"), entry("8:orgid:g1", "Gast Eins", false, true)]));
1545
model.apply(CallUpdate::Roster(vec![
1546
organizer_entry("8:orgid:me"),
1547
entry("8:orgid:g1", "Gast Eins", false, true),
1548
]));
1206
1549
assert!(model.organizer && model.can_admit() && model.organizes_meeting());
1207
1550
let mut owner = CallModel::meeting("Standup", true);
1208
owner.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1551
owner.apply(CallUpdate::State(CallState::Connected {
1552
since: Instant::now(),
1553
}));
1209
1554
assert!(owner.can_admit());
1210
1555
owner.apply(CallUpdate::Lobby(true));
1211
1556
assert!(!owner.can_admit());
@@ -1214,33 +1559,90 @@ mod tests {
1214
1559
#[test]
1215
1560
fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {
1216
1561
let mut model = meeting_with_me();
1217
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), spotlit("8:orgid:c", "Cy", 2)]));
1218
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:c".into(), own: false, spotlight: true, pinned: false }));
1562
model.apply(CallUpdate::Roster(vec![
1563
entry("8:orgid:a", "Ana", false, false),
1564
spotlit("8:orgid:b", "Bo", 4),
1565
spotlit("8:orgid:c", "Cy", 2),
1566
]));
1567
assert_eq!(
1568
model.focus(),
1569
Some(Focus {
1570
mri: "8:orgid:c".into(),
1571
own: false,
1572
spotlight: true,
1573
pinned: false
1574
})
1575
);
1219
1576
assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));
1220
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), entry("8:orgid:c", "Cy", false, false)]));
1221
assert_eq!(model.focus().map(|focus| focus.mri), Some("8:orgid:b".to_owned()));
1222
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));
1577
model.apply(CallUpdate::Roster(vec![
1578
entry("8:orgid:a", "Ana", false, false),
1579
spotlit("8:orgid:b", "Bo", 4),
1580
entry("8:orgid:c", "Cy", false, false),
1581
]));
1582
assert_eq!(
1583
model.focus().map(|focus| focus.mri),
1584
Some("8:orgid:b".to_owned())
1585
);
1586
model.apply(CallUpdate::Roster(vec![entry(
1587
"8:orgid:a",
1588
"Ana",
1589
false,
1590
false,
1591
)]));
1223
1592
assert_eq!(model.focus(), None);
1224
1593
}
1225
1594
1226
1595
#[test]
1227
1596
fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {
1228
1597
let mut model = meeting_with_me();
1229
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:me", "Me", 1)]));
1230
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:me".into(), own: true, spotlight: true, pinned: false }));
1598
model.apply(CallUpdate::Roster(vec![
1599
entry("8:orgid:a", "Ana", false, false),
1600
spotlit("8:orgid:me", "Me", 1),
1601
]));
1602
assert_eq!(
1603
model.focus(),
1604
Some(Focus {
1605
mri: "8:orgid:me".into(),
1606
own: true,
1607
spotlight: true,
1608
pinned: false
1609
})
1610
);
1231
1611
}
1232
1612
1233
1613
#[test]
1234
1614
fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {
1235
1615
let mut model = meeting_with_me();
1236
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1237
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 1)]));
1616
model.apply(CallUpdate::State(CallState::Connected {
1617
since: Instant::now(),
1618
}));
1619
model.apply(CallUpdate::Roster(vec![
1620
entry("8:orgid:a", "Ana", false, false),
1621
spotlit("8:orgid:b", "Bo", 1),
1622
]));
1238
1623
model.toggle_pin("8:orgid:a");
1239
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:a".into(), own: false, spotlight: false, pinned: true }));
1240
let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();
1624
assert_eq!(
1625
model.focus(),
1626
Some(Focus {
1627
mri: "8:orgid:a".into(),
1628
own: false,
1629
spotlight: false,
1630
pinned: true
1631
})
1632
);
1633
let names: Vec<&str> = model
1634
.strip_tiles()
1635
.iter()
1636
.map(|tile| tile.name.as_str())
1637
.collect();
1241
1638
assert_eq!(names[0], "Ana");
1242
1639
model.toggle_pin("8:orgid:b");
1243
assert_eq!(model.focus().map(|focus| (focus.mri, focus.spotlight, focus.pinned)), Some(("8:orgid:b".to_owned(), true, true)));
1640
assert_eq!(
1641
model
1642
.focus()
1643
.map(|focus| (focus.mri, focus.spotlight, focus.pinned)),
1644
Some(("8:orgid:b".to_owned(), true, true))
1645
);
1244
1646
model.toggle_pin("8:orgid:b");
1245
1647
assert_eq!(model.pinned, None);
1246
1648
model.toggle_pin("8:orgid:a");
@@ -1249,7 +1651,13 @@ mod tests {
1249
1651
}
1250
1652
1251
1653
fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {
1252
CaptionEntry { id: id.into(), user_id: "u".into(), display_name: speaker.into(), text: text.into(), is_final }
1654
CaptionEntry {
1655
id: id.into(),
1656
user_id: "u".into(),
1657
display_name: speaker.into(),
1658
text: text.into(),
1659
is_final,
1660
}
1253
1661
}
1254
1662
1255
1663
#[test]
@@ -1263,21 +1671,45 @@ mod tests {
1263
1671
model.note_caption(caption("1", "Ana", "Hello there", true), start);
1264
1672
assert_eq!(model.caption_lines.len(), 1);
1265
1673
assert_eq!(model.caption_lines[0].text, "Hello there");
1266
model.note_caption(caption("2", "", "Next", false), start + Duration::from_secs(1));
1267
model.note_caption(caption("3", "Bo", "Third", false), start + Duration::from_secs(2));
1268
let texts: Vec<&str> = model.caption_lines.iter().map(|line| line.text.as_str()).collect();
1674
model.note_caption(
1675
caption("2", "", "Next", false),
1676
start + Duration::from_secs(1),
1677
);
1678
model.note_caption(
1679
caption("3", "Bo", "Third", false),
1680
start + Duration::from_secs(2),
1681
);
1682
let texts: Vec<&str> = model
1683
.caption_lines
1684
.iter()
1685
.map(|line| line.text.as_str())
1686
.collect();
1269
1687
assert_eq!(texts, vec!["Next", "Third"]);
1270
1688
assert_eq!(model.caption_lines[0].speaker, "Someone");
1271
assert_eq!(model.visible_captions(start + Duration::from_secs(3)).len(), 2);
1272
assert_eq!(model.visible_captions(start + Duration::from_millis(5500)).len(), 1);
1273
assert!(model.visible_captions(start + Duration::from_secs(7)).is_empty());
1689
assert_eq!(
1690
model.visible_captions(start + Duration::from_secs(3)).len(),
1691
2
1692
);
1693
assert_eq!(
1694
model
1695
.visible_captions(start + Duration::from_millis(5500))
1696
.len(),
1697
1
1698
);
1699
assert!(
1700
model
1701
.visible_captions(start + Duration::from_secs(7))
1702
.is_empty()
1703
);
1274
1704
model.apply(CallUpdate::Captions(CaptionState::Off));
1275
1705
assert!(model.caption_lines.is_empty() && !model.captions_on());
1276
1706
}
1277
1707
1278
1708
fn one_to_one() -> CallModel {
1279
1709
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);
1280
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1710
model.apply(CallUpdate::State(CallState::Connected {
1711
since: Instant::now(),
1712
}));
1281
1713
model
1282
1714
}
1283
1715
@@ -1291,13 +1723,24 @@ mod tests {
1291
1723
assert!(!model.can_hold() && !model.can_transfer());
1292
1724
let meeting = meeting_with_me();
1293
1725
assert!(!meeting.can_hold() && !meeting.can_transfer());
1294
assert!(!CallModel::people("Group", &[("8:orgid:a".into(), "A".into()), ("8:orgid:b".into(), "B".into())]).can_hold());
1726
assert!(
1727
!CallModel::people(
1728
"Group",
1729
&[
1730
("8:orgid:a".into(), "A".into()),
1731
("8:orgid:b".into(), "B".into())
1732
]
1733
)
1734
.can_hold()
1735
);
1295
1736
}
1296
1737
1297
1738
#[test]
1298
1739
fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {
1299
1740
let mut model = meeting_with_me();
1300
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));
1741
model.apply(CallUpdate::State(CallState::Connected {
1742
since: Instant::now(),
1743
}));
1301
1744
assert!(!model.can_record());
1302
1745
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));
1303
1746
assert!(model.can_record());
@@ -1313,7 +1756,12 @@ mod tests {
1313
1756
#[test]
1314
1757
fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {
1315
1758
let mut model = meeting_with_me();
1316
model.apply(CallUpdate::Roster(vec![entry("8:orgid:ana", "Ana", false, false)]));
1759
model.apply(CallUpdate::Roster(vec![entry(
1760
"8:orgid:ana",
1761
"Ana",
1762
false,
1763
false,
1764
)]));
1317
1765
assert_eq!(model.whiteboard_label(), None);
1318
1766
let share = |presenter: &str, url: Option<&str>| calling::ContentShare {
1319
1767
session_id: "s".into(),
@@ -1322,11 +1770,26 @@ mod tests {
1322
1770
url: url.map(str::to_owned),
1323
1771
whiteboard: true,
1324
1772
};
1325
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:ana", Some("https://app.whiteboard.microsoft.com/x")))));
1326
assert_eq!(model.whiteboard_label().as_deref(), Some("Ana is sharing a whiteboard"));
1327
assert_eq!(model.whiteboard_url(), Some("https://app.whiteboard.microsoft.com/x"));
1328
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:stranger", None))));
1329
assert_eq!(model.whiteboard_label().as_deref(), Some("Someone is sharing a whiteboard"));
1773
model.apply(CallUpdate::Whiteboard(Some(share(
1774
"8:orgid:ana",
1775
Some("https://app.whiteboard.microsoft.com/x"),
1776
))));
1777
assert_eq!(
1778
model.whiteboard_label().as_deref(),
1779
Some("Ana is sharing a whiteboard")
1780
);
1781
assert_eq!(
1782
model.whiteboard_url(),
1783
Some("https://app.whiteboard.microsoft.com/x")
1784
);
1785
model.apply(CallUpdate::Whiteboard(Some(share(
1786
"8:orgid:stranger",
1787
None,
1788
))));
1789
assert_eq!(
1790
model.whiteboard_label().as_deref(),
1791
Some("Someone is sharing a whiteboard")
1792
);
1330
1793
assert_eq!(model.whiteboard_url(), None);
1331
1794
model.apply(CallUpdate::Whiteboard(None));
1332
1795
assert_eq!(model.whiteboard_label(), None);
@@ -1345,7 +1808,9 @@ mod tests {
1345
1808
};
1346
1809
assert_eq!(consult.status_text(), "Calling Ana...");
1347
1810
assert!(!consult.ready_to_transfer());
1348
consult.state = CallState::Connected { since: Instant::now() };
1811
consult.state = CallState::Connected {
1812
since: Instant::now(),
1813
};
1349
1814
assert_eq!(consult.status_text(), "Consulting Ana");
1350
1815
assert!(!consult.ready_to_transfer());
1351
1816
consult.replacement = Some("https://cc/replacement".into());
@@ -2,8 +2,9 @@ use std::sync::Arc;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use calling::{4
use calling::{5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare, DeviceChoice, DeviceLists, EndKind, EndReason,5
CallCommand, CallState, CallUpdate, CameraDevice, CaptionEntry, CaptionState, ContentShare,6
HoldState, MeetingTarget, Progress, Reaction, RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,6
DeviceChoice, DeviceLists, EndKind, EndReason, HoldState, MeetingTarget, Progress, Reaction,7
RosterEntry, ShareKind, ShareSource, SpeakingDetector, VideoHub,7
};8
};8
use tokio::sync::mpsc::UnboundedSender;9
use tokio::sync::mpsc::UnboundedSender;9
10
@@ -73,7 +74,13 @@ impl ConsultCall {73
}74
}74
75
75
impl ActiveCall {76
impl ActiveCall {76
pub fn new(id: u64, model: CallModel, commands: UnboundedSender<CallCommand>, conversation_id: Option<String>, video: Arc<VideoHub>) -> Self {77
pub fn new(78
id: u64,79
model: CallModel,80
commands: UnboundedSender<CallCommand>,81
conversation_id: Option<String>,82
video: Arc<VideoHub>,83
) -> Self {77
ActiveCall {84
ActiveCall {78
id,85
id,79
model,86
model,@@ -91,11 +98,19 @@ impl ActiveCall {91
}98
}92
99
93
pub fn chat_thread(&self) -> Option<&str> {100
pub fn chat_thread(&self) -> Option<&str> {94
chat_thread(self.model.kind, self.model.meeting_chat.as_deref(), self.conversation_id.as_deref())101
chat_thread(102
self.model.kind,103
self.model.meeting_chat.as_deref(),104
self.conversation_id.as_deref(),105
)95
}106
}96
}107
}97
108
98
pub fn chat_thread<'a>(kind: CallKind, meeting_chat: Option<&'a str>, conversation_id: Option<&'a str>) -> Option<&'a str> {109
pub fn chat_thread<'a>(110
kind: CallKind,111
meeting_chat: Option<&'a str>,112
conversation_id: Option<&'a str>,113
) -> Option<&'a str> {99
match kind {114
match kind {100
CallKind::Meeting => meeting_chat.or(conversation_id),115
CallKind::Meeting => meeting_chat.or(conversation_id),101
CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,116
CallKind::Test | CallKind::Direct | CallKind::Group => conversation_id,@@ -336,12 +351,19 @@ impl CallModel {336
}351
}337
352
338
pub fn people(title: &str, callees: &[(String, String)]) -> Self {353
pub fn people(title: &str, callees: &[(String, String)]) -> Self {339
let kind = if callees.len() == 1 { CallKind::Direct } else { CallKind::Group };354
let kind = if callees.len() == 1 {355
CallKind::Direct356
} else {357
CallKind::Group358
};340
let peer_name = match callees {359
let peer_name = match callees {341
[(_, name)] => name.clone(),360
[(_, name)] => name.clone(),342
_ => title.to_owned(),361
_ => title.to_owned(),343
};362
};344
let tiles = callees.iter().map(|(mri, name)| Tile::invited(mri, name)).collect();363
let tiles = callees364
.iter()365
.map(|(mri, name)| Tile::invited(mri, name))366
.collect();345
Self::base(kind, title, &peer_name, tiles)367
Self::base(kind, title, &peer_name, tiles)346
}368
}347
369
@@ -412,7 +434,9 @@ impl CallModel {412
CallUpdate::ShareSources(sources) => self.share_sources = sources,434
CallUpdate::ShareSources(sources) => self.share_sources = sources,413
CallUpdate::ShareSound(active) => self.share_sound = active,435
CallUpdate::ShareSound(active) => self.share_sound = active,414
CallUpdate::OwnHand(rank) => self.own_hand = rank,436
CallUpdate::OwnHand(rank) => self.own_hand = rank,415
CallUpdate::Reaction { mri, reaction } => self.note_reaction(mri, reaction, Instant::now()),437
CallUpdate::Reaction { mri, reaction } => {438
self.note_reaction(mri, reaction, Instant::now())439
}416
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),440
CallUpdate::MeetingChat(thread) => self.meeting_chat = Some(thread),417
CallUpdate::Captions(state) => {441
CallUpdate::Captions(state) => {418
if state != CaptionState::On {442
if state != CaptionState::On {@@ -438,8 +462,17 @@ impl CallModel {438
if self.captions == CaptionState::Off {462
if self.captions == CaptionState::Off {439
return;463
return;440
}464
}441
let speaker = if entry.display_name.is_empty() { "Someone".to_owned() } else { entry.display_name };465
let speaker = if entry.display_name.is_empty() {442
let line = CaptionLine { id: entry.id, speaker, text: entry.text, at };466
"Someone".to_owned()467
} else {468
entry.display_name469
};470
let line = CaptionLine {471
id: entry.id,472
speaker,473
text: entry.text,474
at,475
};443
match self.caption_lines.last_mut() {476
match self.caption_lines.last_mut() {444
Some(last) if last.id == line.id => *last = line,477
Some(last) if last.id == line.id => *last = line,445
_ => self.caption_lines.push(line),478
_ => self.caption_lines.push(line),@@ -449,7 +482,10 @@ impl CallModel {449
}482
}450
483
451
pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {484
pub fn visible_captions(&self, now: Instant) -> Vec<&CaptionLine> {452
self.caption_lines.iter().filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN).collect()485
self.caption_lines486
.iter()487
.filter(|line| now.saturating_duration_since(line.at) < CAPTION_SHOWN)488
.collect()453
}489
}454
490
455
pub fn captions_on(&self) -> bool {491
pub fn captions_on(&self) -> bool {@@ -467,20 +503,29 @@ impl CallModel {467
pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {503
pub fn note_reaction(&mut self, mri: String, reaction: Reaction, at: Instant) {468
let own_echo = Some(&mri) == self.own_mri.as_ref()504
let own_echo = Some(&mri) == self.own_mri.as_ref()469
&& self.reactions.iter().any(|chip| {505
&& self.reactions.iter().any(|chip| {470
chip.mri == mri && chip.reaction == reaction && at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW506
chip.mri == mri507
&& chip.reaction == reaction508
&& at.saturating_duration_since(chip.since) < OWN_ECHO_WINDOW471
});509
});472
if own_echo {510
if own_echo {473
return;511
return;474
}512
}475
self.reactions.retain(|chip| chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN);513
self.reactions.retain(|chip| {514
chip.mri != mri && at.saturating_duration_since(chip.since) < REACTION_SHOWN515
});476
self.reaction_serial += 1;516
self.reaction_serial += 1;477
self.reactions.push(ReactionChip { mri, reaction, since: at, serial: self.reaction_serial });517
self.reactions.push(ReactionChip {518
mri,519
reaction,520
since: at,521
serial: self.reaction_serial,522
});478
}523
}479
524
480
pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {525
pub fn chip_of(&self, mri: &str, now: Instant) -> Option<&ReactionChip> {481
self.reactions526
self.reactions.iter().find(|chip| {482
.iter()527
chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN483
.find(|chip| chip.mri == mri && now.saturating_duration_since(chip.since) < REACTION_SHOWN)528
})484
}529
}485
530
486
pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {531
pub fn own_chip(&self, now: Instant) -> Option<&ReactionChip> {@@ -488,7 +533,11 @@ impl CallModel {488
}533
}489
534
490
pub fn hand_position(&self, rank: u64) -> usize {535
pub fn hand_position(&self, rank: u64) -> usize {491
let raised = self.tiles.iter().filter_map(|tile| tile.hand).chain(self.own_hand);536
let raised = self537
.tiles538
.iter()539
.filter_map(|tile| tile.hand)540
.chain(self.own_hand);492
1 + raised.filter(|other| *other < rank).count()541
1 + raised.filter(|other| *other < rank).count()493
}542
}494
543
@@ -505,7 +554,10 @@ impl CallModel {505
}554
}506
555
507
pub fn lobby_guests(&self) -> Vec<&Tile> {556
pub fn lobby_guests(&self) -> Vec<&Tile> {508
self.tiles.iter().filter(|tile| tile.state == TileState::InLobby).collect()557
self.tiles558
.iter()559
.filter(|tile| tile.state == TileState::InLobby)560
.collect()509
}561
}510
562
511
pub fn can_admit(&self) -> bool {563
pub fn can_admit(&self) -> bool {@@ -517,23 +569,52 @@ impl CallModel {517
}569
}518
570
519
pub fn toggle_pin(&mut self, mri: &str) {571
pub fn toggle_pin(&mut self, mri: &str) {520
self.pinned = if self.is_pinned(mri) { None } else { Some(mri.to_owned()) };572
self.pinned = if self.is_pinned(mri) {573
None574
} else {575
Some(mri.to_owned())576
};521
}577
}522
578
523
pub fn is_spotlighted(&self, mri: &str) -> bool {579
pub fn is_spotlighted(&self, mri: &str) -> bool {524
self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()580
self.own_mri.as_deref() == Some(mri) && self.own_spotlight.is_some()525
|| self.tiles.iter().any(|tile| tile.mri == mri && tile.spotlight.is_some())581
|| self582
.tiles583
.iter()584
.any(|tile| tile.mri == mri && tile.spotlight.is_some())526
}585
}527
586
528
pub fn focus(&self) -> Option<Focus> {587
pub fn focus(&self) -> Option<Focus> {529
let own = |mri: &str| self.own_mri.as_deref() == Some(mri);588
let own = |mri: &str| self.own_mri.as_deref() == Some(mri);530
let on_stage = |mri: &str| own(mri) || self.visible_tiles().iter().any(|tile| tile.mri == mri && tile.state == TileState::Present);589
let on_stage = |mri: &str| {590
own(mri)591
|| self592
.visible_tiles()593
.iter()594
.any(|tile| tile.mri == mri && tile.state == TileState::Present)595
};531
if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {596
if let Some(pinned) = self.pinned.as_deref().filter(|mri| on_stage(mri)) {532
return Some(Focus { mri: pinned.to_owned(), own: own(pinned), spotlight: self.is_spotlighted(pinned), pinned: true });597
return Some(Focus {598
mri: pinned.to_owned(),599
own: own(pinned),600
spotlight: self.is_spotlighted(pinned),601
pinned: true,602
});533
}603
}534
let remote = self.tiles.iter().filter(|tile| tile.state == TileState::Present).filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));604
let remote = self535
let (_, mri) = remote.chain(self.own_spotlight.zip(self.own_mri.as_deref())).min_by_key(|(rank, _)| *rank)?;605
.tiles536
Some(Focus { mri: mri.to_owned(), own: own(mri), spotlight: true, pinned: false })606
.iter()607
.filter(|tile| tile.state == TileState::Present)608
.filter_map(|tile| Some((tile.spotlight?, tile.mri.as_str())));609
let (_, mri) = remote610
.chain(self.own_spotlight.zip(self.own_mri.as_deref()))611
.min_by_key(|(rank, _)| *rank)?;612
Some(Focus {613
mri: mri.to_owned(),614
own: own(mri),615
spotlight: true,616
pinned: false,617
})537
}618
}538
619
539
pub fn any_hand_raised(&self) -> bool {620
pub fn any_hand_raised(&self) -> bool {@@ -541,22 +622,38 @@ impl CallModel {541
}622
}542
623
543
pub fn own_cell_index(&self, remote_cells: usize) -> usize {624
pub fn own_cell_index(&self, remote_cells: usize) -> usize {544
let Some(own) = self.own_hand else { return remote_cells };625
let Some(own) = self.own_hand else {545
let ahead = self.visible_tiles().iter().filter(|tile| tile.hand.is_some_and(|rank| rank < own)).count();626
return remote_cells;627
};628
let ahead = self629
.visible_tiles()630
.iter()631
.filter(|tile| tile.hand.is_some_and(|rank| rank < own))632
.count();546
ahead.min(remote_cells)633
ahead.min(remote_cells)547
}634
}548
635
549
fn apply_roster(&mut self, entries: &[RosterEntry]) {636
fn apply_roster(&mut self, entries: &[RosterEntry]) {550
let own_entry = entries.iter().find(|entry| Some(&entry.mri) == self.own_mri.as_ref());637
let own_entry = entries638
.iter()639
.find(|entry| Some(&entry.mri) == self.own_mri.as_ref());551
if let Some(entry) = own_entry {640
if let Some(entry) = own_entry {552
self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);641
self.own_hand = entry.hand.as_ref().map(|hand| hand.rank);553
}642
}554
self.own_spotlight = own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));643
self.own_spotlight =644
own_entry.and_then(|entry| entry.spotlight.as_ref().map(|spotlight| spotlight.rank));555
if let Some(entry) = own_entry {645
if let Some(entry) = own_entry {556
self.organizer = entry.organizer;646
self.organizer = entry.organizer;557
}647
}558
for entry in entries.iter().filter(|entry| Some(&entry.mri) != self.own_mri.as_ref()) {648
for entry in entries559
let state = if entry.in_lobby { TileState::InLobby } else { TileState::Present };649
.iter()650
.filter(|entry| Some(&entry.mri) != self.own_mri.as_ref())651
{652
let state = if entry.in_lobby {653
TileState::InLobby654
} else {655
TileState::Present656
};560
match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {657
match self.tiles.iter_mut().find(|tile| tile.mri == entry.mri) {561
Some(tile) => {658
Some(tile) => {562
tile.state = state;659
tile.state = state;@@ -583,7 +680,11 @@ impl CallModel {583
}680
}584
let own_mri = self.own_mri.clone();681
let own_mri = self.own_mri.clone();585
let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);682
let listed = |mri: &str| entries.iter().any(|entry| entry.mri == mri);586
if self.pinned.as_deref().is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref()) {683
if self684
.pinned685
.as_deref()686
.is_some_and(|mri| !listed(mri) && Some(mri) != own_mri.as_deref())687
{587
self.pinned = None;688
self.pinned = None;588
}689
}589
self.tiles.retain_mut(|tile| {690
self.tiles.retain_mut(|tile| {@@ -602,21 +703,37 @@ impl CallModel {602
}703
}603
704
604
pub fn visible_tiles(&self) -> Vec<&Tile> {705
pub fn visible_tiles(&self) -> Vec<&Tile> {605
let mut tiles: Vec<&Tile> = self.tiles.iter().filter(|tile| tile.state != TileState::InLobby).collect();706
let mut tiles: Vec<&Tile> = self707
.tiles708
.iter()709
.filter(|tile| tile.state != TileState::InLobby)710
.collect();606
tiles.sort_by_key(|tile| {711
tiles.sort_by_key(|tile| {607
let state = match tile.state {712
let state = match tile.state {608
TileState::Present => 0,713
TileState::Present => 0,609
TileState::Invited => 1,714
TileState::Invited => 1,610
_ => 2,715
_ => 2,611
};716
};612
(!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), state)717
(718
!self.is_pinned(&tile.mri),719
tile.hand.is_none(),720
tile.hand.unwrap_or(0),721
state,722
)613
});723
});614
tiles724
tiles615
}725
}616
726
617
pub fn strip_tiles(&self) -> Vec<&Tile> {727
pub fn strip_tiles(&self) -> Vec<&Tile> {618
let mut tiles = self.visible_tiles();728
let mut tiles = self.visible_tiles();619
tiles.sort_by_key(|tile| (!self.is_pinned(&tile.mri), tile.hand.is_none(), tile.hand.unwrap_or(0), !self.tile_speaking(tile)));729
tiles.sort_by_key(|tile| {730
(731
!self.is_pinned(&tile.mri),732
tile.hand.is_none(),733
tile.hand.unwrap_or(0),734
!self.tile_speaking(tile),735
)736
});620
tiles737
tiles621
}738
}622
739
@@ -744,15 +861,24 @@ impl CallModel {744
}861
}745
862
746
fn is_live(&self) -> bool {863
fn is_live(&self) -> bool {747
matches!(self.state, CallState::Connected { .. } | CallState::Reconnecting { .. })864
matches!(865
self.state,866
CallState::Connected { .. } | CallState::Reconnecting { .. }867
)748
}868
}749
869
750
pub fn screens(&self) -> Vec<&ShareSource> {870
pub fn screens(&self) -> Vec<&ShareSource> {751
self.share_sources.iter().filter(|source| source.kind == ShareKind::Screen).collect()871
self.share_sources872
.iter()873
.filter(|source| source.kind == ShareKind::Screen)874
.collect()752
}875
}753
876
754
pub fn windows(&self) -> Vec<&ShareSource> {877
pub fn windows(&self) -> Vec<&ShareSource> {755
self.share_sources.iter().filter(|source| source.kind == ShareKind::Window).collect()878
self.share_sources879
.iter()880
.filter(|source| source.kind == ShareKind::Window)881
.collect()756
}882
}757
883
758
pub fn can_unmute(&self) -> bool {884
pub fn can_unmute(&self) -> bool {@@ -815,25 +941,36 @@ mod tests {815
941
816
fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {942
fn spotlit(mri: &str, name: &str, rank: u64) -> RosterEntry {817
RosterEntry {943
RosterEntry {818
spotlight: Some(calling::Spotlight { state_id: format!("sp-{rank}"), rank }),944
spotlight: Some(calling::Spotlight {945
state_id: format!("sp-{rank}"),946
rank,947
}),819
..entry(mri, name, false, false)948
..entry(mri, name, false, false)820
}949
}821
}950
}822
951
823
fn organizer_entry(mri: &str) -> RosterEntry {952
fn organizer_entry(mri: &str) -> RosterEntry {824
RosterEntry { organizer: true, ..entry(mri, "Me", false, false) }953
RosterEntry {954
organizer: true,955
..entry(mri, "Me", false, false)956
}825
}957
}826
958
827
fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {959
fn raised(mri: &str, name: &str, rank: u64) -> RosterEntry {828
RosterEntry {960
RosterEntry {829
hand: Some(calling::RaisedHand { state_id: format!("s-{rank}"), rank }),961
hand: Some(calling::RaisedHand {962
state_id: format!("s-{rank}"),963
rank,964
}),830
..entry(mri, name, false, false)965
..entry(mri, name, false, false)831
}966
}832
}967
}833
968
834
fn meeting_with_me() -> CallModel {969
fn meeting_with_me() -> CallModel {835
let mut model = CallModel::meeting("Standup", false);970
let mut model = CallModel::meeting("Standup", false);836
model.apply(CallUpdate::OwnIdentity { mri: "8:orgid:me".into() });971
model.apply(CallUpdate::OwnIdentity {972
mri: "8:orgid:me".into(),973
});837
model974
model838
}975
}839
976
@@ -896,17 +1033,44 @@ mod tests {896
let elapsed = Some(Duration::from_secs(42));1033
let elapsed = Some(Duration::from_secs(42));897
let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");1034
let notice = |reason: EndReason, elapsed| ended_notice(&reason, elapsed, "Bea");898
assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");1035
assert_eq!(notice(EndReason::LocalHangup, elapsed), "Call ended 00:42");899
assert_eq!(notice(EndReason::Remote(EndKind::Normal), elapsed), "Call ended 00:42");1036
assert_eq!(900
assert_eq!(notice(EndReason::Remote(EndKind::Normal), None), "Call ended");1037
notice(EndReason::Remote(EndKind::Normal), elapsed),1038
"Call ended 00:42"1039
);1040
assert_eq!(1041
notice(EndReason::Remote(EndKind::Normal), None),1042
"Call ended"1043
);901
assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");1044
assert_eq!(notice(EndReason::Cancelled, None), "Call cancelled");902
assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");1045
assert_eq!(notice(EndReason::Dropped, elapsed), "Call dropped");903
assert_eq!(notice(EndReason::Failed("no route".into()), None), "Call failed: no route");1046
assert_eq!(904
assert_eq!(notice(EndReason::Remote(EndKind::Declined), None), "Bea declined");1047
notice(EndReason::Failed("no route".into()), None),905
assert_eq!(notice(EndReason::Remote(EndKind::NoAnswer), None), "No answer");1048
"Call failed: no route"906
assert_eq!(notice(EndReason::Remote(EndKind::Unavailable), None), "Bea is not available");1049
);907
assert_eq!(notice(EndReason::Remote(EndKind::Cancelled), None), "Call ended");1050
assert_eq!(908
assert_eq!(notice(EndReason::Remote(EndKind::Other), None), "Call ended");1051
notice(EndReason::Remote(EndKind::Declined), None),909
assert_eq!(notice(EndReason::Remote(EndKind::AnsweredElsewhere), None), "Call ended");1052
"Bea declined"1053
);1054
assert_eq!(1055
notice(EndReason::Remote(EndKind::NoAnswer), None),1056
"No answer"1057
);1058
assert_eq!(1059
notice(EndReason::Remote(EndKind::Unavailable), None),1060
"Bea is not available"1061
);1062
assert_eq!(1063
notice(EndReason::Remote(EndKind::Cancelled), None),1064
"Call ended"1065
);1066
assert_eq!(1067
notice(EndReason::Remote(EndKind::Other), None),1068
"Call ended"1069
);1070
assert_eq!(1071
notice(EndReason::Remote(EndKind::AnsweredElsewhere), None),1072
"Call ended"1073
);910
}1074
}911
1075
912
#[test]1076
#[test]@@ -915,8 +1079,14 @@ mod tests {915
assert_eq!(direct.connecting_text(), "Calling...");1079
assert_eq!(direct.connecting_text(), "Calling...");916
direct.apply(CallUpdate::Progress(Progress::Ringing));1080
direct.apply(CallUpdate::Progress(Progress::Ringing));917
assert_eq!(direct.connecting_text(), "Ringing");1081
assert_eq!(direct.connecting_text(), "Ringing");918
assert_eq!(CallModel::meeting("Standup", false).connecting_text(), "Joining...");1082
assert_eq!(919
assert_eq!(CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(), "Connecting...");1083
CallModel::meeting("Standup", false).connecting_text(),1084
"Joining..."1085
);1086
assert_eq!(1087
CallModel::incoming("Bea", "8:orgid:b", "Bea").connecting_text(),1088
"Connecting..."1089
);920
assert_eq!(CallModel::test().connecting_text(), "Calling...");1090
assert_eq!(CallModel::test().connecting_text(), "Calling...");921
}1091
}922
1092
@@ -936,7 +1106,12 @@ mod tests {936
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));1106
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Calling..."));937
model.apply(CallUpdate::Progress(Progress::Ringing));1107
model.apply(CallUpdate::Progress(Progress::Ringing));938
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));1108
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Ringing"));939
model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));1109
model.apply(CallUpdate::Roster(vec![entry(1110
"8:orgid:b",1111
"Bea",1112
false,1113
false,1114
)]));940
assert_eq!(model.tiles[0].state, TileState::Present);1115
assert_eq!(model.tiles[0].state, TileState::Present);941
assert_eq!(model.tile_caption(&model.tiles[0]), None);1116
assert_eq!(model.tile_caption(&model.tiles[0]), None);942
}1117
}@@ -945,7 +1120,10 @@ mod tests {945
fn several_callees_make_a_group_call_named_after_the_chat() {1120
fn several_callees_make_a_group_call_named_after_the_chat() {946
let model = CallModel::people(1121
let model = CallModel::people(947
"Retro team",1122
"Retro team",948
&[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],1123
&[1124
("8:orgid:b".into(), "Bea".into()),1125
("8:orgid:c".into(), "Cy".into()),1126
],949
);1127
);950
assert_eq!(model.kind, CallKind::Group);1128
assert_eq!(model.kind, CallKind::Group);951
assert_eq!(model.peer_name, "Retro team");1129
assert_eq!(model.peer_name, "Retro team");@@ -961,8 +1139,18 @@ mod tests {961
entry("8:orgid:b", "Bo", false, false),1139
entry("8:orgid:b", "Bo", false, false),962
]));1140
]));963
assert_eq!(model.tiles.len(), 2);1141
assert_eq!(model.tiles.len(), 2);964
assert!(model.tiles.iter().find(|tile| tile.name == "Ana").unwrap().muted);1142
assert!(965
model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false), entry("8:orgid:b", "Bo", false, false)]));1143
model1144
.tiles1145
.iter()1146
.find(|tile| tile.name == "Ana")1147
.unwrap()1148
.muted1149
);1150
model.apply(CallUpdate::Roster(vec![1151
entry("8:orgid:me", "Me", false, false),1152
entry("8:orgid:b", "Bo", false, false),1153
]));966
assert_eq!(model.tiles.len(), 1);1154
assert_eq!(model.tiles.len(), 1);967
assert_eq!(model.tiles[0].name, "Bo");1155
assert_eq!(model.tiles[0].name, "Bo");968
}1156
}@@ -970,7 +1158,12 @@ mod tests {970
#[test]1158
#[test]971
fn an_invited_callee_who_leaves_stays_as_left() {1159
fn an_invited_callee_who_leaves_stays_as_left() {972
let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);1160
let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);973
model.apply(CallUpdate::Roster(vec![entry("8:orgid:b", "Bea", false, false)]));1161
model.apply(CallUpdate::Roster(vec![entry(1162
"8:orgid:b",1163
"Bea",1164
false,1165
false,1166
)]));974
model.apply(CallUpdate::Roster(Vec::new()));1167
model.apply(CallUpdate::Roster(Vec::new()));975
assert_eq!(model.tiles[0].state, TileState::Left);1168
assert_eq!(model.tiles[0].state, TileState::Left);976
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));1169
assert_eq!(model.tile_caption(&model.tiles[0]), Some("Left"));@@ -983,7 +1176,11 @@ mod tests {983
entry("8:orgid:a", "Ana", false, false),1176
entry("8:orgid:a", "Ana", false, false),984
entry("8:orgid:g", "Guest", false, true),1177
entry("8:orgid:g", "Guest", false, true),985
]));1178
]));986
let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();1179
let names: Vec<&str> = model1180
.visible_tiles()1181
.iter()1182
.map(|tile| tile.name.as_str())1183
.collect();987
assert_eq!(names, vec!["Ana"]);1184
assert_eq!(names, vec!["Ana"]);988
}1185
}989
1186
@@ -1003,29 +1200,72 @@ mod tests {1003
entry("8:orgid:a", "Ana", false, false),1200
entry("8:orgid:a", "Ana", false, false),1004
entry("8:orgid:b", "Bo", false, false),1201
entry("8:orgid:b", "Bo", false, false),1005
]));1202
]));1006
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1203
model.apply(CallUpdate::State(CallState::Connected {1204
since: Instant::now(),1205
}));1007
model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));1206
model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));1008
let tiles: Vec<Tile> = model.tiles.clone();1207
let tiles: Vec<Tile> = model.tiles.clone();1009
assert!(!model.tile_speaking(&tiles[0]));1208
assert!(!model.tile_speaking(&tiles[0]));1010
assert!(model.tile_speaking(&tiles[1]));1209
assert!(model.tile_speaking(&tiles[1]));1011
let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);1210
let mut lone = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);1012
lone.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1211
lone.apply(CallUpdate::State(CallState::Connected {1013
lone.apply(CallUpdate::Levels { local: 0.0, remote: 0.5 });1212
since: Instant::now(),1213
}));1214
lone.apply(CallUpdate::Levels {1215
local: 0.0,1216
remote: 0.5,1217
});1014
assert!(lone.tile_speaking(&lone.tiles[0].clone()));1218
assert!(lone.tile_speaking(&lone.tiles[0].clone()));1015
}1219
}1016
1220
1017
#[test]1221
#[test]1018
fn more_than_nine_cells_collapse_into_a_plus_n_tile() {1222
fn more_than_nine_cells_collapse_into_a_plus_n_tile() {1019
assert_eq!(grid_layout(0, MAX_TILES), GridLayout { shown_others: 0, hidden: 0 });1223
assert_eq!(1020
assert_eq!(grid_layout(8, MAX_TILES), GridLayout { shown_others: 8, hidden: 0 });1224
grid_layout(0, MAX_TILES),1021
assert_eq!(grid_layout(9, MAX_TILES), GridLayout { shown_others: 7, hidden: 2 });1225
GridLayout {1022
assert_eq!(grid_layout(30, MAX_TILES), GridLayout { shown_others: 7, hidden: 23 });1226
shown_others: 0,1227
hidden: 01228
}1229
);1230
assert_eq!(1231
grid_layout(8, MAX_TILES),1232
GridLayout {1233
shown_others: 8,1234
hidden: 01235
}1236
);1237
assert_eq!(1238
grid_layout(9, MAX_TILES),1239
GridLayout {1240
shown_others: 7,1241
hidden: 21242
}1243
);1244
assert_eq!(1245
grid_layout(30, MAX_TILES),1246
GridLayout {1247
shown_others: 7,1248
hidden: 231249
}1250
);1023
}1251
}1024
1252
1025
#[test]1253
#[test]1026
fn an_open_chat_panel_leaves_room_for_fewer_tiles() {1254
fn an_open_chat_panel_leaves_room_for_fewer_tiles() {1027
assert_eq!(grid_layout(5, CHAT_OPEN_TILES), GridLayout { shown_others: 5, hidden: 0 });1255
assert_eq!(1028
assert_eq!(grid_layout(6, CHAT_OPEN_TILES), GridLayout { shown_others: 4, hidden: 2 });1256
grid_layout(5, CHAT_OPEN_TILES),1257
GridLayout {1258
shown_others: 5,1259
hidden: 01260
}1261
);1262
assert_eq!(1263
grid_layout(6, CHAT_OPEN_TILES),1264
GridLayout {1265
shown_others: 4,1266
hidden: 21267
}1268
);1029
}1269
}1030
1270
1031
#[test]1271
#[test]@@ -1045,9 +1285,15 @@ mod tests {1045
assert_eq!(model.sharing_label(), None);1285
assert_eq!(model.sharing_label(), None);1046
model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));1286
model.apply(CallUpdate::ScreenShare(Some("8:orgid:b".into())));1047
assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));1287
assert_eq!(model.sharing_label().as_deref(), Some("Bo is sharing"));1048
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1288
model.apply(CallUpdate::State(CallState::Connected {1289
since: Instant::now(),1290
}));1049
model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));1291
model.apply(CallUpdate::Speakers(vec!["8:orgid:b".into()]));1050
let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();1292
let names: Vec<&str> = model1293
.strip_tiles()1294
.iter()1295
.map(|tile| tile.name.as_str())1296
.collect();1051
assert_eq!(names, vec!["Bo", "Ana"]);1297
assert_eq!(names, vec!["Bo", "Ana"]);1052
model.apply(CallUpdate::ScreenShare(None));1298
model.apply(CallUpdate::ScreenShare(None));1053
assert_eq!(model.sharing_label(), None);1299
assert_eq!(model.sharing_label(), None);@@ -1060,7 +1306,12 @@ mod tests {1060
with_camera.has_video = true;1306
with_camera.has_video = true;1061
model.apply(CallUpdate::Roster(vec![with_camera]));1307
model.apply(CallUpdate::Roster(vec![with_camera]));1062
assert!(model.tiles[0].has_video);1308
assert!(model.tiles[0].has_video);1063
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));1309
model.apply(CallUpdate::Roster(vec![entry(1310
"8:orgid:a",1311
"Ana",1312
false,1313
false,1314
)]));1064
assert!(!model.tiles[0].has_video);1315
assert!(!model.tiles[0].has_video);1065
}1316
}1066
1317
@@ -1068,10 +1319,22 @@ mod tests {1068
fn present_guests_sort_before_waiting_ones() {1319
fn present_guests_sort_before_waiting_ones() {1069
let mut model = CallModel::people(1320
let mut model = CallModel::people(1070
"Group",1321
"Group",1071
&[("8:orgid:b".into(), "Bea".into()), ("8:orgid:c".into(), "Cy".into())],1322
&[1323
("8:orgid:b".into(), "Bea".into()),1324
("8:orgid:c".into(), "Cy".into()),1325
],1072
);1326
);1073
model.apply(CallUpdate::Roster(vec![entry("8:orgid:c", "Cy", false, false)]));1327
model.apply(CallUpdate::Roster(vec![entry(1074
let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();1328
"8:orgid:c",1329
"Cy",1330
false,1331
false,1332
)]));1333
let names: Vec<&str> = model1334
.visible_tiles()1335
.iter()1336
.map(|tile| tile.name.as_str())1337
.collect();1075
assert_eq!(names, vec!["Cy", "Bea"]);1338
assert_eq!(names, vec!["Cy", "Bea"]);1076
}1339
}1077
1340
@@ -1086,12 +1349,23 @@ mod tests {1086
]));1349
]));1087
assert_eq!(model.own_hand, Some(6));1350
assert_eq!(model.own_hand, Some(6));1088
assert!(model.any_hand_raised());1351
assert!(model.any_hand_raised());1089
let names: Vec<&str> = model.visible_tiles().iter().map(|tile| tile.name.as_str()).collect();1352
let names: Vec<&str> = model1353
.visible_tiles()1354
.iter()1355
.map(|tile| tile.name.as_str())1356
.collect();1090
assert_eq!(names, vec!["Cy", "Bo", "Ana"]);1357
assert_eq!(names, vec!["Cy", "Bo", "Ana"]);1091
let positions: Vec<usize> = [4, 6, 9].into_iter().map(|rank| model.hand_position(rank)).collect();1358
let positions: Vec<usize> = [4, 6, 9]1359
.into_iter()1360
.map(|rank| model.hand_position(rank))1361
.collect();1092
assert_eq!(positions, vec![1, 2, 3]);1362
assert_eq!(positions, vec![1, 2, 3]);1093
assert_eq!(model.own_cell_index(3), 1);1363
assert_eq!(model.own_cell_index(3), 1);1094
let strip: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();1364
let strip: Vec<&str> = model1365
.strip_tiles()1366
.iter()1367
.map(|tile| tile.name.as_str())1368
.collect();1095
assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);1369
assert_eq!(strip, vec!["Cy", "Bo", "Ana"]);1096
}1370
}1097
1371
@@ -1099,16 +1373,31 @@ mod tests {1099
fn a_roster_without_the_own_entry_keeps_the_own_hand() {1373
fn a_roster_without_the_own_entry_keeps_the_own_hand() {1100
let mut model = meeting_with_me();1374
let mut model = meeting_with_me();1101
model.apply(CallUpdate::OwnHand(Some(5)));1375
model.apply(CallUpdate::OwnHand(Some(5)));1102
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));1376
model.apply(CallUpdate::Roster(vec![entry(1377
"8:orgid:a",1378
"Ana",1379
false,1380
false,1381
)]));1103
assert_eq!(model.own_hand, Some(5));1382
assert_eq!(model.own_hand, Some(5));1104
model.apply(CallUpdate::Roster(vec![entry("8:orgid:me", "Me", false, false)]));1383
model.apply(CallUpdate::Roster(vec![entry(1384
"8:orgid:me",1385
"Me",1386
false,1387
false,1388
)]));1105
assert_eq!(model.own_hand, None);1389
assert_eq!(model.own_hand, None);1106
}1390
}1107
1391
1108
#[test]1392
#[test]1109
fn reaction_controls_show_in_group_calls_and_meetings_only() {1393
fn reaction_controls_show_in_group_calls_and_meetings_only() {1110
let mut model = CallModel::test();1394
let mut model = CallModel::test();1111
for (kind, expected) in [(CallKind::Test, false), (CallKind::Direct, false), (CallKind::Group, true), (CallKind::Meeting, true)] {1395
for (kind, expected) in [1396
(CallKind::Test, false),1397
(CallKind::Direct, false),1398
(CallKind::Group, true),1399
(CallKind::Meeting, true),1400
] {1112
model.kind = kind;1401
model.kind = kind;1113
assert_eq!(model.has_reaction_controls(), expected);1402
assert_eq!(model.has_reaction_controls(), expected);1114
}1403
}@@ -1120,12 +1409,24 @@ mod tests {1120
let start = Instant::now();1409
let start = Instant::now();1121
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);1410
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);1122
let serial = model.reactions[0].serial;1411
let serial = model.reactions[0].serial;1123
model.note_reaction("8:orgid:me".into(), Reaction::Like, start + Duration::from_millis(1500));1412
model.note_reaction(1413
"8:orgid:me".into(),1414
Reaction::Like,1415
start + Duration::from_millis(1500),1416
);1124
assert_eq!(model.reactions.len(), 1);1417
assert_eq!(model.reactions.len(), 1);1125
assert_eq!(model.reactions[0].serial, serial);1418
assert_eq!(model.reactions[0].serial, serial);1126
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_millis(1600));1419
model.note_reaction(1420
"8:orgid:me".into(),1421
Reaction::Heart,1422
start + Duration::from_millis(1600),1423
);1127
assert_eq!(model.reactions[0].reaction, Reaction::Heart);1424
assert_eq!(model.reactions[0].reaction, Reaction::Heart);1128
model.note_reaction("8:orgid:me".into(), Reaction::Heart, start + Duration::from_secs(4));1425
model.note_reaction(1426
"8:orgid:me".into(),1427
Reaction::Heart,1428
start + Duration::from_secs(4),1429
);1129
assert_ne!(model.reactions[0].serial, serial);1430
assert_ne!(model.reactions[0].serial, serial);1130
}1431
}1131
1432
@@ -1135,15 +1436,25 @@ mod tests {1135
let start = Instant::now();1436
let start = Instant::now();1136
model.note_reaction("8:orgid:a".into(), Reaction::Like, start);1437
model.note_reaction("8:orgid:a".into(), Reaction::Like, start);1137
let serial = model.reactions[0].serial;1438
let serial = model.reactions[0].serial;1138
model.note_reaction("8:orgid:a".into(), Reaction::Like, start + Duration::from_secs(1));1439
model.note_reaction(1440
"8:orgid:a".into(),1441
Reaction::Like,1442
start + Duration::from_secs(1),1443
);1139
assert_ne!(model.reactions[0].serial, serial);1444
assert_ne!(model.reactions[0].serial, serial);1140
}1445
}1141
1446
1142
#[test]1447
#[test]1143
fn lowering_clears_the_hand_everywhere() {1448
fn lowering_clears_the_hand_everywhere() {1144
let mut model = meeting_with_me();1449
let mut model = meeting_with_me();1145
model.apply(CallUpdate::Roster(vec![raised("8:orgid:a", "Ana", 1), raised("8:orgid:me", "Me", 2)]));1450
model.apply(CallUpdate::Roster(vec![1146
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), entry("8:orgid:me", "Me", false, false)]));1451
raised("8:orgid:a", "Ana", 1),1452
raised("8:orgid:me", "Me", 2),1453
]));1454
model.apply(CallUpdate::Roster(vec![1455
entry("8:orgid:a", "Ana", false, false),1456
entry("8:orgid:me", "Me", false, false),1457
]));1147
assert!(!model.any_hand_raised());1458
assert!(!model.any_hand_raised());1148
assert_eq!(model.own_cell_index(1), 1);1459
assert_eq!(model.own_cell_index(1), 1);1149
}1460
}@@ -1161,22 +1472,45 @@ mod tests {1161
model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);1472
model.note_reaction("8:orgid:a".into(), Reaction::Heart, start);1162
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);1473
model.note_reaction("8:orgid:me".into(), Reaction::Like, start);1163
let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {1474
let reaction_at = |model: &CallModel, mri: &str, seconds: u64| {1164
model.chip_of(mri, start + Duration::from_secs(seconds)).map(|chip| chip.reaction)1475
model1476
.chip_of(mri, start + Duration::from_secs(seconds))1477
.map(|chip| chip.reaction)1165
};1478
};1166
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));1479
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Heart));1167
assert_eq!(model.own_chip(start + Duration::from_secs(2)).map(|chip| chip.reaction), Some(Reaction::Like));1480
assert_eq!(1481
model1482
.own_chip(start + Duration::from_secs(2))1483
.map(|chip| chip.reaction),1484
Some(Reaction::Like)1485
);1168
assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);1486
assert_eq!(reaction_at(&model, "8:orgid:a", 3), None);1169
model.note_reaction("8:orgid:a".into(), Reaction::Laugh, start + Duration::from_secs(1));1487
model.note_reaction(1488
"8:orgid:a".into(),1489
Reaction::Laugh,1490
start + Duration::from_secs(1),1491
);1170
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));1492
assert_eq!(reaction_at(&model, "8:orgid:a", 2), Some(Reaction::Laugh));1171
assert_eq!(model.reactions.len(), 2);1493
assert_eq!(model.reactions.len(), 2);1172
}1494
}1173
1495
1174
#[test]1496
#[test]1175
fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {1497
fn the_chat_panel_picks_the_meeting_thread_or_the_call_chat() {1176
assert_eq!(chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")), Some("19:meeting_x"));1498
assert_eq!(1177
assert_eq!(chat_thread(CallKind::Meeting, None, Some("19:list")), Some("19:list"));1499
chat_thread(CallKind::Meeting, Some("19:meeting_x"), Some("19:list")),1178
assert_eq!(chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")), Some("19:dm"));1500
Some("19:meeting_x")1179
assert_eq!(chat_thread(CallKind::Group, None, Some("19:group")), Some("19:group"));1501
);1502
assert_eq!(1503
chat_thread(CallKind::Meeting, None, Some("19:list")),1504
Some("19:list")1505
);1506
assert_eq!(1507
chat_thread(CallKind::Direct, Some("19:meeting_x"), Some("19:dm")),1508
Some("19:dm")1509
);1510
assert_eq!(1511
chat_thread(CallKind::Group, None, Some("19:group")),1512
Some("19:group")1513
);1180
assert_eq!(chat_thread(CallKind::Test, None, None), None);1514
assert_eq!(chat_thread(CallKind::Test, None, None), None);1181
}1515
}1182
1516
@@ -1193,19 +1527,30 @@ mod tests {1193
#[test]1527
#[test]1194
fn lobby_guests_are_listed_for_organizers_who_may_admit() {1528
fn lobby_guests_are_listed_for_organizers_who_may_admit() {1195
let mut model = meeting_with_me();1529
let mut model = meeting_with_me();1196
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1530
model.apply(CallUpdate::State(CallState::Connected {1531
since: Instant::now(),1532
}));1197
model.apply(CallUpdate::Roster(vec![1533
model.apply(CallUpdate::Roster(vec![1198
entry("8:orgid:a", "Ana", false, false),1534
entry("8:orgid:a", "Ana", false, false),1199
entry("8:orgid:g1", "Gast Eins", false, true),1535
entry("8:orgid:g1", "Gast Eins", false, true),1200
entry("8:orgid:g2", "Gast Zwei", false, true),1536
entry("8:orgid:g2", "Gast Zwei", false, true),1201
]));1537
]));1202
let waiting: Vec<&str> = model.lobby_guests().iter().map(|tile| tile.name.as_str()).collect();1538
let waiting: Vec<&str> = model1539
.lobby_guests()1540
.iter()1541
.map(|tile| tile.name.as_str())1542
.collect();1203
assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);1543
assert_eq!(waiting, vec!["Gast Eins", "Gast Zwei"]);1204
assert!(!model.can_admit());1544
assert!(!model.can_admit());1205
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me"), entry("8:orgid:g1", "Gast Eins", false, true)]));1545
model.apply(CallUpdate::Roster(vec![1546
organizer_entry("8:orgid:me"),1547
entry("8:orgid:g1", "Gast Eins", false, true),1548
]));1206
assert!(model.organizer && model.can_admit() && model.organizes_meeting());1549
assert!(model.organizer && model.can_admit() && model.organizes_meeting());1207
let mut owner = CallModel::meeting("Standup", true);1550
let mut owner = CallModel::meeting("Standup", true);1208
owner.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1551
owner.apply(CallUpdate::State(CallState::Connected {1552
since: Instant::now(),1553
}));1209
assert!(owner.can_admit());1554
assert!(owner.can_admit());1210
owner.apply(CallUpdate::Lobby(true));1555
owner.apply(CallUpdate::Lobby(true));1211
assert!(!owner.can_admit());1556
assert!(!owner.can_admit());@@ -1214,33 +1559,90 @@ mod tests {1214
#[test]1559
#[test]1215
fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {1560
fn a_spotlight_takes_the_stage_and_the_lowest_rank_wins() {1216
let mut model = meeting_with_me();1561
let mut model = meeting_with_me();1217
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), spotlit("8:orgid:c", "Cy", 2)]));1562
model.apply(CallUpdate::Roster(vec![1218
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:c".into(), own: false, spotlight: true, pinned: false }));1563
entry("8:orgid:a", "Ana", false, false),1564
spotlit("8:orgid:b", "Bo", 4),1565
spotlit("8:orgid:c", "Cy", 2),1566
]));1567
assert_eq!(1568
model.focus(),1569
Some(Focus {1570
mri: "8:orgid:c".into(),1571
own: false,1572
spotlight: true,1573
pinned: false1574
})1575
);1219
assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));1576
assert!(model.is_spotlighted("8:orgid:b") && !model.is_spotlighted("8:orgid:a"));1220
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 4), entry("8:orgid:c", "Cy", false, false)]));1577
model.apply(CallUpdate::Roster(vec![1221
assert_eq!(model.focus().map(|focus| focus.mri), Some("8:orgid:b".to_owned()));1578
entry("8:orgid:a", "Ana", false, false),1222
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false)]));1579
spotlit("8:orgid:b", "Bo", 4),1580
entry("8:orgid:c", "Cy", false, false),1581
]));1582
assert_eq!(1583
model.focus().map(|focus| focus.mri),1584
Some("8:orgid:b".to_owned())1585
);1586
model.apply(CallUpdate::Roster(vec![entry(1587
"8:orgid:a",1588
"Ana",1589
false,1590
false,1591
)]));1223
assert_eq!(model.focus(), None);1592
assert_eq!(model.focus(), None);1224
}1593
}1225
1594
1226
#[test]1595
#[test]1227
fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {1596
fn spotlighting_yourself_puts_your_own_tile_on_the_stage() {1228
let mut model = meeting_with_me();1597
let mut model = meeting_with_me();1229
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:me", "Me", 1)]));1598
model.apply(CallUpdate::Roster(vec![1230
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:me".into(), own: true, spotlight: true, pinned: false }));1599
entry("8:orgid:a", "Ana", false, false),1600
spotlit("8:orgid:me", "Me", 1),1601
]));1602
assert_eq!(1603
model.focus(),1604
Some(Focus {1605
mri: "8:orgid:me".into(),1606
own: true,1607
spotlight: true,1608
pinned: false1609
})1610
);1231
}1611
}1232
1612
1233
#[test]1613
#[test]1234
fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {1614
fn a_pin_is_local_beats_the_spotlight_and_ends_when_the_person_leaves() {1235
let mut model = meeting_with_me();1615
let mut model = meeting_with_me();1236
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1616
model.apply(CallUpdate::State(CallState::Connected {1237
model.apply(CallUpdate::Roster(vec![entry("8:orgid:a", "Ana", false, false), spotlit("8:orgid:b", "Bo", 1)]));1617
since: Instant::now(),1618
}));1619
model.apply(CallUpdate::Roster(vec![1620
entry("8:orgid:a", "Ana", false, false),1621
spotlit("8:orgid:b", "Bo", 1),1622
]));1238
model.toggle_pin("8:orgid:a");1623
model.toggle_pin("8:orgid:a");1239
assert_eq!(model.focus(), Some(Focus { mri: "8:orgid:a".into(), own: false, spotlight: false, pinned: true }));1624
assert_eq!(1240
let names: Vec<&str> = model.strip_tiles().iter().map(|tile| tile.name.as_str()).collect();1625
model.focus(),1626
Some(Focus {1627
mri: "8:orgid:a".into(),1628
own: false,1629
spotlight: false,1630
pinned: true1631
})1632
);1633
let names: Vec<&str> = model1634
.strip_tiles()1635
.iter()1636
.map(|tile| tile.name.as_str())1637
.collect();1241
assert_eq!(names[0], "Ana");1638
assert_eq!(names[0], "Ana");1242
model.toggle_pin("8:orgid:b");1639
model.toggle_pin("8:orgid:b");1243
assert_eq!(model.focus().map(|focus| (focus.mri, focus.spotlight, focus.pinned)), Some(("8:orgid:b".to_owned(), true, true)));1640
assert_eq!(1641
model1642
.focus()1643
.map(|focus| (focus.mri, focus.spotlight, focus.pinned)),1644
Some(("8:orgid:b".to_owned(), true, true))1645
);1244
model.toggle_pin("8:orgid:b");1646
model.toggle_pin("8:orgid:b");1245
assert_eq!(model.pinned, None);1647
assert_eq!(model.pinned, None);1246
model.toggle_pin("8:orgid:a");1648
model.toggle_pin("8:orgid:a");@@ -1249,7 +1651,13 @@ mod tests {1249
}1651
}1250
1652
1251
fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {1653
fn caption(id: &str, speaker: &str, text: &str, is_final: bool) -> CaptionEntry {1252
CaptionEntry { id: id.into(), user_id: "u".into(), display_name: speaker.into(), text: text.into(), is_final }1654
CaptionEntry {1655
id: id.into(),1656
user_id: "u".into(),1657
display_name: speaker.into(),1658
text: text.into(),1659
is_final,1660
}1253
}1661
}1254
1662
1255
#[test]1663
#[test]@@ -1263,21 +1671,45 @@ mod tests {1263
model.note_caption(caption("1", "Ana", "Hello there", true), start);1671
model.note_caption(caption("1", "Ana", "Hello there", true), start);1264
assert_eq!(model.caption_lines.len(), 1);1672
assert_eq!(model.caption_lines.len(), 1);1265
assert_eq!(model.caption_lines[0].text, "Hello there");1673
assert_eq!(model.caption_lines[0].text, "Hello there");1266
model.note_caption(caption("2", "", "Next", false), start + Duration::from_secs(1));1674
model.note_caption(1267
model.note_caption(caption("3", "Bo", "Third", false), start + Duration::from_secs(2));1675
caption("2", "", "Next", false),1268
let texts: Vec<&str> = model.caption_lines.iter().map(|line| line.text.as_str()).collect();1676
start + Duration::from_secs(1),1677
);1678
model.note_caption(1679
caption("3", "Bo", "Third", false),1680
start + Duration::from_secs(2),1681
);1682
let texts: Vec<&str> = model1683
.caption_lines1684
.iter()1685
.map(|line| line.text.as_str())1686
.collect();1269
assert_eq!(texts, vec!["Next", "Third"]);1687
assert_eq!(texts, vec!["Next", "Third"]);1270
assert_eq!(model.caption_lines[0].speaker, "Someone");1688
assert_eq!(model.caption_lines[0].speaker, "Someone");1271
assert_eq!(model.visible_captions(start + Duration::from_secs(3)).len(), 2);1689
assert_eq!(1272
assert_eq!(model.visible_captions(start + Duration::from_millis(5500)).len(), 1);1690
model.visible_captions(start + Duration::from_secs(3)).len(),1273
assert!(model.visible_captions(start + Duration::from_secs(7)).is_empty());1691
21692
);1693
assert_eq!(1694
model1695
.visible_captions(start + Duration::from_millis(5500))1696
.len(),1697
11698
);1699
assert!(1700
model1701
.visible_captions(start + Duration::from_secs(7))1702
.is_empty()1703
);1274
model.apply(CallUpdate::Captions(CaptionState::Off));1704
model.apply(CallUpdate::Captions(CaptionState::Off));1275
assert!(model.caption_lines.is_empty() && !model.captions_on());1705
assert!(model.caption_lines.is_empty() && !model.captions_on());1276
}1706
}1277
1707
1278
fn one_to_one() -> CallModel {1708
fn one_to_one() -> CallModel {1279
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);1709
let mut model = CallModel::people("Bea", &[("8:orgid:bea".into(), "Bea".into())]);1280
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1710
model.apply(CallUpdate::State(CallState::Connected {1711
since: Instant::now(),1712
}));1281
model1713
model1282
}1714
}1283
1715
@@ -1291,13 +1723,24 @@ mod tests {1291
assert!(!model.can_hold() && !model.can_transfer());1723
assert!(!model.can_hold() && !model.can_transfer());1292
let meeting = meeting_with_me();1724
let meeting = meeting_with_me();1293
assert!(!meeting.can_hold() && !meeting.can_transfer());1725
assert!(!meeting.can_hold() && !meeting.can_transfer());1294
assert!(!CallModel::people("Group", &[("8:orgid:a".into(), "A".into()), ("8:orgid:b".into(), "B".into())]).can_hold());1726
assert!(1727
!CallModel::people(1728
"Group",1729
&[1730
("8:orgid:a".into(), "A".into()),1731
("8:orgid:b".into(), "B".into())1732
]1733
)1734
.can_hold()1735
);1295
}1736
}1296
1737
1297
#[test]1738
#[test]1298
fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {1739
fn recording_and_consent_follow_the_call_updates_and_only_organizers_may_record() {1299
let mut model = meeting_with_me();1740
let mut model = meeting_with_me();1300
model.apply(CallUpdate::State(CallState::Connected { since: Instant::now() }));1741
model.apply(CallUpdate::State(CallState::Connected {1742
since: Instant::now(),1743
}));1301
assert!(!model.can_record());1744
assert!(!model.can_record());1302
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));1745
model.apply(CallUpdate::Roster(vec![organizer_entry("8:orgid:me")]));1303
assert!(model.can_record());1746
assert!(model.can_record());@@ -1313,7 +1756,12 @@ mod tests {1313
#[test]1756
#[test]1314
fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {1757
fn a_whiteboard_share_names_the_presenter_and_offers_the_browser_only_with_a_link() {1315
let mut model = meeting_with_me();1758
let mut model = meeting_with_me();1316
model.apply(CallUpdate::Roster(vec![entry("8:orgid:ana", "Ana", false, false)]));1759
model.apply(CallUpdate::Roster(vec![entry(1760
"8:orgid:ana",1761
"Ana",1762
false,1763
false,1764
)]));1317
assert_eq!(model.whiteboard_label(), None);1765
assert_eq!(model.whiteboard_label(), None);1318
let share = |presenter: &str, url: Option<&str>| calling::ContentShare {1766
let share = |presenter: &str, url: Option<&str>| calling::ContentShare {1319
session_id: "s".into(),1767
session_id: "s".into(),@@ -1322,11 +1770,26 @@ mod tests {1322
url: url.map(str::to_owned),1770
url: url.map(str::to_owned),1323
whiteboard: true,1771
whiteboard: true,1324
};1772
};1325
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:ana", Some("https://app.whiteboard.microsoft.com/x")))));1773
model.apply(CallUpdate::Whiteboard(Some(share(1326
assert_eq!(model.whiteboard_label().as_deref(), Some("Ana is sharing a whiteboard"));1774
"8:orgid:ana",1327
assert_eq!(model.whiteboard_url(), Some("https://app.whiteboard.microsoft.com/x"));1775
Some("https://app.whiteboard.microsoft.com/x"),1328
model.apply(CallUpdate::Whiteboard(Some(share("8:orgid:stranger", None))));1776
))));1329
assert_eq!(model.whiteboard_label().as_deref(), Some("Someone is sharing a whiteboard"));1777
assert_eq!(1778
model.whiteboard_label().as_deref(),1779
Some("Ana is sharing a whiteboard")1780
);1781
assert_eq!(1782
model.whiteboard_url(),1783
Some("https://app.whiteboard.microsoft.com/x")1784
);1785
model.apply(CallUpdate::Whiteboard(Some(share(1786
"8:orgid:stranger",1787
None,1788
))));1789
assert_eq!(1790
model.whiteboard_label().as_deref(),1791
Some("Someone is sharing a whiteboard")1792
);1330
assert_eq!(model.whiteboard_url(), None);1793
assert_eq!(model.whiteboard_url(), None);1331
model.apply(CallUpdate::Whiteboard(None));1794
model.apply(CallUpdate::Whiteboard(None));1332
assert_eq!(model.whiteboard_label(), None);1795
assert_eq!(model.whiteboard_label(), None);@@ -1345,7 +1808,9 @@ mod tests {1345
};1808
};1346
assert_eq!(consult.status_text(), "Calling Ana...");1809
assert_eq!(consult.status_text(), "Calling Ana...");1347
assert!(!consult.ready_to_transfer());1810
assert!(!consult.ready_to_transfer());1348
consult.state = CallState::Connected { since: Instant::now() };1811
consult.state = CallState::Connected {1812
since: Instant::now(),1813
};1349
assert_eq!(consult.status_text(), "Consulting Ana");1814
assert_eq!(consult.status_text(), "Consulting Ana");1350
assert!(!consult.ready_to_transfer());1815
assert!(!consult.ready_to_transfer());1351
consult.replacement = Some("https://cc/replacement".into());1816
consult.replacement = Some("https://cc/replacement".into());@@ -6,8 +6,8 @@ use gpui_kit::*;
6
6
7
7
use super::model::format_elapsed;
8
8
use super::overlay_layout::{
9
MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness, format_position, mini_rect,
10
mini_wanted, mini_work_area, parse_position,
9
MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness, format_position,
10
mini_rect, 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};
@@ -40,7 +40,9 @@ impl Placed {
40
40
};
41
41
platform::place(native, rect.left, rect.top, rect.width(), rect.height());
42
42
// WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
43
self.handle.update(cx, |_, window, cx| window.bounds_changed(cx)).ok();
43
self.handle
44
.update(cx, |_, window, cx| window.bounds_changed(cx))
45
.ok();
44
46
}
45
47
}
46
48
@@ -84,7 +86,10 @@ fn display_work_area(cx: &App) -> Option<WorkArea> {
84
86
fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
85
87
let bounds = Bounds::new(
86
88
point(px(rect.left as f32 / scale), px(rect.top as f32 / scale)),
87
size(px(rect.width() as f32 / scale), px(rect.height() as f32 / scale)),
89
size(
90
px(rect.width() as f32 / scale),
91
px(rect.height() as f32 / scale),
92
),
88
93
);
89
94
WindowOptions {
90
95
window_bounds: Some(WindowBounds::Windowed(bounds)),
@@ -163,7 +168,10 @@ impl CallWindows {
163
168
Some(ShareKind::Window) => "window",
164
169
_ => "screen",
165
170
};
166
format!("Sharing {what} {}", format_elapsed(session.started.elapsed()))
171
format!(
172
"Sharing {what} {}",
173
format_elapsed(session.started.elapsed())
174
)
167
175
}
168
176
169
177
pub fn toggle_pin(&mut self, cx: &mut Context<Self>) {
@@ -184,12 +192,17 @@ impl CallWindows {
184
192
if let Some(native) = self.main_native {
185
193
platform::restore_and_raise(native);
186
194
}
187
self.main_window.update(cx, |_, window, _| window.activate_window()).ok();
195
self.main_window
196
.update(cx, |_, window, _| window.activate_window())
197
.ok();
188
198
self.app.update(cx, |state, cx| state.show_call(true, cx));
189
199
}
190
200
191
201
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()
202
self.app.read(cx).call.is_none()
203
&& self.share.is_none()
204
&& self.windows.is_empty()
205
&& self.opening.is_empty()
193
206
}
194
207
195
208
fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
@@ -220,7 +233,13 @@ impl CallWindows {
220
233
fn local_share(&self, cx: &App) -> Option<Option<ShareSource>> {
221
234
let model = &self.app.read(cx).call.as_ref()?.model;
222
235
let label = model.local_share.as_ref()?;
223
Some(model.share_sources.iter().find(|source| &source.label() == label).cloned())
236
Some(
237
model
238
.share_sources
239
.iter()
240
.find(|source| &source.label() == label)
241
.cloned(),
242
)
224
243
}
225
244
226
245
fn sync_share(&mut self, refresh_geometry: bool, cx: &mut Context<Self>) {
@@ -231,7 +250,11 @@ impl CallWindows {
231
250
let mut refresh_geometry = refresh_geometry;
232
251
if self.share.is_none() {
233
252
self.bar_idle_since = Instant::now();
234
self.share = Some(ShareSession { started: Instant::now(), source: None, geometry: None });
253
self.share = Some(ShareSession {
254
started: Instant::now(),
255
source: None,
256
geometry: None,
257
});
235
258
refresh_geometry = true;
236
259
}
237
260
let Some(session) = self.share.as_mut() else {
@@ -239,14 +262,24 @@ impl CallWindows {
239
262
};
240
263
session.source = source;
241
264
if refresh_geometry {
242
session.geometry = session.source.as_ref().and_then(|source| platform::share_geometry(source.kind, source.id));
265
session.geometry = session
266
.source
267
.as_ref()
268
.and_then(|source| platform::share_geometry(source.kind, source.id));
243
269
}
244
270
let geometry = session.geometry;
245
271
let elapsed_seconds = session.started.elapsed().as_secs();
246
let Some(work) = geometry.map(|geometry| geometry.work).or(self.work_area).or_else(|| display_work_area(cx)) else {
272
let Some(work) = geometry
273
.map(|geometry| geometry.work)
274
.or(self.work_area)
275
.or_else(|| display_work_area(cx))
276
else {
247
277
return;
248
278
};
249
let can_collapse = self.windows.get(&Role::Bar).is_some_and(|placed| placed.native.is_some());
279
let can_collapse = self
280
.windows
281
.get(&Role::Bar)
282
.is_some_and(|placed| placed.native.is_some());
250
283
let collapsed = can_collapse && bar_collapsed(self.pinned, self.bar_idle_since.elapsed());
251
284
if collapsed != self.bar_collapsed || elapsed_seconds != self.shown_second {
252
285
self.bar_collapsed = collapsed;
@@ -257,7 +290,10 @@ impl CallWindows {
257
290
match geometry {
258
291
Some(geometry) => {
259
292
let thickness = border_thickness(geometry.work.scale);
260
for (side, rect) in border_rects(geometry.target, thickness).into_iter().enumerate() {
293
for (side, rect) in border_rects(geometry.target, thickness)
294
.into_iter()
295
.enumerate()
296
{
261
297
self.ensure_window(Role::Border(side), rect, geometry.work.scale, true, cx);
262
298
}
263
299
}
@@ -294,7 +330,11 @@ impl CallWindows {
294
330
}
295
331
296
332
fn track_mini_position(&mut self, cx: &mut Context<Self>) {
297
let Some(native) = self.windows.get(&Role::Mini).and_then(|placed| placed.native) else {
333
let Some(native) = self
334
.windows
335
.get(&Role::Mini)
336
.and_then(|placed| placed.native)
337
else {
298
338
return;
299
339
};
300
340
let Some(rect) = platform::window_rect(native) else {
@@ -305,11 +345,22 @@ impl CallWindows {
305
345
self.mini_seen = Some(position);
306
346
if settled && self.mini_saved != Some(position) {
307
347
self.mini_saved = Some(position);
308
let _ = self.app.read(cx).store.set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
348
let _ = self
349
.app
350
.read(cx)
351
.store
352
.set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
309
353
}
310
354
}
311
355
312
fn ensure_window(&mut self, role: Role, rect: ScreenRect, scale: f32, follow: bool, cx: &mut Context<Self>) {
356
fn ensure_window(
357
&mut self,
358
role: Role,
359
rect: ScreenRect,
360
scale: f32,
361
follow: bool,
362
cx: &mut Context<Self>,
363
) {
313
364
match self.windows.get_mut(&role) {
314
365
Some(placed) => {
315
366
if placed.rect.is_none() || follow && placed.rect != Some(rect) {
@@ -322,7 +373,10 @@ impl CallWindows {
322
373
323
374
fn close(&mut self, role: Role, cx: &mut Context<Self>) {
324
375
if let Some(placed) = self.windows.remove(&role) {
325
placed.handle.update(cx, |_, window, _| window.remove_window()).ok();
376
placed
377
.handle
378
.update(cx, |_, window, _| window.remove_window())
379
.ok();
326
380
}
327
381
}
328
382
@@ -345,7 +399,10 @@ impl CallWindows {
345
399
});
346
400
let placed = opened.ok().map(|handle| {
347
401
let handle = AnyWindowHandle::from(handle);
348
let native = handle.update(cx, |_, window, _| platform::native_handle(window)).ok().flatten();
402
let native = handle
403
.update(cx, |_, window, _| platform::native_handle(window))
404
.ok()
405
.flatten();
349
406
if let Some(native) = native {
350
407
platform::prepare_toast_window(native);
351
408
platform::exclude_from_capture(native);
@@ -353,7 +410,11 @@ impl CallWindows {
353
410
platform::make_click_through(native);
354
411
}
355
412
}
356
Placed { handle, native, rect: None }
413
Placed {
414
handle,
415
native,
416
rect: None,
417
}
357
418
});
358
419
controller.update(cx, |this, _| {
359
420
this.opening.remove(&role);
@@ -6,8 +6,8 @@ use gpui_kit::*;6
6
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,10
mini_wanted, mini_work_area, parse_position,10
mini_rect, 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};@@ -40,7 +40,9 @@ impl Placed {40
};40
};41
platform::place(native, rect.left, rect.top, rect.width(), rect.height());41
platform::place(native, rect.left, rect.top, rect.width(), rect.height());42
// WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.42
// WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.43
self.handle.update(cx, |_, window, cx| window.bounds_changed(cx)).ok();43
self.handle44
.update(cx, |_, window, cx| window.bounds_changed(cx))45
.ok();44
}46
}45
}47
}46
48
@@ -84,7 +86,10 @@ fn display_work_area(cx: &App) -> Option<WorkArea> {84
fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {86
fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {85
let bounds = Bounds::new(87
let bounds = Bounds::new(86
point(px(rect.left as f32 / scale), px(rect.top as f32 / scale)),88
point(px(rect.left as f32 / scale), px(rect.top as f32 / scale)),87
size(px(rect.width() as f32 / scale), px(rect.height() as f32 / scale)),89
size(90
px(rect.width() as f32 / scale),91
px(rect.height() as f32 / scale),92
),88
);93
);89
WindowOptions {94
WindowOptions {90
window_bounds: Some(WindowBounds::Windowed(bounds)),95
window_bounds: Some(WindowBounds::Windowed(bounds)),@@ -163,7 +168,10 @@ impl CallWindows {163
Some(ShareKind::Window) => "window",168
Some(ShareKind::Window) => "window",164
_ => "screen",169
_ => "screen",165
};170
};166
format!("Sharing {what} {}", format_elapsed(session.started.elapsed()))171
format!(172
"Sharing {what} {}",173
format_elapsed(session.started.elapsed())174
)167
}175
}168
176
169
pub fn toggle_pin(&mut self, cx: &mut Context<Self>) {177
pub fn toggle_pin(&mut self, cx: &mut Context<Self>) {@@ -184,12 +192,17 @@ impl CallWindows {184
if let Some(native) = self.main_native {192
if let Some(native) = self.main_native {185
platform::restore_and_raise(native);193
platform::restore_and_raise(native);186
}194
}187
self.main_window.update(cx, |_, window, _| window.activate_window()).ok();195
self.main_window196
.update(cx, |_, window, _| window.activate_window())197
.ok();188
self.app.update(cx, |state, cx| state.show_call(true, cx));198
self.app.update(cx, |state, cx| state.show_call(true, cx));189
}199
}190
200
191
fn idle(&self, cx: &App) -> bool {201
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()202
self.app.read(cx).call.is_none()203
&& self.share.is_none()204
&& self.windows.is_empty()205
&& self.opening.is_empty()193
}206
}194
207
195
fn tick(&mut self, cx: &mut Context<Self>) -> Duration {208
fn tick(&mut self, cx: &mut Context<Self>) -> Duration {@@ -220,7 +233,13 @@ impl CallWindows {220
fn local_share(&self, cx: &App) -> Option<Option<ShareSource>> {233
fn local_share(&self, cx: &App) -> Option<Option<ShareSource>> {221
let model = &self.app.read(cx).call.as_ref()?.model;234
let model = &self.app.read(cx).call.as_ref()?.model;222
let label = model.local_share.as_ref()?;235
let label = model.local_share.as_ref()?;223
Some(model.share_sources.iter().find(|source| &source.label() == label).cloned())236
Some(237
model238
.share_sources239
.iter()240
.find(|source| &source.label() == label)241
.cloned(),242
)224
}243
}225
244
226
fn sync_share(&mut self, refresh_geometry: bool, cx: &mut Context<Self>) {245
fn sync_share(&mut self, refresh_geometry: bool, cx: &mut Context<Self>) {@@ -231,7 +250,11 @@ impl CallWindows {231
let mut refresh_geometry = refresh_geometry;250
let mut refresh_geometry = refresh_geometry;232
if self.share.is_none() {251
if self.share.is_none() {233
self.bar_idle_since = Instant::now();252
self.bar_idle_since = Instant::now();234
self.share = Some(ShareSession { started: Instant::now(), source: None, geometry: None });253
self.share = Some(ShareSession {254
started: Instant::now(),255
source: None,256
geometry: None,257
});235
refresh_geometry = true;258
refresh_geometry = true;236
}259
}237
let Some(session) = self.share.as_mut() else {260
let Some(session) = self.share.as_mut() else {@@ -239,14 +262,24 @@ impl CallWindows {239
};262
};240
session.source = source;263
session.source = source;241
if refresh_geometry {264
if refresh_geometry {242
session.geometry = session.source.as_ref().and_then(|source| platform::share_geometry(source.kind, source.id));265
session.geometry = session266
.source267
.as_ref()268
.and_then(|source| platform::share_geometry(source.kind, source.id));243
}269
}244
let geometry = session.geometry;270
let geometry = session.geometry;245
let elapsed_seconds = session.started.elapsed().as_secs();271
let elapsed_seconds = session.started.elapsed().as_secs();246
let Some(work) = geometry.map(|geometry| geometry.work).or(self.work_area).or_else(|| display_work_area(cx)) else {272
let Some(work) = geometry273
.map(|geometry| geometry.work)274
.or(self.work_area)275
.or_else(|| display_work_area(cx))276
else {247
return;277
return;248
};278
};249
let can_collapse = self.windows.get(&Role::Bar).is_some_and(|placed| placed.native.is_some());279
let can_collapse = self280
.windows281
.get(&Role::Bar)282
.is_some_and(|placed| placed.native.is_some());250
let collapsed = can_collapse && bar_collapsed(self.pinned, self.bar_idle_since.elapsed());283
let collapsed = can_collapse && bar_collapsed(self.pinned, self.bar_idle_since.elapsed());251
if collapsed != self.bar_collapsed || elapsed_seconds != self.shown_second {284
if collapsed != self.bar_collapsed || elapsed_seconds != self.shown_second {252
self.bar_collapsed = collapsed;285
self.bar_collapsed = collapsed;@@ -257,7 +290,10 @@ impl CallWindows {257
match geometry {290
match geometry {258
Some(geometry) => {291
Some(geometry) => {259
let thickness = border_thickness(geometry.work.scale);292
let thickness = border_thickness(geometry.work.scale);260
for (side, rect) in border_rects(geometry.target, thickness).into_iter().enumerate() {293
for (side, rect) in border_rects(geometry.target, thickness)294
.into_iter()295
.enumerate()296
{261
self.ensure_window(Role::Border(side), rect, geometry.work.scale, true, cx);297
self.ensure_window(Role::Border(side), rect, geometry.work.scale, true, cx);262
}298
}263
}299
}@@ -294,7 +330,11 @@ impl CallWindows {294
}330
}295
331
296
fn track_mini_position(&mut self, cx: &mut Context<Self>) {332
fn track_mini_position(&mut self, cx: &mut Context<Self>) {297
let Some(native) = self.windows.get(&Role::Mini).and_then(|placed| placed.native) else {333
let Some(native) = self334
.windows335
.get(&Role::Mini)336
.and_then(|placed| placed.native)337
else {298
return;338
return;299
};339
};300
let Some(rect) = platform::window_rect(native) else {340
let Some(rect) = platform::window_rect(native) else {@@ -305,11 +345,22 @@ impl CallWindows {305
self.mini_seen = Some(position);345
self.mini_seen = Some(position);306
if settled && self.mini_saved != Some(position) {346
if settled && self.mini_saved != Some(position) {307
self.mini_saved = Some(position);347
self.mini_saved = Some(position);308
let _ = self.app.read(cx).store.set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));348
let _ = self349
.app350
.read(cx)351
.store352
.set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));309
}353
}310
}354
}311
355
312
fn ensure_window(&mut self, role: Role, rect: ScreenRect, scale: f32, follow: bool, cx: &mut Context<Self>) {356
fn ensure_window(357
&mut self,358
role: Role,359
rect: ScreenRect,360
scale: f32,361
follow: bool,362
cx: &mut Context<Self>,363
) {313
match self.windows.get_mut(&role) {364
match self.windows.get_mut(&role) {314
Some(placed) => {365
Some(placed) => {315
if placed.rect.is_none() || follow && placed.rect != Some(rect) {366
if placed.rect.is_none() || follow && placed.rect != Some(rect) {@@ -322,7 +373,10 @@ impl CallWindows {322
373
323
fn close(&mut self, role: Role, cx: &mut Context<Self>) {374
fn close(&mut self, role: Role, cx: &mut Context<Self>) {324
if let Some(placed) = self.windows.remove(&role) {375
if let Some(placed) = self.windows.remove(&role) {325
placed.handle.update(cx, |_, window, _| window.remove_window()).ok();376
placed377
.handle378
.update(cx, |_, window, _| window.remove_window())379
.ok();326
}380
}327
}381
}328
382
@@ -345,7 +399,10 @@ impl CallWindows {345
});399
});346
let placed = opened.ok().map(|handle| {400
let placed = opened.ok().map(|handle| {347
let handle = AnyWindowHandle::from(handle);401
let handle = AnyWindowHandle::from(handle);348
let native = handle.update(cx, |_, window, _| platform::native_handle(window)).ok().flatten();402
let native = handle403
.update(cx, |_, window, _| platform::native_handle(window))404
.ok()405
.flatten();349
if let Some(native) = native {406
if let Some(native) = native {350
platform::prepare_toast_window(native);407
platform::prepare_toast_window(native);351
platform::exclude_from_capture(native);408
platform::exclude_from_capture(native);@@ -353,7 +410,11 @@ impl CallWindows {353
platform::make_click_through(native);410
platform::make_click_through(native);354
}411
}355
}412
}356
Placed { handle, native, rect: None }413
Placed {414
handle,415
native,416
rect: None,417
}357
});418
});358
controller.update(cx, |this, _| {419
controller.update(cx, |this, _| {359
this.opening.remove(&role);420
this.opening.remove(&role);@@ -43,12 +43,37 @@ pub fn bar_collapsed(pinned: bool, idle: Duration) -> bool {
43
43
44
44
pub fn border_rects(target: ScreenRect, thickness: i32) -> [ScreenRect; 4] {
45
45
let thickness = thickness.clamp(1, (target.width().min(target.height()) / 2).max(1));
46
let ScreenRect { left, top, right, bottom } = target;
46
let ScreenRect {
47
left,
48
top,
49
right,
50
bottom,
51
} = target;
47
52
[
48
ScreenRect { left, top, right, bottom: top + thickness },
49
ScreenRect { left, top: bottom - thickness, right, bottom },
50
ScreenRect { left, top: top + thickness, right: left + thickness, bottom: bottom - thickness },
51
ScreenRect { left: right - thickness, top: top + thickness, right, bottom: bottom - thickness },
53
ScreenRect {
54
left,
55
top,
56
right,
57
bottom: top + thickness,
58
},
59
ScreenRect {
60
left,
61
top: bottom - thickness,
62
right,
63
bottom,
64
},
65
ScreenRect {
66
left,
67
top: top + thickness,
68
right: left + thickness,
69
bottom: bottom - thickness,
70
},
71
ScreenRect {
72
left: right - thickness,
73
top: top + thickness,
74
right,
75
bottom: bottom - thickness,
76
},
52
77
]
53
78
}
54
79
@@ -67,8 +92,14 @@ pub fn mini_rect(work: WorkArea, saved: Option<(i32, i32)>) -> ScreenRect {
67
92
}
68
93
}
69
94
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)
95
pub fn mini_work_area(
96
main: WorkArea,
97
saved: Option<(i32, i32)>,
98
area_at: impl Fn(i32, i32) -> Option<WorkArea>,
99
) -> WorkArea {
100
saved
101
.and_then(|(left, top)| area_at(left, top))
102
.unwrap_or(main)
72
103
}
73
104
74
105
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {
@@ -89,18 +120,33 @@ mod tests {
89
120
use super::*;
90
121
91
122
fn work(scale: f32) -> WorkArea {
92
WorkArea { left: 0, top: 0, right: 1920, bottom: 1040, scale }
123
WorkArea {
124
left: 0,
125
top: 0,
126
right: 1920,
127
bottom: 1040,
128
scale,
129
}
93
130
}
94
131
95
132
#[test]
96
133
fn bar_is_centred_at_the_top() {
97
134
let rect = bar_rect(work(1.), false);
98
assert_eq!((rect.left, rect.top, rect.right, rect.bottom), (770, 0, 1150, 40));
135
assert_eq!(
136
(rect.left, rect.top, rect.right, rect.bottom),
137
(770, 0, 1150, 40)
138
);
99
139
}
100
140
101
141
#[test]
102
142
fn bar_follows_a_secondary_monitor_and_scale() {
103
let second = WorkArea { left: 1920, top: 100, right: 3840, bottom: 1140, scale: 1.5 };
143
let second = WorkArea {
144
left: 1920,
145
top: 100,
146
right: 3840,
147
bottom: 1140,
148
scale: 1.5,
149
};
104
150
let rect = bar_rect(second, false);
105
151
assert_eq!(rect.width(), 570);
106
152
assert_eq!(rect.height(), 60);
@@ -130,17 +176,33 @@ mod tests {
130
176
131
177
#[test]
132
178
fn border_rects_frame_the_target_without_overlap() {
133
let target = ScreenRect { left: 100, top: 50, right: 500, bottom: 350 };
179
let target = ScreenRect {
180
left: 100,
181
top: 50,
182
right: 500,
183
bottom: 350,
184
};
134
185
let [top, bottom, left, right] = border_rects(target, 4);
135
assert_eq!((top.left, top.top, top.right, top.bottom), (100, 50, 500, 54));
186
assert_eq!(
187
(top.left, top.top, top.right, top.bottom),
188
(100, 50, 500, 54)
189
);
136
190
assert_eq!((bottom.top, bottom.bottom), (346, 350));
137
assert_eq!((left.left, left.right, left.top, left.bottom), (100, 104, 54, 346));
191
assert_eq!(
192
(left.left, left.right, left.top, left.bottom),
193
(100, 104, 54, 346)
194
);
138
195
assert_eq!((right.left, right.right), (496, 500));
139
196
}
140
197
141
198
#[test]
142
199
fn border_thickness_never_exceeds_half_the_target() {
143
let target = ScreenRect { left: 0, top: 0, right: 6, bottom: 100 };
200
let target = ScreenRect {
201
left: 0,
202
top: 0,
203
right: 6,
204
bottom: 100,
205
};
144
206
let [top, _, left, right] = border_rects(target, 4);
145
207
assert_eq!(top.bottom, 3);
146
208
assert_eq!(left.right, 3);
@@ -150,7 +212,10 @@ mod tests {
150
212
#[test]
151
213
fn mini_defaults_to_the_bottom_right_corner() {
152
214
let rect = mini_rect(work(1.), None);
153
assert_eq!((rect.left, rect.top, rect.right, rect.bottom), (1584, 844, 1904, 1024));
215
assert_eq!(
216
(rect.left, rect.top, rect.right, rect.bottom),
217
(1584, 844, 1904, 1024)
218
);
154
219
}
155
220
156
221
#[test]
@@ -164,12 +229,21 @@ mod tests {
164
229
165
230
#[test]
166
231
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. };
232
let second = WorkArea {
233
left: 1920,
234
top: 0,
235
right: 3840,
236
bottom: 1040,
237
scale: 1.,
238
};
168
239
let area_at = |left: i32, _: i32| (left >= 1920).then_some(second);
169
240
let saved = Some((3700, 900));
170
241
let rect = mini_rect(mini_work_area(work(1.), saved, area_at), saved);
171
242
assert_eq!((rect.right, rect.bottom), (3840, 1040));
172
assert_eq!(mini_work_area(work(1.), Some((100, 100)), area_at), work(1.));
243
assert_eq!(
244
mini_work_area(work(1.), Some((100, 100)), area_at),
245
work(1.)
246
);
173
247
assert_eq!(mini_work_area(work(1.), None, area_at), work(1.));
174
248
}
175
249
@@ -188,7 +262,10 @@ mod tests {
188
262
189
263
#[test]
190
264
fn position_round_trips() {
191
assert_eq!(parse_position(&format_position(-1200, 80)), Some((-1200, 80)));
265
assert_eq!(
266
parse_position(&format_position(-1200, 80)),
267
Some((-1200, 80))
268
);
192
269
assert_eq!(parse_position("garbage"), None);
193
270
}
194
271
}
@@ -43,12 +43,37 @@ pub fn bar_collapsed(pinned: bool, idle: Duration) -> bool {43
43
44
pub fn border_rects(target: ScreenRect, thickness: i32) -> [ScreenRect; 4] {44
pub fn border_rects(target: ScreenRect, thickness: i32) -> [ScreenRect; 4] {45
let thickness = thickness.clamp(1, (target.width().min(target.height()) / 2).max(1));45
let thickness = thickness.clamp(1, (target.width().min(target.height()) / 2).max(1));46
let ScreenRect { left, top, right, bottom } = target;46
let ScreenRect {47
left,48
top,49
right,50
bottom,51
} = target;47
[52
[48
ScreenRect { left, top, right, bottom: top + thickness },53
ScreenRect {49
ScreenRect { left, top: bottom - thickness, right, bottom },54
left,50
ScreenRect { left, top: top + thickness, right: left + thickness, bottom: bottom - thickness },55
top,51
ScreenRect { left: right - thickness, top: top + thickness, right, bottom: bottom - thickness },56
right,57
bottom: top + thickness,58
},59
ScreenRect {60
left,61
top: bottom - thickness,62
right,63
bottom,64
},65
ScreenRect {66
left,67
top: top + thickness,68
right: left + thickness,69
bottom: bottom - thickness,70
},71
ScreenRect {72
left: right - thickness,73
top: top + thickness,74
right,75
bottom: bottom - thickness,76
},52
]77
]53
}78
}54
79
@@ -67,8 +92,14 @@ pub fn mini_rect(work: WorkArea, saved: Option<(i32, i32)>) -> ScreenRect {67
}92
}68
}93
}69
94
70
pub fn mini_work_area(main: WorkArea, saved: Option<(i32, i32)>, area_at: impl Fn(i32, i32) -> Option<WorkArea>) -> WorkArea {95
pub fn mini_work_area(71
saved.and_then(|(left, top)| area_at(left, top)).unwrap_or(main)96
main: WorkArea,97
saved: Option<(i32, i32)>,98
area_at: impl Fn(i32, i32) -> Option<WorkArea>,99
) -> WorkArea {100
saved101
.and_then(|(left, top)| area_at(left, top))102
.unwrap_or(main)72
}103
}73
104
74
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {105
pub fn mini_wanted(call_active: bool, main_minimized: bool) -> bool {@@ -89,18 +120,33 @@ mod tests {89
use super::*;120
use super::*;90
121
91
fn work(scale: f32) -> WorkArea {122
fn work(scale: f32) -> WorkArea {92
WorkArea { left: 0, top: 0, right: 1920, bottom: 1040, scale }123
WorkArea {124
left: 0,125
top: 0,126
right: 1920,127
bottom: 1040,128
scale,129
}93
}130
}94
131
95
#[test]132
#[test]96
fn bar_is_centred_at_the_top() {133
fn bar_is_centred_at_the_top() {97
let rect = bar_rect(work(1.), false);134
let rect = bar_rect(work(1.), false);98
assert_eq!((rect.left, rect.top, rect.right, rect.bottom), (770, 0, 1150, 40));135
assert_eq!(136
(rect.left, rect.top, rect.right, rect.bottom),137
(770, 0, 1150, 40)138
);99
}139
}100
140
101
#[test]141
#[test]102
fn bar_follows_a_secondary_monitor_and_scale() {142
fn bar_follows_a_secondary_monitor_and_scale() {103
let second = WorkArea { left: 1920, top: 100, right: 3840, bottom: 1140, scale: 1.5 };143
let second = WorkArea {144
left: 1920,145
top: 100,146
right: 3840,147
bottom: 1140,148
scale: 1.5,149
};104
let rect = bar_rect(second, false);150
let rect = bar_rect(second, false);105
assert_eq!(rect.width(), 570);151
assert_eq!(rect.width(), 570);106
assert_eq!(rect.height(), 60);152
assert_eq!(rect.height(), 60);@@ -130,17 +176,33 @@ mod tests {130
176
131
#[test]177
#[test]132
fn border_rects_frame_the_target_without_overlap() {178
fn border_rects_frame_the_target_without_overlap() {133
let target = ScreenRect { left: 100, top: 50, right: 500, bottom: 350 };179
let target = ScreenRect {180
left: 100,181
top: 50,182
right: 500,183
bottom: 350,184
};134
let [top, bottom, left, right] = border_rects(target, 4);185
let [top, bottom, left, right] = border_rects(target, 4);135
assert_eq!((top.left, top.top, top.right, top.bottom), (100, 50, 500, 54));186
assert_eq!(187
(top.left, top.top, top.right, top.bottom),188
(100, 50, 500, 54)189
);136
assert_eq!((bottom.top, bottom.bottom), (346, 350));190
assert_eq!((bottom.top, bottom.bottom), (346, 350));137
assert_eq!((left.left, left.right, left.top, left.bottom), (100, 104, 54, 346));191
assert_eq!(192
(left.left, left.right, left.top, left.bottom),193
(100, 104, 54, 346)194
);138
assert_eq!((right.left, right.right), (496, 500));195
assert_eq!((right.left, right.right), (496, 500));139
}196
}140
197
141
#[test]198
#[test]142
fn border_thickness_never_exceeds_half_the_target() {199
fn border_thickness_never_exceeds_half_the_target() {143
let target = ScreenRect { left: 0, top: 0, right: 6, bottom: 100 };200
let target = ScreenRect {201
left: 0,202
top: 0,203
right: 6,204
bottom: 100,205
};144
let [top, _, left, right] = border_rects(target, 4);206
let [top, _, left, right] = border_rects(target, 4);145
assert_eq!(top.bottom, 3);207
assert_eq!(top.bottom, 3);146
assert_eq!(left.right, 3);208
assert_eq!(left.right, 3);@@ -150,7 +212,10 @@ mod tests {150
#[test]212
#[test]151
fn mini_defaults_to_the_bottom_right_corner() {213
fn mini_defaults_to_the_bottom_right_corner() {152
let rect = mini_rect(work(1.), None);214
let rect = mini_rect(work(1.), None);153
assert_eq!((rect.left, rect.top, rect.right, rect.bottom), (1584, 844, 1904, 1024));215
assert_eq!(216
(rect.left, rect.top, rect.right, rect.bottom),217
(1584, 844, 1904, 1024)218
);154
}219
}155
220
156
#[test]221
#[test]@@ -164,12 +229,21 @@ mod tests {164
229
165
#[test]230
#[test]166
fn mini_stays_on_the_monitor_that_holds_the_saved_point() {231
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. };232
let second = WorkArea {233
left: 1920,234
top: 0,235
right: 3840,236
bottom: 1040,237
scale: 1.,238
};168
let area_at = |left: i32, _: i32| (left >= 1920).then_some(second);239
let area_at = |left: i32, _: i32| (left >= 1920).then_some(second);169
let saved = Some((3700, 900));240
let saved = Some((3700, 900));170
let rect = mini_rect(mini_work_area(work(1.), saved, area_at), saved);241
let rect = mini_rect(mini_work_area(work(1.), saved, area_at), saved);171
assert_eq!((rect.right, rect.bottom), (3840, 1040));242
assert_eq!((rect.right, rect.bottom), (3840, 1040));172
assert_eq!(mini_work_area(work(1.), Some((100, 100)), area_at), work(1.));243
assert_eq!(244
mini_work_area(work(1.), Some((100, 100)), area_at),245
work(1.)246
);173
assert_eq!(mini_work_area(work(1.), None, area_at), work(1.));247
assert_eq!(mini_work_area(work(1.), None, area_at), work(1.));174
}248
}175
249
@@ -188,7 +262,10 @@ mod tests {188
262
189
#[test]263
#[test]190
fn position_round_trips() {264
fn position_round_trips() {191
assert_eq!(parse_position(&format_position(-1200, 80)), Some((-1200, 80)));265
assert_eq!(266
parse_position(&format_position(-1200, 80)),267
Some((-1200, 80))268
);192
assert_eq!(parse_position("garbage"), None);269
assert_eq!(parse_position("garbage"), None);193
}270
}194
}271
}@@ -28,8 +28,16 @@ impl CallPictures {
28
28
let now = Instant::now();
29
29
for (key, picture) in hub.drain() {
30
30
let picture = Arc::try_unwrap(picture).unwrap_or_else(|shared| (*shared).clone());
31
let Some(image) = render_image(picture) else { continue };
32
if let Some(previous) = self.shown.insert(key, Shown { image, updated: now }) {
31
let Some(image) = render_image(picture) else {
32
continue;
33
};
34
if let Some(previous) = self.shown.insert(
35
key,
36
Shown {
37
image,
38
updated: now,
39
},
40
) {
33
41
cx.drop_image(previous.image, None);
34
42
}
35
43
}
@@ -28,8 +28,16 @@ impl CallPictures {28
let now = Instant::now();28
let now = Instant::now();29
for (key, picture) in hub.drain() {29
for (key, picture) in hub.drain() {30
let picture = Arc::try_unwrap(picture).unwrap_or_else(|shared| (*shared).clone());30
let picture = Arc::try_unwrap(picture).unwrap_or_else(|shared| (*shared).clone());31
let Some(image) = render_image(picture) else { continue };31
let Some(image) = render_image(picture) else {32
if let Some(previous) = self.shown.insert(key, Shown { image, updated: now }) {32
continue;33
};34
if let Some(previous) = self.shown.insert(35
key,36
Shown {37
image,38
updated: now,39
},40
) {33
cx.drop_image(previous.image, None);41
cx.drop_image(previous.image, None);34
}42
}35
}43
}@@ -68,12 +68,17 @@ impl CameraPreview {
68
68
);
69
69
match started {
70
70
Ok(capture) => self.capture = Some(capture),
71
Err(error) => *self.failure.lock().expect("preview failure lock") = Some(error.to_string()),
71
Err(error) => {
72
*self.failure.lock().expect("preview failure lock") = Some(error.to_string())
73
}
72
74
}
73
75
}
74
76
75
77
pub fn set_background(&self, choice: BackgroundChoice) {
76
let mut latest = self.background_request.lock().expect("background request lock");
78
let mut latest = self
79
.background_request
80
.lock()
81
.expect("background request lock");
77
82
*latest += 1;
78
83
let request = *latest;
79
84
match choice {
@@ -124,7 +129,10 @@ impl CameraPreview {
124
129
if elapsed < FPS_WINDOW {
125
130
return;
126
131
}
127
self.fps = self.capture.is_some().then(|| frames_per_second(total.saturating_sub(previous), elapsed));
132
self.fps = self
133
.capture
134
.is_some()
135
.then(|| frames_per_second(total.saturating_sub(previous), elapsed));
128
136
self.counted = (now, total);
129
137
}
130
138
@@ -153,23 +161,39 @@ pub fn preview_backgrounds(library: &BackgroundLibrary) -> Vec<(BackgroundPick,
153
161
.shown()
154
162
.iter()
155
163
.filter(|image| library.cached_image(&image.id).is_some())
156
.map(|image| (BackgroundPick::Default(image.id.clone()), image.name.clone()));
157
let customs = library.customs.iter().filter(|path| path.exists()).map(|path| {
158
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());
159
(BackgroundPick::Custom(path.clone()), name)
160
});
161
[(BackgroundPick::None, "None".to_owned()), (BackgroundPick::Blur, "Blur".to_owned())]
162
.into_iter()
163
.chain(defaults)
164
.chain(customs)
165
.collect()
164
.map(|image| {
165
(
166
BackgroundPick::Default(image.id.clone()),
167
image.name.clone(),
168
)
169
});
170
let customs = library
171
.customs
172
.iter()
173
.filter(|path| path.exists())
174
.map(|path| {
175
let name = path
176
.file_name()
177
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
178
(BackgroundPick::Custom(path.clone()), name)
179
});
180
[
181
(BackgroundPick::None, "None".to_owned()),
182
(BackgroundPick::Blur, "Blur".to_owned()),
183
]
184
.into_iter()
185
.chain(defaults)
186
.chain(customs)
187
.collect()
166
188
}
167
189
168
190
#[cfg(test)]
169
191
mod tests {
170
192
use std::time::{Duration, Instant};
171
193
172
use super::{BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds};
194
use super::{
195
BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds,
196
};
173
197
174
198
#[test]
175
199
fn frames_per_second_divides_by_elapsed_time() {
@@ -180,8 +204,12 @@ mod tests {
180
204
181
205
#[test]
182
206
fn the_background_choices_start_with_none_and_blur() {
183
let library = BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));
184
let picks: Vec<BackgroundPick> = preview_backgrounds(&library).into_iter().map(|(pick, _)| pick).collect();
207
let library =
208
BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));
209
let picks: Vec<BackgroundPick> = preview_backgrounds(&library)
210
.into_iter()
211
.map(|(pick, _)| pick)
212
.collect();
185
213
assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);
186
214
}
187
215
@@ -68,12 +68,17 @@ impl CameraPreview {68
);68
);69
match started {69
match started {70
Ok(capture) => self.capture = Some(capture),70
Ok(capture) => self.capture = Some(capture),71
Err(error) => *self.failure.lock().expect("preview failure lock") = Some(error.to_string()),71
Err(error) => {72
*self.failure.lock().expect("preview failure lock") = Some(error.to_string())73
}72
}74
}73
}75
}74
76
75
pub fn set_background(&self, choice: BackgroundChoice) {77
pub fn set_background(&self, choice: BackgroundChoice) {76
let mut latest = self.background_request.lock().expect("background request lock");78
let mut latest = self79
.background_request80
.lock()81
.expect("background request lock");77
*latest += 1;82
*latest += 1;78
let request = *latest;83
let request = *latest;79
match choice {84
match choice {@@ -124,7 +129,10 @@ impl CameraPreview {124
if elapsed < FPS_WINDOW {129
if elapsed < FPS_WINDOW {125
return;130
return;126
}131
}127
self.fps = self.capture.is_some().then(|| frames_per_second(total.saturating_sub(previous), elapsed));132
self.fps = self133
.capture134
.is_some()135
.then(|| frames_per_second(total.saturating_sub(previous), elapsed));128
self.counted = (now, total);136
self.counted = (now, total);129
}137
}130
138
@@ -153,23 +161,39 @@ pub fn preview_backgrounds(library: &BackgroundLibrary) -> Vec<(BackgroundPick,153
.shown()161
.shown()154
.iter()162
.iter()155
.filter(|image| library.cached_image(&image.id).is_some())163
.filter(|image| library.cached_image(&image.id).is_some())156
.map(|image| (BackgroundPick::Default(image.id.clone()), image.name.clone()));164
.map(|image| {157
let customs = library.customs.iter().filter(|path| path.exists()).map(|path| {165
(158
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());166
BackgroundPick::Default(image.id.clone()),159
(BackgroundPick::Custom(path.clone()), name)167
image.name.clone(),160
});168
)161
[(BackgroundPick::None, "None".to_owned()), (BackgroundPick::Blur, "Blur".to_owned())]169
});162
.into_iter()170
let customs = library163
.chain(defaults)171
.customs164
.chain(customs)172
.iter()165
.collect()173
.filter(|path| path.exists())174
.map(|path| {175
let name = path176
.file_name()177
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());178
(BackgroundPick::Custom(path.clone()), name)179
});180
[181
(BackgroundPick::None, "None".to_owned()),182
(BackgroundPick::Blur, "Blur".to_owned()),183
]184
.into_iter()185
.chain(defaults)186
.chain(customs)187
.collect()166
}188
}167
189
168
#[cfg(test)]190
#[cfg(test)]169
mod tests {191
mod tests {170
use std::time::{Duration, Instant};192
use std::time::{Duration, Instant};171
193
172
use super::{BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds};194
use super::{195
BackgroundLibrary, BackgroundPick, CameraPreview, frames_per_second, preview_backgrounds,196
};173
197
174
#[test]198
#[test]175
fn frames_per_second_divides_by_elapsed_time() {199
fn frames_per_second_divides_by_elapsed_time() {@@ -180,8 +204,12 @@ mod tests {180
204
181
#[test]205
#[test]182
fn the_background_choices_start_with_none_and_blur() {206
fn the_background_choices_start_with_none_and_blur() {183
let library = BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));207
let library =184
let picks: Vec<BackgroundPick> = preview_backgrounds(&library).into_iter().map(|(pick, _)| pick).collect();208
BackgroundLibrary::new(std::env::temp_dir().join("teams-preview-test-no-cache"));209
let picks: Vec<BackgroundPick> = preview_backgrounds(&library)210
.into_iter()211
.map(|(pick, _)| pick)212
.collect();185
assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);213
assert_eq!(picks, vec![BackgroundPick::None, BackgroundPick::Blur]);186
}214
}187
215
@@ -14,7 +14,11 @@ pub struct RingEntry {
14
14
15
15
impl RingEntry {
16
16
pub fn caller_user_id(&self) -> Option<String> {
17
self.ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)
17
self.ring
18
.caller
19
.mri
20
.strip_prefix(ORGID_PREFIX)
21
.map(str::to_owned)
18
22
}
19
23
20
24
pub fn caller_name(&self) -> &str {
@@ -55,7 +59,11 @@ pub struct Rings {
55
59
56
60
impl Rings {
57
61
pub fn push(&mut self, ring: IncomingRing, demo: bool, now: Instant) {
58
if self.entries.iter().any(|entry| entry.ring.ring_id == ring.ring_id) {
62
if self
63
.entries
64
.iter()
65
.any(|entry| entry.ring.ring_id == ring.ring_id)
66
{
59
67
return;
60
68
}
61
69
self.entries.push(RingEntry {
@@ -66,7 +74,9 @@ impl Rings {
66
74
}
67
75
68
76
pub fn get(&self, ring_id: u64) -> Option<&RingEntry> {
69
self.entries.iter().find(|entry| entry.ring.ring_id == ring_id)
77
self.entries
78
.iter()
79
.find(|entry| entry.ring.ring_id == ring_id)
70
80
}
71
81
72
82
pub fn ringing(&self) -> impl Iterator<Item = &RingEntry> {
@@ -85,8 +95,16 @@ impl Rings {
85
95
self.entries.is_empty()
86
96
}
87
97
88
pub fn signal(&mut self, ring_id: u64, signal: RingSignal, now: Instant) -> Option<RingOutcome> {
89
let index = self.entries.iter().position(|entry| entry.ring.ring_id == ring_id)?;
98
pub fn signal(
99
&mut self,
100
ring_id: u64,
101
signal: RingSignal,
102
now: Instant,
103
) -> Option<RingOutcome> {
104
let index = self
105
.entries
106
.iter()
107
.position(|entry| entry.ring.ring_id == ring_id)?;
90
108
let next = self.entries[index].state.next(signal, now);
91
109
self.entries[index].state = next;
92
110
self.settle(index)
@@ -94,7 +112,11 @@ impl Rings {
94
112
95
113
pub fn tick(&mut self, now: Instant) -> Vec<(u64, RingOutcome)> {
96
114
let mut outcomes = Vec::new();
97
let ids: Vec<u64> = self.entries.iter().map(|entry| entry.ring.ring_id).collect();
115
let ids: Vec<u64> = self
116
.entries
117
.iter()
118
.map(|entry| entry.ring.ring_id)
119
.collect();
98
120
for ring_id in ids {
99
121
if let Some(outcome) = self.signal(ring_id, RingSignal::Tick, now) {
100
122
outcomes.push((ring_id, outcome));
@@ -162,7 +184,9 @@ mod tests {
162
184
rings.push(ring(1, false), false, start);
163
185
let outcomes = rings.tick(start + Duration::from_secs(30));
164
186
assert_eq!(outcomes.len(), 1);
165
let (ring_id, RingOutcome::Missed(missed)) = &outcomes[0] else { panic!("not missed") };
187
let (ring_id, RingOutcome::Missed(missed)) = &outcomes[0] else {
188
panic!("not missed")
189
};
166
190
assert_eq!(*ring_id, 1);
167
191
assert_eq!(missed.caller_name, "Cara");
168
192
assert_eq!(missed.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));
@@ -187,8 +211,14 @@ mod tests {
187
211
let mut rings = Rings::default();
188
212
rings.push(ring(1, false), false, start);
189
213
rings.push(ring(2, false), false, start);
190
assert_eq!(rings.signal(1, RingSignal::Accept, start), Some(RingOutcome::Gone));
191
assert_eq!(rings.signal(2, RingSignal::Decline, start), Some(RingOutcome::Gone));
214
assert_eq!(
215
rings.signal(1, RingSignal::Accept, start),
216
Some(RingOutcome::Gone)
217
);
218
assert_eq!(
219
rings.signal(2, RingSignal::Decline, start),
220
Some(RingOutcome::Gone)
221
);
192
222
assert!(rings.is_empty());
193
223
assert_eq!(rings.signal(1, RingSignal::Accept, start), None);
194
224
}
@@ -204,8 +234,15 @@ mod tests {
204
234
205
235
#[test]
206
236
fn video_calls_offer_audio_and_video_answers() {
207
let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };
208
let video = RingEntry { ring: ring(2, true), ..audio.clone() };
237
let audio = RingEntry {
238
ring: ring(1, false),
239
state: RingState::start(Instant::now()),
240
demo: false,
241
};
242
let video = RingEntry {
243
ring: ring(2, true),
244
..audio.clone()
245
};
209
246
assert_eq!(audio.subtitle(), "Incoming audio call");
210
247
assert_eq!(audio.accept_label(), "Accept");
211
248
assert_eq!(video.subtitle(), "Incoming video call");
@@ -217,7 +254,11 @@ mod tests {
217
254
fn group_rings_say_so() {
218
255
let mut group = ring(3, false);
219
256
group.is_group = true;
220
let entry = RingEntry { ring: group, state: RingState::start(Instant::now()), demo: false };
257
let entry = RingEntry {
258
ring: group,
259
state: RingState::start(Instant::now()),
260
demo: false,
261
};
221
262
assert_eq!(entry.subtitle(), "Incoming group audio call");
222
263
}
223
264
}
@@ -14,7 +14,11 @@ pub struct RingEntry {14
14
15
impl RingEntry {15
impl RingEntry {16
pub fn caller_user_id(&self) -> Option<String> {16
pub fn caller_user_id(&self) -> Option<String> {17
self.ring.caller.mri.strip_prefix(ORGID_PREFIX).map(str::to_owned)17
self.ring18
.caller19
.mri20
.strip_prefix(ORGID_PREFIX)21
.map(str::to_owned)18
}22
}19
23
20
pub fn caller_name(&self) -> &str {24
pub fn caller_name(&self) -> &str {@@ -55,7 +59,11 @@ pub struct Rings {55
59
56
impl Rings {60
impl Rings {57
pub fn push(&mut self, ring: IncomingRing, demo: bool, now: Instant) {61
pub fn push(&mut self, ring: IncomingRing, demo: bool, now: Instant) {58
if self.entries.iter().any(|entry| entry.ring.ring_id == ring.ring_id) {62
if self63
.entries64
.iter()65
.any(|entry| entry.ring.ring_id == ring.ring_id)66
{59
return;67
return;60
}68
}61
self.entries.push(RingEntry {69
self.entries.push(RingEntry {@@ -66,7 +74,9 @@ impl Rings {66
}74
}67
75
68
pub fn get(&self, ring_id: u64) -> Option<&RingEntry> {76
pub fn get(&self, ring_id: u64) -> Option<&RingEntry> {69
self.entries.iter().find(|entry| entry.ring.ring_id == ring_id)77
self.entries78
.iter()79
.find(|entry| entry.ring.ring_id == ring_id)70
}80
}71
81
72
pub fn ringing(&self) -> impl Iterator<Item = &RingEntry> {82
pub fn ringing(&self) -> impl Iterator<Item = &RingEntry> {@@ -85,8 +95,16 @@ impl Rings {85
self.entries.is_empty()95
self.entries.is_empty()86
}96
}87
97
88
pub fn signal(&mut self, ring_id: u64, signal: RingSignal, now: Instant) -> Option<RingOutcome> {98
pub fn signal(89
let index = self.entries.iter().position(|entry| entry.ring.ring_id == ring_id)?;99
&mut self,100
ring_id: u64,101
signal: RingSignal,102
now: Instant,103
) -> Option<RingOutcome> {104
let index = self105
.entries106
.iter()107
.position(|entry| entry.ring.ring_id == ring_id)?;90
let next = self.entries[index].state.next(signal, now);108
let next = self.entries[index].state.next(signal, now);91
self.entries[index].state = next;109
self.entries[index].state = next;92
self.settle(index)110
self.settle(index)@@ -94,7 +112,11 @@ impl Rings {94
112
95
pub fn tick(&mut self, now: Instant) -> Vec<(u64, RingOutcome)> {113
pub fn tick(&mut self, now: Instant) -> Vec<(u64, RingOutcome)> {96
let mut outcomes = Vec::new();114
let mut outcomes = Vec::new();97
let ids: Vec<u64> = self.entries.iter().map(|entry| entry.ring.ring_id).collect();115
let ids: Vec<u64> = self116
.entries117
.iter()118
.map(|entry| entry.ring.ring_id)119
.collect();98
for ring_id in ids {120
for ring_id in ids {99
if let Some(outcome) = self.signal(ring_id, RingSignal::Tick, now) {121
if let Some(outcome) = self.signal(ring_id, RingSignal::Tick, now) {100
outcomes.push((ring_id, outcome));122
outcomes.push((ring_id, outcome));@@ -162,7 +184,9 @@ mod tests {162
rings.push(ring(1, false), false, start);184
rings.push(ring(1, false), false, start);163
let outcomes = rings.tick(start + Duration::from_secs(30));185
let outcomes = rings.tick(start + Duration::from_secs(30));164
assert_eq!(outcomes.len(), 1);186
assert_eq!(outcomes.len(), 1);165
let (ring_id, RingOutcome::Missed(missed)) = &outcomes[0] else { panic!("not missed") };187
let (ring_id, RingOutcome::Missed(missed)) = &outcomes[0] else {188
panic!("not missed")189
};166
assert_eq!(*ring_id, 1);190
assert_eq!(*ring_id, 1);167
assert_eq!(missed.caller_name, "Cara");191
assert_eq!(missed.caller_name, "Cara");168
assert_eq!(missed.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));192
assert_eq!(missed.thread_id.as_deref(), Some("19:a_b@unq.gbl.spaces"));@@ -187,8 +211,14 @@ mod tests {187
let mut rings = Rings::default();211
let mut rings = Rings::default();188
rings.push(ring(1, false), false, start);212
rings.push(ring(1, false), false, start);189
rings.push(ring(2, false), false, start);213
rings.push(ring(2, false), false, start);190
assert_eq!(rings.signal(1, RingSignal::Accept, start), Some(RingOutcome::Gone));214
assert_eq!(191
assert_eq!(rings.signal(2, RingSignal::Decline, start), Some(RingOutcome::Gone));215
rings.signal(1, RingSignal::Accept, start),216
Some(RingOutcome::Gone)217
);218
assert_eq!(219
rings.signal(2, RingSignal::Decline, start),220
Some(RingOutcome::Gone)221
);192
assert!(rings.is_empty());222
assert!(rings.is_empty());193
assert_eq!(rings.signal(1, RingSignal::Accept, start), None);223
assert_eq!(rings.signal(1, RingSignal::Accept, start), None);194
}224
}@@ -204,8 +234,15 @@ mod tests {204
234
205
#[test]235
#[test]206
fn video_calls_offer_audio_and_video_answers() {236
fn video_calls_offer_audio_and_video_answers() {207
let audio = RingEntry { ring: ring(1, false), state: RingState::start(Instant::now()), demo: false };237
let audio = RingEntry {208
let video = RingEntry { ring: ring(2, true), ..audio.clone() };238
ring: ring(1, false),239
state: RingState::start(Instant::now()),240
demo: false,241
};242
let video = RingEntry {243
ring: ring(2, true),244
..audio.clone()245
};209
assert_eq!(audio.subtitle(), "Incoming audio call");246
assert_eq!(audio.subtitle(), "Incoming audio call");210
assert_eq!(audio.accept_label(), "Accept");247
assert_eq!(audio.accept_label(), "Accept");211
assert_eq!(video.subtitle(), "Incoming video call");248
assert_eq!(video.subtitle(), "Incoming video call");@@ -217,7 +254,11 @@ mod tests {217
fn group_rings_say_so() {254
fn group_rings_say_so() {218
let mut group = ring(3, false);255
let mut group = ring(3, false);219
group.is_group = true;256
group.is_group = true;220
let entry = RingEntry { ring: group, state: RingState::start(Instant::now()), demo: false };257
let entry = RingEntry {258
ring: group,259
state: RingState::start(Instant::now()),260
demo: false,261
};221
assert_eq!(entry.subtitle(), "Incoming group audio call");262
assert_eq!(entry.subtitle(), "Incoming group audio call");222
}263
}223
}264
}@@ -65,10 +65,17 @@ mod tests {
65
65
66
66
#[test]
67
67
fn a_one_on_one_chat_calls_the_other_person_by_name() {
68
let chat = chat("oneOnOne", "", &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")]);
68
let chat = chat(
69
"oneOnOne",
70
"",
71
&[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")],
72
);
69
73
let plan = plan_for_chat(&chat, Some(&me())).unwrap();
70
74
assert_eq!(plan.title, "Bea");
71
assert_eq!(plan.callees, vec![("8:orgid:bea-id".to_owned(), "Bea".to_owned())]);
75
assert_eq!(
76
plan.callees,
77
vec![("8:orgid:bea-id".to_owned(), "Bea".to_owned())]
78
);
72
79
}
73
80
74
81
#[test]
@@ -76,7 +83,11 @@ mod tests {
76
83
let chat = chat(
77
84
"group",
78
85
"Retro team",
79
&[(Some("me-id"), "Me"), (Some("bea-id"), "Bea"), (Some("cy-id"), "Cy")],
86
&[
87
(Some("me-id"), "Me"),
88
(Some("bea-id"), "Bea"),
89
(Some("cy-id"), "Cy"),
90
],
80
91
);
81
92
let plan = plan_for_chat(&chat, Some(&me())).unwrap();
82
93
assert_eq!(plan.title, "Retro team");
@@ -65,10 +65,17 @@ mod tests {65
65
66
#[test]66
#[test]67
fn a_one_on_one_chat_calls_the_other_person_by_name() {67
fn a_one_on_one_chat_calls_the_other_person_by_name() {68
let chat = chat("oneOnOne", "", &[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")]);68
let chat = chat(69
"oneOnOne",70
"",71
&[(Some("me-id"), "Me"), (Some("bea-id"), "Bea")],72
);69
let plan = plan_for_chat(&chat, Some(&me())).unwrap();73
let plan = plan_for_chat(&chat, Some(&me())).unwrap();70
assert_eq!(plan.title, "Bea");74
assert_eq!(plan.title, "Bea");71
assert_eq!(plan.callees, vec![("8:orgid:bea-id".to_owned(), "Bea".to_owned())]);75
assert_eq!(76
plan.callees,77
vec![("8:orgid:bea-id".to_owned(), "Bea".to_owned())]78
);72
}79
}73
80
74
#[test]81
#[test]@@ -76,7 +83,11 @@ mod tests {76
let chat = chat(83
let chat = chat(77
"group",84
"group",78
"Retro team",85
"Retro team",79
&[(Some("me-id"), "Me"), (Some("bea-id"), "Bea"), (Some("cy-id"), "Cy")],86
&[87
(Some("me-id"), "Me"),88
(Some("bea-id"), "Bea"),89
(Some("cy-id"), "Cy"),90
],80
);91
);81
let plan = plan_for_chat(&chat, Some(&me())).unwrap();92
let plan = plan_for_chat(&chat, Some(&me())).unwrap();82
assert_eq!(plan.title, "Retro team");93
assert_eq!(plan.title, "Retro team");@@ -259,9 +259,8 @@ impl AppState {
259
259
Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),
260
260
_ => None,
261
261
};
262
let is_listed = |state: &Self, chat_id: &str| {
263
state.sidebar.chats.iter().any(|chat| chat.id == chat_id)
264
};
262
let is_listed =
263
|state: &Self, chat_id: &str| state.sidebar.chats.iter().any(|chat| chat.id == chat_id);
265
264
let was_listed = selected
266
265
.as_deref()
267
266
.is_some_and(|chat_id| is_listed(self, chat_id));
@@ -259,9 +259,8 @@ impl AppState {259
Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),259
Some(Selection::Chat(chat_id)) => Some(chat_id.clone()),260
_ => None,260
_ => None,261
};261
};262
let is_listed = |state: &Self, chat_id: &str| {262
let is_listed =263
state.sidebar.chats.iter().any(|chat| chat.id == chat_id)263
|state: &Self, chat_id: &str| state.sidebar.chats.iter().any(|chat| chat.id == chat_id);264
};265
let was_listed = selected264
let was_listed = selected266
.as_deref()265
.as_deref()267
.is_some_and(|chat_id| is_listed(self, chat_id));266
.is_some_and(|chat_id| is_listed(self, chat_id));@@ -19,7 +19,14 @@ pub fn install(path: PathBuf) {
19
19
fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String {
20
20
let location = info
21
21
.location()
22
.map(|location| format!("{}:{}:{}", location.file(), location.line(), location.column()))
22
.map(|location| {
23
format!(
24
"{}:{}:{}",
25
location.file(),
26
location.line(),
27
location.column()
28
)
29
})
23
30
.unwrap_or_default();
24
31
let thread = std::thread::current();
25
32
format!(
@@ -19,7 +19,14 @@ pub fn install(path: PathBuf) {19
fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String {19
fn entry(info: &PanicHookInfo<'_>, backtrace: &str) -> String {20
let location = info20
let location = info21
.location()21
.location()22
.map(|location| format!("{}:{}:{}", location.file(), location.line(), location.column()))22
.map(|location| {23
format!(24
"{}:{}:{}",25
location.file(),26
location.line(),27
location.column()28
)29
})23
.unwrap_or_default();30
.unwrap_or_default();24
let thread = std::thread::current();31
let thread = std::thread::current();25
format!(32
format!(@@ -10,9 +10,9 @@ use store::{
10
10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,
11
11
};
12
12
use teams_core::{
13
Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
14
LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage,
15
TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
13
Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview,
14
MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage, TaskDialog,
15
TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
16
16
};
17
17
18
18
use crate::activity::{Actor, Entry, Kind};
@@ -595,8 +595,12 @@ pub fn language_stamps(conversation_id: &str) -> HashMap<String, String> {
595
595
596
596
pub fn translations(message_ids: &[String]) -> Vec<Translation> {
597
597
let translated = |message_id: &str| match message_id {
598
FRENCH_MESSAGE => Some("<p>Hello everyone, <strong>version 0.2</strong> is ready. Can you check the checklist before Friday?</p>"),
599
SPANISH_MESSAGE => Some("<p>Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.</p>"),
598
FRENCH_MESSAGE => Some(
599
"<p>Hello everyone, <strong>version 0.2</strong> is ready. Can you check the checklist before Friday?</p>",
600
),
601
SPANISH_MESSAGE => Some(
602
"<p>Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.</p>",
603
),
600
604
_ => None,
601
605
};
602
606
message_ids
@@ -1221,7 +1225,9 @@ fn meeting_link_messages() -> Vec<MessageRecord> {
1221
1225
None,
1222
1226
mara,
1223
1227
at(0, 13, 38),
1224
&format!("<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"),
1228
&format!(
1229
"<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"
1230
),
1225
1231
"[]",
1226
1232
false,
1227
1233
)]
@@ -10,9 +10,9 @@ use store::{10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,10
ChannelTabRecord, ChatRecord, MemberRecord, MessageRecord, Store, TeamLayoutRecord, TeamRecord,11
};11
};12
use teams_core::{12
use teams_core::{13
Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,13
Activity, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview,14
LinkPreview, MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage,14
MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage, TaskDialog,15
TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,15
TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,16
};16
};17
17
18
use crate::activity::{Actor, Entry, Kind};18
use crate::activity::{Actor, Entry, Kind};@@ -595,8 +595,12 @@ pub fn language_stamps(conversation_id: &str) -> HashMap<String, String> {595
595
596
pub fn translations(message_ids: &[String]) -> Vec<Translation> {596
pub fn translations(message_ids: &[String]) -> Vec<Translation> {597
let translated = |message_id: &str| match message_id {597
let translated = |message_id: &str| match message_id {598
FRENCH_MESSAGE => Some("<p>Hello everyone, <strong>version 0.2</strong> is ready. Can you check the checklist before Friday?</p>"),598
FRENCH_MESSAGE => Some(599
SPANISH_MESSAGE => Some("<p>Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.</p>"),599
"<p>Hello everyone, <strong>version 0.2</strong> is ready. Can you check the checklist before Friday?</p>",600
),601
SPANISH_MESSAGE => Some(602
"<p>Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.</p>",603
),600
_ => None,604
_ => None,601
};605
};602
message_ids606
message_ids@@ -1221,7 +1225,9 @@ fn meeting_link_messages() -> Vec<MessageRecord> {1221
None,1225
None,1222
mara,1226
mara,1223
at(0, 13, 38),1227
at(0, 13, 38),1224
&format!("<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"),1228
&format!(1229
"<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"1230
),1225
"[]",1231
"[]",1226
false,1232
false,1227
)]1233
)]@@ -8,7 +8,13 @@ const MAX_BYTES: u64 = 1024 * 1024;
8
8
9
9
static PATH: OnceLock<PathBuf> = OnceLock::new();
10
10
11
const WEBRTC_AUDIO_MARKERS: [&str; 5] = ["AdmProxy", "audio_device", "core_audio", "WebRtcVoiceEngine", "webrtc_voice_engine"];
11
const WEBRTC_AUDIO_MARKERS: [&str; 5] = [
12
"AdmProxy",
13
"audio_device",
14
"core_audio",
15
"WebRtcVoiceEngine",
16
"webrtc_voice_engine",
17
];
12
18
const WEBRTC_SKIPPED: [&str; 1] = ["audio_device_buffer"];
13
19
const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;
14
20
@@ -40,7 +46,9 @@ impl log::Log for WebrtcAudioLog {
40
46
}
41
47
42
48
fn keeps_webrtc_line(text: &str) -> bool {
43
WEBRTC_AUDIO_MARKERS.iter().any(|marker| text.contains(marker))
49
WEBRTC_AUDIO_MARKERS
50
.iter()
51
.any(|marker| text.contains(marker))
44
52
&& !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))
45
53
&& !is_endpoint_dump(text)
46
54
}
@@ -89,10 +97,18 @@ mod tests {
89
97
#[test]
90
98
fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {
91
99
assert!(keeps_webrtc_line("(audio_device_impl.cc:123): Init"));
92
assert!(keeps_webrtc_line("(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"));
93
assert!(!keeps_webrtc_line("(audio_device_core_win.cc:4090): endpoint 3"));
94
assert!(keeps_webrtc_line("(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"));
95
assert!(!keeps_webrtc_line("(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"));
100
assert!(keeps_webrtc_line(
101
"(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"
102
));
103
assert!(!keeps_webrtc_line(
104
"(audio_device_core_win.cc:4090): endpoint 3"
105
));
106
assert!(keeps_webrtc_line(
107
"(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"
108
));
109
assert!(!keeps_webrtc_line(
110
"(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"
111
));
96
112
assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));
97
113
}
98
114
}
@@ -8,7 +8,13 @@ const MAX_BYTES: u64 = 1024 * 1024;8
8
9
static PATH: OnceLock<PathBuf> = OnceLock::new();9
static PATH: OnceLock<PathBuf> = OnceLock::new();10
10
11
const WEBRTC_AUDIO_MARKERS: [&str; 5] = ["AdmProxy", "audio_device", "core_audio", "WebRtcVoiceEngine", "webrtc_voice_engine"];11
const WEBRTC_AUDIO_MARKERS: [&str; 5] = [12
"AdmProxy",13
"audio_device",14
"core_audio",15
"WebRtcVoiceEngine",16
"webrtc_voice_engine",17
];12
const WEBRTC_SKIPPED: [&str; 1] = ["audio_device_buffer"];18
const WEBRTC_SKIPPED: [&str; 1] = ["audio_device_buffer"];13
const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;19
const ENDPOINT_DUMP_LINES: std::ops::Range<u32> = 4040..4170;14
20
@@ -40,7 +46,9 @@ impl log::Log for WebrtcAudioLog {40
}46
}41
47
42
fn keeps_webrtc_line(text: &str) -> bool {48
fn keeps_webrtc_line(text: &str) -> bool {43
WEBRTC_AUDIO_MARKERS.iter().any(|marker| text.contains(marker))49
WEBRTC_AUDIO_MARKERS50
.iter()51
.any(|marker| text.contains(marker))44
&& !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))52
&& !WEBRTC_SKIPPED.iter().any(|skipped| text.contains(skipped))45
&& !is_endpoint_dump(text)53
&& !is_endpoint_dump(text)46
}54
}@@ -89,10 +97,18 @@ mod tests {89
#[test]97
#[test]90
fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {98
fn audio_lines_are_kept_and_endpoint_dumps_and_noise_are_skipped() {91
assert!(keeps_webrtc_line("(audio_device_impl.cc:123): Init"));99
assert!(keeps_webrtc_line("(audio_device_impl.cc:123): Init"));92
assert!(keeps_webrtc_line("(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"));100
assert!(keeps_webrtc_line(93
assert!(!keeps_webrtc_line("(audio_device_core_win.cc:4090): endpoint 3"));101
"(webrtc_voice_engine.cc:10): WebRtcVoiceEngine::Init"94
assert!(keeps_webrtc_line("(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"));102
));95
assert!(!keeps_webrtc_line("(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"));103
assert!(!keeps_webrtc_line(104
"(audio_device_core_win.cc:4090): endpoint 3"105
));106
assert!(keeps_webrtc_line(107
"(audio_device_core_win.cc:412): AvRevertMmThreadCharacteristics() is OK"108
));109
assert!(!keeps_webrtc_line(110
"(audio_device_buffer.cc:450): [REC : 10000msec, 48kHz] callbacks: 1000"111
));96
assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));112
assert!(!keeps_webrtc_line("(peer_connection.cc:55): something"));97
}113
}98
}114
}@@ -211,12 +211,18 @@ mod tests {
211
211
#[test]
212
212
fn post_time_adds_the_day_when_not_today() {
213
213
assert_eq!(post_time_label(utc(7, 13), today(), zero()), "13:05");
214
assert_eq!(post_time_label(utc(6, 9), today(), zero()), "Yesterday 09:05");
214
assert_eq!(
215
post_time_label(utc(6, 9), today(), zero()),
216
"Yesterday 09:05"
217
);
215
218
assert_eq!(post_time_label(utc(5, 13), today(), zero()), "Mon 13:05");
216
219
let september = Utc.with_ymd_and_hms(2026, 9, 30, 8, 42, 0).unwrap();
217
220
assert_eq!(post_time_label(september, today(), zero()), "Sep 30 08:42");
218
221
let last_year = Utc.with_ymd_and_hms(2020, 5, 22, 8, 42, 0).unwrap();
219
assert_eq!(post_time_label(last_year, today(), zero()), "May 22, 2020 08:42");
222
assert_eq!(
223
post_time_label(last_year, today(), zero()),
224
"May 22, 2020 08:42"
225
);
220
226
}
221
227
222
228
#[test]
@@ -211,12 +211,18 @@ mod tests {211
#[test]211
#[test]212
fn post_time_adds_the_day_when_not_today() {212
fn post_time_adds_the_day_when_not_today() {213
assert_eq!(post_time_label(utc(7, 13), today(), zero()), "13:05");213
assert_eq!(post_time_label(utc(7, 13), today(), zero()), "13:05");214
assert_eq!(post_time_label(utc(6, 9), today(), zero()), "Yesterday 09:05");214
assert_eq!(215
post_time_label(utc(6, 9), today(), zero()),216
"Yesterday 09:05"217
);215
assert_eq!(post_time_label(utc(5, 13), today(), zero()), "Mon 13:05");218
assert_eq!(post_time_label(utc(5, 13), today(), zero()), "Mon 13:05");216
let september = Utc.with_ymd_and_hms(2026, 9, 30, 8, 42, 0).unwrap();219
let september = Utc.with_ymd_and_hms(2026, 9, 30, 8, 42, 0).unwrap();217
assert_eq!(post_time_label(september, today(), zero()), "Sep 30 08:42");220
assert_eq!(post_time_label(september, today(), zero()), "Sep 30 08:42");218
let last_year = Utc.with_ymd_and_hms(2020, 5, 22, 8, 42, 0).unwrap();221
let last_year = Utc.with_ymd_and_hms(2020, 5, 22, 8, 42, 0).unwrap();219
assert_eq!(post_time_label(last_year, today(), zero()), "May 22, 2020 08:42");222
assert_eq!(223
post_time_label(last_year, today(), zero()),224
"May 22, 2020 08:42"225
);220
}226
}221
227
222
#[test]228
#[test]@@ -130,7 +130,11 @@ mod tests {
130
130
let mut deleted = record("d", 7, "<img src=\"https://x/deleted\">");
131
131
deleted.deleted = true;
132
132
let records = [
133
record("a", 6, "<p>first</p><img src=\"https://x/one\"><img src=\"https://x/two\">"),
133
record(
134
"a",
135
6,
136
"<p>first</p><img src=\"https://x/one\"><img src=\"https://x/two\">",
137
),
134
138
record("b", 6, "<p>no image</p>"),
135
139
deleted,
136
140
record("c", 7, "<img src=\"https://x/three\">"),
@@ -145,7 +149,11 @@ mod tests {
145
149
#[test]
146
150
fn items_carry_author_caption_and_time() {
147
151
let records = [
148
record("a", 6, "<p>Release notes</p><p>second line</p><img src=\"https://x/one\">"),
152
record(
153
"a",
154
6,
155
"<p>Release notes</p><p>second line</p><img src=\"https://x/one\">",
156
),
149
157
record("b", 7, "<img src=\"https://x/two\">"),
150
158
];
151
159
let items = collect_gallery(&rows(&records), today(), offset());
@@ -130,7 +130,11 @@ mod tests {130
let mut deleted = record("d", 7, "<img src=\"https://x/deleted\">");130
let mut deleted = record("d", 7, "<img src=\"https://x/deleted\">");131
deleted.deleted = true;131
deleted.deleted = true;132
let records = [132
let records = [133
record("a", 6, "<p>first</p><img src=\"https://x/one\"><img src=\"https://x/two\">"),133
record(134
"a",135
6,136
"<p>first</p><img src=\"https://x/one\"><img src=\"https://x/two\">",137
),134
record("b", 6, "<p>no image</p>"),138
record("b", 6, "<p>no image</p>"),135
deleted,139
deleted,136
record("c", 7, "<img src=\"https://x/three\">"),140
record("c", 7, "<img src=\"https://x/three\">"),@@ -145,7 +149,11 @@ mod tests {145
#[test]149
#[test]146
fn items_carry_author_caption_and_time() {150
fn items_carry_author_caption_and_time() {147
let records = [151
let records = [148
record("a", 6, "<p>Release notes</p><p>second line</p><img src=\"https://x/one\">"),152
record(153
"a",154
6,155
"<p>Release notes</p><p>second line</p><img src=\"https://x/one\">",156
),149
record("b", 7, "<img src=\"https://x/two\">"),157
record("b", 7, "<img src=\"https://x/two\">"),150
];158
];151
let items = collect_gallery(&rows(&records), today(), offset());159
let items = collect_gallery(&rows(&records), today(), offset());@@ -94,9 +94,7 @@ pub fn step_index(current: usize, len: usize, delta: isize) -> usize {
94
94
if len == 0 {
95
95
return 0;
96
96
}
97
current
98
.saturating_add_signed(delta)
99
.min(len - 1)
97
current.saturating_add_signed(delta).min(len - 1)
100
98
}
101
99
102
100
pub fn counter_label(index: usize, len: usize) -> String {
@@ -166,8 +164,14 @@ mod tests {
166
164
let anchor = (100., 50.);
167
165
let zoomed = zoom_at(start, 1., anchor, image, STAGE);
168
166
assert_eq!(zoomed.scale, 1.);
169
let before = ((anchor.0 - start.pan.0) / start.scale, (anchor.1 - start.pan.1) / start.scale);
170
let after = ((anchor.0 - zoomed.pan.0) / zoomed.scale, (anchor.1 - zoomed.pan.1) / zoomed.scale);
167
let before = (
168
(anchor.0 - start.pan.0) / start.scale,
169
(anchor.1 - start.pan.1) / start.scale,
170
);
171
let after = (
172
(anchor.0 - zoomed.pan.0) / zoomed.scale,
173
(anchor.1 - zoomed.pan.1) / zoomed.scale,
174
);
171
175
assert!((before.0 - after.0).abs() < 0.01);
172
176
assert!((before.1 - after.1).abs() < 0.01);
173
177
}
@@ -94,9 +94,7 @@ pub fn step_index(current: usize, len: usize, delta: isize) -> usize {94
if len == 0 {94
if len == 0 {95
return 0;95
return 0;96
}96
}97
current97
current.saturating_add_signed(delta).min(len - 1)98
.saturating_add_signed(delta)99
.min(len - 1)100
}98
}101
99
102
pub fn counter_label(index: usize, len: usize) -> String {100
pub fn counter_label(index: usize, len: usize) -> String {@@ -166,8 +164,14 @@ mod tests {166
let anchor = (100., 50.);164
let anchor = (100., 50.);167
let zoomed = zoom_at(start, 1., anchor, image, STAGE);165
let zoomed = zoom_at(start, 1., anchor, image, STAGE);168
assert_eq!(zoomed.scale, 1.);166
assert_eq!(zoomed.scale, 1.);169
let before = ((anchor.0 - start.pan.0) / start.scale, (anchor.1 - start.pan.1) / start.scale);167
let before = (170
let after = ((anchor.0 - zoomed.pan.0) / zoomed.scale, (anchor.1 - zoomed.pan.1) / zoomed.scale);168
(anchor.0 - start.pan.0) / start.scale,169
(anchor.1 - start.pan.1) / start.scale,170
);171
let after = (172
(anchor.0 - zoomed.pan.0) / zoomed.scale,173
(anchor.1 - zoomed.pan.1) / zoomed.scale,174
);171
assert!((before.0 - after.0).abs() < 0.01);175
assert!((before.0 - after.0).abs() < 0.01);172
assert!((before.1 - after.1).abs() < 0.01);176
assert!((before.1 - after.1).abs() < 0.01);173
}177
}@@ -13,12 +13,11 @@ mod backend;
13
13
mod call;
14
14
mod card_actions;
15
15
mod card_inputs;
16
mod chat_actions;
17
mod crash_log;
18
mod diagnostics;
19
16
mod card_refresh;
20
17
mod card_state;
21
18
mod channel_files;
19
mod chat_actions;
20
mod crash_log;
22
21
mod data;
23
22
mod demo;
24
23
mod demo_cards;
@@ -27,6 +26,7 @@ mod demo_gifs;
27
26
mod demo_input_cards;
28
27
mod demo_library;
29
28
mod demo_profiles;
29
mod diagnostics;
30
30
mod downloads;
31
31
mod emoji;
32
32
mod format;
@@ -38,9 +38,9 @@ mod image_view_math;
38
38
mod local_previews;
39
39
mod message_actions;
40
40
mod notice;
41
mod own_status;
42
41
mod notify;
43
42
mod outbox;
43
mod own_status;
44
44
mod pending_rows;
45
45
mod people;
46
46
mod presence_link;
@@ -56,8 +56,8 @@ mod schedule_time;
56
56
mod scheduled;
57
57
mod scheduled_rows;
58
58
mod section_actions;
59
mod single_instance;
60
59
mod sidebar_model;
60
mod single_instance;
61
61
mod stickers;
62
62
mod stored_outgoing;
63
63
mod task_dialog;
@@ -153,7 +153,10 @@ fn data_path(name: &str) -> PathBuf {
153
153
.unwrap_or_else(|| PathBuf::from(name))
154
154
}
155
155
156
fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<dyn session::Transport> {
156
fn transport(
157
endpoint: Option<&str>,
158
database: Option<&std::path::Path>,
159
) -> Arc<dyn session::Transport> {
157
160
#[cfg(windows)]
158
161
if endpoint.is_none() {
159
162
let user_data_folder = match database.and_then(std::path::Path::parent) {
@@ -223,82 +226,79 @@ fn main() {
223
226
};
224
227
let store = Arc::new(store);
225
228
let user_input = user_activity::UserInput::new();
226
let receiver = (!arguments.demo)
227
.then(|| {
228
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
229
let activity = user_activity::track(user_input.clone());
230
backend::start(store.clone(), transport, !arguments.read_only, activity)
231
});
229
let receiver = (!arguments.demo).then(|| {
230
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
231
let activity = user_activity::track(user_input.clone());
232
backend::start(store.clone(), transport, !arguments.read_only, activity)
233
});
232
234
233
235
let mut application = gpui_kit::application();
234
236
if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {
235
237
application = application.with_http_client(Arc::new(http_client));
236
238
}
237
239
238
application
239
.with_assets(assets::AppAssets)
240
.run(move |cx| {
241
gpui_kit::init(cx);
242
cx.on_app_quit(|_| {
243
updater::exit_after_grace();
244
async {}
245
})
246
.detach();
247
theme::load_fonts(cx);
248
theme::apply(cx);
249
bind_keys(cx);
250
let state = cx.new(|_| {
251
let mut state = AppState::new(store, mode);
252
state.start_on_channels = arguments.channels_tab;
253
state
240
application.with_assets(assets::AppAssets).run(move |cx| {
241
gpui_kit::init(cx);
242
cx.on_app_quit(|_| {
243
updater::exit_after_grace();
244
async {}
245
})
246
.detach();
247
theme::load_fonts(cx);
248
theme::apply(cx);
249
bind_keys(cx);
250
let state = cx.new(|_| {
251
let mut state = AppState::new(store, mode);
252
state.start_on_channels = arguments.channels_tab;
253
state
254
});
255
cx.set_global(app_state::AppHandle(state.clone()));
256
cx.set_global(views::shell::UserInputHandle(user_input));
257
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
258
agents::install(state.clone(), cx);
259
if arguments.demo {
260
state.update(cx, |state, cx| {
261
demo::seed_directory(state);
262
state.demo_live_meetings();
263
state.select(demo::first_selection(), cx);
254
264
});
255
cx.set_global(app_state::AppHandle(state.clone()));
256
cx.set_global(views::shell::UserInputHandle(user_input));
257
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
258
agents::install(state.clone(), cx);
259
if arguments.demo {
260
state.update(cx, |state, cx| {
261
demo::seed_directory(state);
262
state.demo_live_meetings();
263
state.select(demo::first_selection(), cx);
264
});
265
}
266
if let Some(mut receiver) = receiver {
267
let state = state.clone();
268
cx.spawn(async move |cx| {
269
while let Some(event) = receiver.recv().await {
270
state.update(cx, |state, cx| state.apply(event, cx));
271
}
272
})
273
.detach();
274
}
275
276
let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
277
let mut options = TitleBar::window_options();
278
options.window_bounds = Some(WindowBounds::Windowed(bounds));
279
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
280
if let Some(titlebar) = options.titlebar.as_mut() {
281
titlebar.title = Some(APP_NAME.into());
282
}
283
let open_target = arguments.open_target;
284
let startup = Startup {
285
switcher_query: arguments.switcher_query,
286
composer_text: arguments.composer_text,
287
reply_to_last: arguments.reply_to_last,
288
};
289
let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
290
cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
291
})
292
.expect("failed to open window");
293
let main_window_id = main_window.window_id();
294
cx.on_window_closed(move |cx, closed| {
295
if closed == main_window_id {
296
cx.quit();
265
}
266
if let Some(mut receiver) = receiver {
267
let state = state.clone();
268
cx.spawn(async move |cx| {
269
while let Some(event) = receiver.recv().await {
270
state.update(cx, |state, cx| state.apply(event, cx));
297
271
}
298
272
})
299
273
.detach();
300
cx.activate(true);
301
});
274
}
275
276
let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
277
let mut options = TitleBar::window_options();
278
options.window_bounds = Some(WindowBounds::Windowed(bounds));
279
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
280
if let Some(titlebar) = options.titlebar.as_mut() {
281
titlebar.title = Some(APP_NAME.into());
282
}
283
let open_target = arguments.open_target;
284
let startup = Startup {
285
switcher_query: arguments.switcher_query,
286
composer_text: arguments.composer_text,
287
reply_to_last: arguments.reply_to_last,
288
};
289
let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
290
cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
291
})
292
.expect("failed to open window");
293
let main_window_id = main_window.window_id();
294
cx.on_window_closed(move |cx, closed| {
295
if closed == main_window_id {
296
cx.quit();
297
}
298
})
299
.detach();
300
cx.activate(true);
301
});
302
302
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
303
303
#[cfg(windows)]
304
304
updater::exit_now();
@@ -13,12 +13,11 @@ mod backend;13
mod call;13
mod call;14
mod card_actions;14
mod card_actions;15
mod card_inputs;15
mod card_inputs;16
mod chat_actions;17
mod crash_log;18
mod diagnostics;19
mod card_refresh;16
mod card_refresh;20
mod card_state;17
mod card_state;21
mod channel_files;18
mod channel_files;19
mod chat_actions;20
mod crash_log;22
mod data;21
mod data;23
mod demo;22
mod demo;24
mod demo_cards;23
mod demo_cards;@@ -27,6 +26,7 @@ mod demo_gifs;27
mod demo_input_cards;26
mod demo_input_cards;28
mod demo_library;27
mod demo_library;29
mod demo_profiles;28
mod demo_profiles;29
mod diagnostics;30
mod downloads;30
mod downloads;31
mod emoji;31
mod emoji;32
mod format;32
mod format;@@ -38,9 +38,9 @@ mod image_view_math;38
mod local_previews;38
mod local_previews;39
mod message_actions;39
mod message_actions;40
mod notice;40
mod notice;41
mod own_status;42
mod notify;41
mod notify;43
mod outbox;42
mod outbox;43
mod own_status;44
mod pending_rows;44
mod pending_rows;45
mod people;45
mod people;46
mod presence_link;46
mod presence_link;@@ -56,8 +56,8 @@ mod schedule_time;56
mod scheduled;56
mod scheduled;57
mod scheduled_rows;57
mod scheduled_rows;58
mod section_actions;58
mod section_actions;59
mod single_instance;60
mod sidebar_model;59
mod sidebar_model;60
mod single_instance;61
mod stickers;61
mod stickers;62
mod stored_outgoing;62
mod stored_outgoing;63
mod task_dialog;63
mod task_dialog;@@ -153,7 +153,10 @@ fn data_path(name: &str) -> PathBuf {153
.unwrap_or_else(|| PathBuf::from(name))153
.unwrap_or_else(|| PathBuf::from(name))154
}154
}155
155
156
fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<dyn session::Transport> {156
fn transport(157
endpoint: Option<&str>,158
database: Option<&std::path::Path>,159
) -> Arc<dyn session::Transport> {157
#[cfg(windows)]160
#[cfg(windows)]158
if endpoint.is_none() {161
if endpoint.is_none() {159
let user_data_folder = match database.and_then(std::path::Path::parent) {162
let user_data_folder = match database.and_then(std::path::Path::parent) {@@ -223,82 +226,79 @@ fn main() {223
};226
};224
let store = Arc::new(store);227
let store = Arc::new(store);225
let user_input = user_activity::UserInput::new();228
let user_input = user_activity::UserInput::new();226
let receiver = (!arguments.demo)229
let receiver = (!arguments.demo).then(|| {227
.then(|| {230
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());228
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());231
let activity = user_activity::track(user_input.clone());229
let activity = user_activity::track(user_input.clone());232
backend::start(store.clone(), transport, !arguments.read_only, activity)230
backend::start(store.clone(), transport, !arguments.read_only, activity)233
});231
});232
234
233
let mut application = gpui_kit::application();235
let mut application = gpui_kit::application();234
if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {236
if let Ok(http_client) = reqwest_client::ReqwestClient::user_agent(HTTP_USER_AGENT) {235
application = application.with_http_client(Arc::new(http_client));237
application = application.with_http_client(Arc::new(http_client));236
}238
}237
239
238
application240
application.with_assets(assets::AppAssets).run(move |cx| {239
.with_assets(assets::AppAssets)241
gpui_kit::init(cx);240
.run(move |cx| {242
cx.on_app_quit(|_| {241
gpui_kit::init(cx);243
updater::exit_after_grace();242
cx.on_app_quit(|_| {244
async {}243
updater::exit_after_grace();245
})244
async {}246
.detach();245
})247
theme::load_fonts(cx);246
.detach();248
theme::apply(cx);247
theme::load_fonts(cx);249
bind_keys(cx);248
theme::apply(cx);250
let state = cx.new(|_| {249
bind_keys(cx);251
let mut state = AppState::new(store, mode);250
let state = cx.new(|_| {252
state.start_on_channels = arguments.channels_tab;251
let mut state = AppState::new(store, mode);253
state252
state.start_on_channels = arguments.channels_tab;254
});253
state255
cx.set_global(app_state::AppHandle(state.clone()));256
cx.set_global(views::shell::UserInputHandle(user_input));257
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);258
agents::install(state.clone(), cx);259
if arguments.demo {260
state.update(cx, |state, cx| {261
demo::seed_directory(state);262
state.demo_live_meetings();263
state.select(demo::first_selection(), cx);254
});264
});255
cx.set_global(app_state::AppHandle(state.clone()));265
}256
cx.set_global(views::shell::UserInputHandle(user_input));266
if let Some(mut receiver) = receiver {257
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);267
let state = state.clone();258
agents::install(state.clone(), cx);268
cx.spawn(async move |cx| {259
if arguments.demo {269
while let Some(event) = receiver.recv().await {260
state.update(cx, |state, cx| {270
state.update(cx, |state, cx| state.apply(event, cx));261
demo::seed_directory(state);262
state.demo_live_meetings();263
state.select(demo::first_selection(), cx);264
});265
}266
if let Some(mut receiver) = receiver {267
let state = state.clone();268
cx.spawn(async move |cx| {269
while let Some(event) = receiver.recv().await {270
state.update(cx, |state, cx| state.apply(event, cx));271
}272
})273
.detach();274
}275
276
let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);277
let mut options = TitleBar::window_options();278
options.window_bounds = Some(WindowBounds::Windowed(bounds));279
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));280
if let Some(titlebar) = options.titlebar.as_mut() {281
titlebar.title = Some(APP_NAME.into());282
}283
let open_target = arguments.open_target;284
let startup = Startup {285
switcher_query: arguments.switcher_query,286
composer_text: arguments.composer_text,287
reply_to_last: arguments.reply_to_last,288
};289
let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {290
cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))291
})292
.expect("failed to open window");293
let main_window_id = main_window.window_id();294
cx.on_window_closed(move |cx, closed| {295
if closed == main_window_id {296
cx.quit();297
}271
}298
})272
})299
.detach();273
.detach();300
cx.activate(true);274
}301
});275
276
let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);277
let mut options = TitleBar::window_options();278
options.window_bounds = Some(WindowBounds::Windowed(bounds));279
options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));280
if let Some(titlebar) = options.titlebar.as_mut() {281
titlebar.title = Some(APP_NAME.into());282
}283
let open_target = arguments.open_target;284
let startup = Startup {285
switcher_query: arguments.switcher_query,286
composer_text: arguments.composer_text,287
reply_to_last: arguments.reply_to_last,288
};289
let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {290
cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))291
})292
.expect("failed to open window");293
let main_window_id = main_window.window_id();294
cx.on_window_closed(move |cx, closed| {295
if closed == main_window_id {296
cx.quit();297
}298
})299
.detach();300
cx.activate(true);301
});302
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);302
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);303
#[cfg(windows)]303
#[cfg(windows)]304
updater::exit_now();304
updater::exit_now();@@ -81,7 +81,11 @@ fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {
81
81
}
82
82
83
83
impl AppState {
84
pub(crate) fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> {
84
pub(crate) fn message_record(
85
&self,
86
conversation_id: &str,
87
message_id: &str,
88
) -> Option<MessageRecord> {
85
89
self.store
86
90
.messages_by_id(conversation_id, &[message_id.to_owned()])
87
91
.ok()?
@@ -81,7 +81,11 @@ fn saved_entry(record: &MessageRecord, is_channel: bool) -> SavedMessage {81
}81
}82
82
83
impl AppState {83
impl AppState {84
pub(crate) fn message_record(&self, conversation_id: &str, message_id: &str) -> Option<MessageRecord> {84
pub(crate) fn message_record(85
&self,86
conversation_id: &str,87
message_id: &str,88
) -> Option<MessageRecord> {85
self.store89
self.store86
.messages_by_id(conversation_id, &[message_id.to_owned()])90
.messages_by_id(conversation_id, &[message_id.to_owned()])87
.ok()?91
.ok()?@@ -24,17 +24,39 @@ pub fn badge_for(unread_chats: usize) -> Option<Badge> {
24
24
}
25
25
26
26
const GLYPHS: [[u8; GLYPH_HEIGHT]; 11] = [
27
[0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],
28
[0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],
29
[0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],
30
[0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],
31
[0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],
32
[0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],
33
[0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],
34
[0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],
35
[0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],
36
[0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],
37
[0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],
27
[
28
0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,
29
],
30
[
31
0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,
32
],
33
[
34
0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,
35
],
36
[
37
0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110,
38
],
39
[
40
0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,
41
],
42
[
43
0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,
44
],
45
[
46
0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,
47
],
48
[
49
0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,
50
],
51
[
52
0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,
53
],
54
[
55
0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,
56
],
57
[
58
0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000,
59
],
38
60
];
39
61
40
62
fn glyph_for(character: char) -> Option<&'static [u8; GLYPH_HEIGHT]> {
@@ -60,7 +82,8 @@ pub fn render_badge(badge: &Badge) -> Vec<u8> {
60
82
let radius = BADGE_SIZE as f32 / 2.;
61
83
for row in 0..BADGE_SIZE {
62
84
for column in 0..BADGE_SIZE {
63
let distance = ((column as f32 - center).powi(2) + (row as f32 - center).powi(2)).sqrt();
85
let distance =
86
((column as f32 - center).powi(2) + (row as f32 - center).powi(2)).sqrt();
64
87
if distance <= radius - 0.5 {
65
88
put(&mut pixels, column, row, RED);
66
89
}
@@ -24,17 +24,39 @@ pub fn badge_for(unread_chats: usize) -> Option<Badge> {24
}24
}25
25
26
const GLYPHS: [[u8; GLYPH_HEIGHT]; 11] = [26
const GLYPHS: [[u8; GLYPH_HEIGHT]; 11] = [27
[0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110],27
[28
[0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110],28
0b01110, 0b10001, 0b10011, 0b10101, 0b11001, 0b10001, 0b01110,29
[0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111],29
],30
[0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110],30
[31
[0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010],31
0b00100, 0b01100, 0b00100, 0b00100, 0b00100, 0b00100, 0b01110,32
[0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110],32
],33
[0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110],33
[34
[0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000],34
0b01110, 0b10001, 0b00001, 0b00010, 0b00100, 0b01000, 0b11111,35
[0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110],35
],36
[0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100],36
[37
[0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000],37
0b11110, 0b00001, 0b00001, 0b01110, 0b00001, 0b00001, 0b11110,38
],39
[40
0b00010, 0b00110, 0b01010, 0b10010, 0b11111, 0b00010, 0b00010,41
],42
[43
0b11111, 0b10000, 0b11110, 0b00001, 0b00001, 0b10001, 0b01110,44
],45
[46
0b00110, 0b01000, 0b10000, 0b11110, 0b10001, 0b10001, 0b01110,47
],48
[49
0b11111, 0b00001, 0b00010, 0b00100, 0b01000, 0b01000, 0b01000,50
],51
[52
0b01110, 0b10001, 0b10001, 0b01110, 0b10001, 0b10001, 0b01110,53
],54
[55
0b01110, 0b10001, 0b10001, 0b01111, 0b00001, 0b00010, 0b01100,56
],57
[58
0b00000, 0b00100, 0b00100, 0b11111, 0b00100, 0b00100, 0b00000,59
],38
];60
];39
61
40
fn glyph_for(character: char) -> Option<&'static [u8; GLYPH_HEIGHT]> {62
fn glyph_for(character: char) -> Option<&'static [u8; GLYPH_HEIGHT]> {@@ -60,7 +82,8 @@ pub fn render_badge(badge: &Badge) -> Vec<u8> {60
let radius = BADGE_SIZE as f32 / 2.;82
let radius = BADGE_SIZE as f32 / 2.;61
for row in 0..BADGE_SIZE {83
for row in 0..BADGE_SIZE {62
for column in 0..BADGE_SIZE {84
for column in 0..BADGE_SIZE {63
let distance = ((column as f32 - center).powi(2) + (row as f32 - center).powi(2)).sqrt();85
let distance =86
((column as f32 - center).powi(2) + (row as f32 - center).powi(2)).sqrt();64
if distance <= radius - 0.5 {87
if distance <= radius - 0.5 {65
put(&mut pixels, column, row, RED);88
put(&mut pixels, column, row, RED);66
}89
}@@ -9,6 +9,7 @@ use super::badge::{Badge, badge_for};
9
9
use super::incoming::IncomingTracker;
10
10
use super::layout::{self, Slot, ring_height};
11
11
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12
use super::ring_view::RingView;
12
13
use super::rules::{
13
14
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,
14
15
should_flash, should_ringback,
@@ -19,7 +20,6 @@ use super::stack::{
19
20
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20
21
};
21
22
use super::text::describe;
22
use super::ring_view::RingView;
23
23
use super::toast::{PillView, ToastView};
24
24
use crate::agents::{AgentRun, AgentRunsEvent, RunState};
25
25
use crate::app_state::{AppEvent, AppState, Selection};
@@ -149,7 +149,8 @@ impl NotificationCenter {
149
149
}
150
150
if let Some(delay) = demo_ring_delay() {
151
151
let app = center.app.clone();
152
let video = std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");
152
let video =
153
std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");
153
154
cx.spawn(async move |_, cx| {
154
155
cx.background_executor().timer(delay).await;
155
156
app.update(cx, |state, cx| {
@@ -200,7 +201,11 @@ impl NotificationCenter {
200
201
}
201
202
202
203
fn animated(&self, duration: Duration) -> Duration {
203
if self.animations { duration } else { Duration::ZERO }
204
if self.animations {
205
duration
206
} else {
207
Duration::ZERO
208
}
204
209
}
205
210
206
211
pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {
@@ -304,11 +309,8 @@ impl NotificationCenter {
304
309
}
305
310
let decision = decide(&self.settings, &incoming, environment);
306
311
self.present(&incoming, decision, cx);
307
if should_flash(
308
&self.settings,
309
decision.toast,
310
self.main_window_active(cx),
311
) && let Some(native) = self.main_native
312
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))
313
&& let Some(native) = self.main_native
312
314
{
313
315
platform::flash(native);
314
316
}
@@ -345,12 +347,21 @@ impl NotificationCenter {
345
347
let toast = AgentToast {
346
348
run_id: run.id,
347
349
session_id: run.session_id.clone(),
348
header: format!("{} - {} - {}", run.action_label, run.agent_name, run.elapsed_text()),
350
header: format!(
351
"{} - {} - {}",
352
run.action_label,
353
run.agent_name,
354
run.elapsed_text()
355
),
349
356
title: format!(
350
357
"{} {verb}: {} for {}",
351
358
run.agent_name, run.action_label, run.sender_name
352
359
),
353
body: if body.is_empty() { "Done".to_owned() } else { body },
360
body: if body.is_empty() {
361
"Done".to_owned()
362
} else {
363
body
364
},
354
365
failed,
355
366
};
356
367
let now = Instant::now();
@@ -467,7 +478,13 @@ impl NotificationCenter {
467
478
}
468
479
}
469
480
470
fn open_ring_window(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
481
fn open_ring_window(
482
&mut self,
483
ring_id: u64,
484
slot: Slot,
485
area: WorkArea,
486
cx: &mut Context<Self>,
487
) {
471
488
if !self.ring_opening.insert(ring_id) {
472
489
return;
473
490
}
@@ -498,7 +515,10 @@ impl NotificationCenter {
498
515
499
516
fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
500
517
let ringing = self.app.read(cx).rings.is_ringing();
501
if ringing && !self.main_window_active(cx) && let Some(native) = self.main_native {
518
if ringing
519
&& !self.main_window_active(cx)
520
&& let Some(native) = self.main_native
521
{
502
522
platform::flash(native);
503
523
}
504
524
self.sync_windows(cx);
@@ -516,7 +536,8 @@ impl NotificationCenter {
516
536
}
517
537
518
538
fn sync_ringback(&mut self, cx: &Context<Self>) {
519
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model)) && !self.demo_mode;
539
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model))
540
&& !self.demo_mode;
520
541
match (audible, self.ringback.is_some()) {
521
542
(true, false) => self.ringback = platform::start_ringback(),
522
543
(false, true) => self.ringback = None,
@@ -572,12 +593,7 @@ impl NotificationCenter {
572
593
);
573
594
}
574
595
575
fn sync_pill(
576
&mut self,
577
slot: Option<Slot>,
578
area: WorkArea,
579
cx: &mut Context<Self>,
580
) {
596
fn sync_pill(&mut self, slot: Option<Slot>, area: WorkArea, cx: &mut Context<Self>) {
581
597
let Some(slot) = slot else {
582
598
if let Some(pill) = self.pill.take() {
583
599
pill.handle
@@ -670,7 +686,11 @@ impl NotificationCenter {
670
686
if !self.app.read(cx).rings.is_empty() {
671
687
self.app.update(cx, |state, cx| state.tick_rings(cx));
672
688
}
673
if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() || !self.ring_windows.is_empty() {
689
if !self.stack.is_empty()
690
|| !self.windows.is_empty()
691
|| self.pill.is_some()
692
|| !self.ring_windows.is_empty()
693
{
674
694
self.sync_windows(cx);
675
695
cx.notify();
676
696
}
@@ -894,7 +914,12 @@ impl NotificationCenter {
894
914
self.show_settings(Section::Agents, true, cx);
895
915
}
896
916
897
fn show_settings(&mut self, section: Section, switch_open_window: bool, cx: &mut Context<Self>) {
917
fn show_settings(
918
&mut self,
919
section: Section,
920
switch_open_window: bool,
921
cx: &mut Context<Self>,
922
) {
898
923
if let Some(handle) = self.settings_window {
899
924
let shown = handle.update(cx, |view, window, cx| {
900
925
window.activate_window();
@@ -9,6 +9,7 @@ use super::badge::{Badge, badge_for};9
use super::incoming::IncomingTracker;9
use super::incoming::IncomingTracker;10
use super::layout::{self, Slot, ring_height};10
use super::layout::{self, Slot, ring_height};11
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};11
use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};12
use super::ring_view::RingView;12
use super::rules::{13
use super::rules::{13
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,14
ChatKind, Decision, Environment, Incoming, Preview, Settings, SoundThrottle, decide, in_call,14
should_flash, should_ringback,15
should_flash, should_ringback,@@ -19,7 +20,6 @@ use super::stack::{19
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,20
AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,20
};21
};21
use super::text::describe;22
use super::text::describe;22
use super::ring_view::RingView;23
use super::toast::{PillView, ToastView};23
use super::toast::{PillView, ToastView};24
use crate::agents::{AgentRun, AgentRunsEvent, RunState};24
use crate::agents::{AgentRun, AgentRunsEvent, RunState};25
use crate::app_state::{AppEvent, AppState, Selection};25
use crate::app_state::{AppEvent, AppState, Selection};@@ -149,7 +149,8 @@ impl NotificationCenter {149
}149
}150
if let Some(delay) = demo_ring_delay() {150
if let Some(delay) = demo_ring_delay() {151
let app = center.app.clone();151
let app = center.app.clone();152
let video = std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");152
let video =153
std::env::var(DEMO_RING_KIND_ENV).is_ok_and(|kind| kind.trim() == "video");153
cx.spawn(async move |_, cx| {154
cx.spawn(async move |_, cx| {154
cx.background_executor().timer(delay).await;155
cx.background_executor().timer(delay).await;155
app.update(cx, |state, cx| {156
app.update(cx, |state, cx| {@@ -200,7 +201,11 @@ impl NotificationCenter {200
}201
}201
202
202
fn animated(&self, duration: Duration) -> Duration {203
fn animated(&self, duration: Duration) -> Duration {203
if self.animations { duration } else { Duration::ZERO }204
if self.animations {205
duration206
} else {207
Duration::ZERO208
}204
}209
}205
210
206
pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {211
pub fn directory<'a>(&self, cx: &'a App) -> &'a Directory {@@ -304,11 +309,8 @@ impl NotificationCenter {304
}309
}305
let decision = decide(&self.settings, &incoming, environment);310
let decision = decide(&self.settings, &incoming, environment);306
self.present(&incoming, decision, cx);311
self.present(&incoming, decision, cx);307
if should_flash(312
if should_flash(&self.settings, decision.toast, self.main_window_active(cx))308
&self.settings,313
&& let Some(native) = self.main_native309
decision.toast,310
self.main_window_active(cx),311
) && let Some(native) = self.main_native312
{314
{313
platform::flash(native);315
platform::flash(native);314
}316
}@@ -345,12 +347,21 @@ impl NotificationCenter {345
let toast = AgentToast {347
let toast = AgentToast {346
run_id: run.id,348
run_id: run.id,347
session_id: run.session_id.clone(),349
session_id: run.session_id.clone(),348
header: format!("{} - {} - {}", run.action_label, run.agent_name, run.elapsed_text()),350
header: format!(351
"{} - {} - {}",352
run.action_label,353
run.agent_name,354
run.elapsed_text()355
),349
title: format!(356
title: format!(350
"{} {verb}: {} for {}",357
"{} {verb}: {} for {}",351
run.agent_name, run.action_label, run.sender_name358
run.agent_name, run.action_label, run.sender_name352
),359
),353
body: if body.is_empty() { "Done".to_owned() } else { body },360
body: if body.is_empty() {361
"Done".to_owned()362
} else {363
body364
},354
failed,365
failed,355
};366
};356
let now = Instant::now();367
let now = Instant::now();@@ -467,7 +478,13 @@ impl NotificationCenter {467
}478
}468
}479
}469
480
470
fn open_ring_window(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {481
fn open_ring_window(482
&mut self,483
ring_id: u64,484
slot: Slot,485
area: WorkArea,486
cx: &mut Context<Self>,487
) {471
if !self.ring_opening.insert(ring_id) {488
if !self.ring_opening.insert(ring_id) {472
return;489
return;473
}490
}@@ -498,7 +515,10 @@ impl NotificationCenter {498
515
499
fn on_rings_changed(&mut self, cx: &mut Context<Self>) {516
fn on_rings_changed(&mut self, cx: &mut Context<Self>) {500
let ringing = self.app.read(cx).rings.is_ringing();517
let ringing = self.app.read(cx).rings.is_ringing();501
if ringing && !self.main_window_active(cx) && let Some(native) = self.main_native {518
if ringing519
&& !self.main_window_active(cx)520
&& let Some(native) = self.main_native521
{502
platform::flash(native);522
platform::flash(native);503
}523
}504
self.sync_windows(cx);524
self.sync_windows(cx);@@ -516,7 +536,8 @@ impl NotificationCenter {516
}536
}517
537
518
fn sync_ringback(&mut self, cx: &Context<Self>) {538
fn sync_ringback(&mut self, cx: &Context<Self>) {519
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model)) && !self.demo_mode;539
let audible = should_ringback(self.app.read(cx).call.as_ref().map(|call| &call.model))540
&& !self.demo_mode;520
match (audible, self.ringback.is_some()) {541
match (audible, self.ringback.is_some()) {521
(true, false) => self.ringback = platform::start_ringback(),542
(true, false) => self.ringback = platform::start_ringback(),522
(false, true) => self.ringback = None,543
(false, true) => self.ringback = None,@@ -572,12 +593,7 @@ impl NotificationCenter {572
);593
);573
}594
}574
595
575
fn sync_pill(596
fn sync_pill(&mut self, slot: Option<Slot>, area: WorkArea, cx: &mut Context<Self>) {576
&mut self,577
slot: Option<Slot>,578
area: WorkArea,579
cx: &mut Context<Self>,580
) {581
let Some(slot) = slot else {597
let Some(slot) = slot else {582
if let Some(pill) = self.pill.take() {598
if let Some(pill) = self.pill.take() {583
pill.handle599
pill.handle@@ -670,7 +686,11 @@ impl NotificationCenter {670
if !self.app.read(cx).rings.is_empty() {686
if !self.app.read(cx).rings.is_empty() {671
self.app.update(cx, |state, cx| state.tick_rings(cx));687
self.app.update(cx, |state, cx| state.tick_rings(cx));672
}688
}673
if !self.stack.is_empty() || !self.windows.is_empty() || self.pill.is_some() || !self.ring_windows.is_empty() {689
if !self.stack.is_empty()690
|| !self.windows.is_empty()691
|| self.pill.is_some()692
|| !self.ring_windows.is_empty()693
{674
self.sync_windows(cx);694
self.sync_windows(cx);675
cx.notify();695
cx.notify();676
}696
}@@ -894,7 +914,12 @@ impl NotificationCenter {894
self.show_settings(Section::Agents, true, cx);914
self.show_settings(Section::Agents, true, cx);895
}915
}896
916
897
fn show_settings(&mut self, section: Section, switch_open_window: bool, cx: &mut Context<Self>) {917
fn show_settings(918
&mut self,919
section: Section,920
switch_open_window: bool,921
cx: &mut Context<Self>,922
) {898
if let Some(handle) = self.settings_window {923
if let Some(handle) = self.settings_window {899
let shown = handle.update(cx, |view, window, cx| {924
let shown = handle.update(cx, |view, window, cx| {900
window.activate_window();925
window.activate_window();@@ -39,20 +39,23 @@ pub struct Slot {
39
39
40
40
pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {
41
41
if model.agent.is_some() {
42
return AGENT_CHROME_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
42
return AGENT_CHROME_HEIGHT
43
+ preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
43
44
}
44
45
let base = BASE_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
45
46
match model.reply {
46
47
ReplyState::Sent | ReplyState::Failed => CONFIRM_HEIGHT,
47
ReplyState::Open => {
48
base + REPLY_SPACING + SEND_BUTTON + REPLY_FIELD_FRAME + REPLY_HINT_ROW
49
}
48
ReplyState::Open => base + REPLY_SPACING + SEND_BUTTON + REPLY_FIELD_FRAME + REPLY_HINT_ROW,
50
49
ReplyState::Closed => base + ACTION_ROW_SPACING + ACTION_BUTTON,
51
50
}
52
51
}
53
52
54
53
pub fn ring_height(ends_current_call: bool) -> f32 {
55
if ends_current_call { RING_BASE_HEIGHT + RING_NOTE_HEIGHT } else { RING_BASE_HEIGHT }
54
if ends_current_call {
55
RING_BASE_HEIGHT + RING_NOTE_HEIGHT
56
} else {
57
RING_BASE_HEIGHT
58
}
56
59
}
57
60
58
61
pub struct StackSlots {
@@ -60,12 +63,7 @@ pub struct StackSlots {
60
63
pub pill: Option<Slot>,
61
64
}
62
65
63
pub fn stack_slots(
64
area: WorkArea,
65
corner: Corner,
66
heights: &[f32],
67
with_pill: bool,
68
) -> StackSlots {
66
pub fn stack_slots(area: WorkArea, corner: Corner, heights: &[f32], with_pill: bool) -> StackSlots {
69
67
let scale = area.scale;
70
68
let physical = |value: f32| (value * scale).round() as i32;
71
69
let width = physical(TOAST_WIDTH);
@@ -144,7 +142,10 @@ mod tests {
144
142
let pill = slots.pill.unwrap();
145
143
assert_eq!(pill.height, 36);
146
144
assert_eq!(pill.y + pill.height + 8, slots.toasts[0].y);
147
assert_eq!((pill.x, pill.width), (slots.toasts[0].x, slots.toasts[0].width));
145
assert_eq!(
146
(pill.x, pill.width),
147
(slots.toasts[0].x, slots.toasts[0].width)
148
);
148
149
}
149
150
150
151
#[test]
@@ -39,20 +39,23 @@ pub struct Slot {39
39
40
pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {40
pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {41
if model.agent.is_some() {41
if model.agent.is_some() {42
return AGENT_CHROME_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;42
return AGENT_CHROME_HEIGHT43
+ preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;43
}44
}44
let base = BASE_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;45
let base = BASE_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;45
match model.reply {46
match model.reply {46
ReplyState::Sent | ReplyState::Failed => CONFIRM_HEIGHT,47
ReplyState::Sent | ReplyState::Failed => CONFIRM_HEIGHT,47
ReplyState::Open => {48
ReplyState::Open => base + REPLY_SPACING + SEND_BUTTON + REPLY_FIELD_FRAME + REPLY_HINT_ROW,48
base + REPLY_SPACING + SEND_BUTTON + REPLY_FIELD_FRAME + REPLY_HINT_ROW49
}50
ReplyState::Closed => base + ACTION_ROW_SPACING + ACTION_BUTTON,49
ReplyState::Closed => base + ACTION_ROW_SPACING + ACTION_BUTTON,51
}50
}52
}51
}53
52
54
pub fn ring_height(ends_current_call: bool) -> f32 {53
pub fn ring_height(ends_current_call: bool) -> f32 {55
if ends_current_call { RING_BASE_HEIGHT + RING_NOTE_HEIGHT } else { RING_BASE_HEIGHT }54
if ends_current_call {55
RING_BASE_HEIGHT + RING_NOTE_HEIGHT56
} else {57
RING_BASE_HEIGHT58
}56
}59
}57
60
58
pub struct StackSlots {61
pub struct StackSlots {@@ -60,12 +63,7 @@ pub struct StackSlots {60
pub pill: Option<Slot>,63
pub pill: Option<Slot>,61
}64
}62
65
63
pub fn stack_slots(66
pub fn stack_slots(area: WorkArea, corner: Corner, heights: &[f32], with_pill: bool) -> StackSlots {64
area: WorkArea,65
corner: Corner,66
heights: &[f32],67
with_pill: bool,68
) -> StackSlots {69
let scale = area.scale;67
let scale = area.scale;70
let physical = |value: f32| (value * scale).round() as i32;68
let physical = |value: f32| (value * scale).round() as i32;71
let width = physical(TOAST_WIDTH);69
let width = physical(TOAST_WIDTH);@@ -144,7 +142,10 @@ mod tests {144
let pill = slots.pill.unwrap();142
let pill = slots.pill.unwrap();145
assert_eq!(pill.height, 36);143
assert_eq!(pill.height, 36);146
assert_eq!(pill.y + pill.height + 8, slots.toasts[0].y);144
assert_eq!(pill.y + pill.height + 8, slots.toasts[0].y);147
assert_eq!((pill.x, pill.width), (slots.toasts[0].x, slots.toasts[0].width));145
assert_eq!(146
(pill.x, pill.width),147
(slots.toasts[0].x, slots.toasts[0].width)148
);148
}149
}149
150
150
#[test]151
#[test]@@ -19,9 +19,9 @@ mod toast;
19
19
20
20
pub use center::{NotificationCenter, selection_for};
21
21
pub use incoming::{IncomingTracker, preview_of};
22
pub(crate) use settings_view::switch;
23
pub use rules::{Incoming, Preview, channel_alerts};
24
#[cfg(test)]
25
pub use rules::ChatKind;
26
22
#[cfg(windows)]
27
23
pub use platform::native_handle;
24
#[cfg(test)]
25
pub use rules::ChatKind;
26
pub use rules::{Incoming, Preview, channel_alerts};
27
pub(crate) use settings_view::switch;
@@ -19,9 +19,9 @@ mod toast;19
19
20
pub use center::{NotificationCenter, selection_for};20
pub use center::{NotificationCenter, selection_for};21
pub use incoming::{IncomingTracker, preview_of};21
pub use incoming::{IncomingTracker, preview_of};22
pub(crate) use settings_view::switch;23
pub use rules::{Incoming, Preview, channel_alerts};24
#[cfg(test)]25
pub use rules::ChatKind;26
#[cfg(windows)]22
#[cfg(windows)]27
pub use platform::native_handle;23
pub use platform::native_handle;24
#[cfg(test)]25
pub use rules::ChatKind;26
pub use rules::{Incoming, Preview, channel_alerts};27
pub(crate) use settings_view::switch;@@ -82,7 +82,6 @@ impl Tray {
82
82
pub fn sync(&self, _sound_on: bool, _do_not_disturb: bool, _mention: bool) {}
83
83
}
84
84
85
86
85
pub fn animations_enabled() -> bool {
87
86
true
88
87
}
@@ -82,7 +82,6 @@ impl Tray {82
pub fn sync(&self, _sound_on: bool, _do_not_disturb: bool, _mention: bool) {}82
pub fn sync(&self, _sound_on: bool, _do_not_disturb: bool, _mention: bool) {}83
}83
}84
84
85
86
pub fn animations_enabled() -> bool {85
pub fn animations_enabled() -> bool {87
true86
true88
}87
}@@ -12,28 +12,30 @@ use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuIt
12
12
use tray_icon::{Icon, MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
13
13
use windows::Win32::Foundation::{COLORREF, HWND, POINT, RECT};
14
14
use windows::Win32::Graphics::Dwm::{
15
DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS, DWMWA_WINDOW_CORNER_PREFERENCE,
16
DWMWCP_DONOTROUND, DwmGetWindowAttribute, DwmSetWindowAttribute,
15
DWMWA_BORDER_COLOR, DWMWA_COLOR_NONE, DWMWA_EXTENDED_FRAME_BOUNDS,
16
DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND, DwmGetWindowAttribute,
17
DwmSetWindowAttribute,
17
18
};
18
19
use windows::Win32::Graphics::Gdi::{
19
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject, ENUM_CURRENT_SETTINGS,
20
EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,
21
MonitorFromPoint, MonitorFromRect, MonitorFromWindow,
20
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject,
21
ENUM_CURRENT_SETTINGS, EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ,
22
MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromPoint, MonitorFromRect, MonitorFromWindow,
22
23
};
23
24
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};
24
use windows::Win32::UI::HiDpi::{GetDpiForWindow, GetDpiForMonitor, MDT_EFFECTIVE_DPI};
25
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, GetDpiForWindow, MDT_EFFECTIVE_DPI};
25
26
use windows::Win32::UI::Shell::{
26
ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME, QUNS_RUNNING_D3D_FULL_SCREEN,
27
SHQueryUserNotificationState, TaskbarList,
27
ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME,
28
QUNS_RUNNING_D3D_FULL_SCREEN, SHQueryUserNotificationState, TaskbarList,
28
29
};
29
30
use windows::Win32::UI::WindowsAndMessaging::{
30
CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO, FlashWindowEx, GWL_EXSTYLE, GWL_STYLE,
31
GetWindowLongPtrW, HICON, HWND_TOPMOST, ICONINFO, IsIconic, SW_HIDE, SW_RESTORE, SW_SHOW, SWP_NOACTIVATE,
32
SPI_GETCLIENTAREAANIMATION, SWP_FRAMECHANGED, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,
33
SWP_NOZORDER, WS_CAPTION, WS_POPUP, WS_THICKFRAME, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetForegroundWindow,
34
SetWindowLongPtrW, SetWindowPos, ShowWindow, SystemParametersInfoW,
35
WS_EX_NOACTIVATE, WS_EX_LAYERED, WS_EX_TRANSPARENT, LWA_ALPHA, SetLayeredWindowAttributes, SetWindowDisplayAffinity,
36
WDA_EXCLUDEFROMCAPTURE, GetWindowRect,
31
CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO,
32
FlashWindowEx, GWL_EXSTYLE, GWL_STYLE, GetWindowLongPtrW, GetWindowRect, HICON, HWND_TOPMOST,
33
ICONINFO, IsIconic, LWA_ALPHA, SPI_GETCLIENTAREAANIMATION, SW_HIDE, SW_RESTORE, SW_SHOW,
34
SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOZORDER,
35
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetForegroundWindow, SetLayeredWindowAttributes,
36
SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos, ShowWindow, SystemParametersInfoW,
37
WDA_EXCLUDEFROMCAPTURE, WS_CAPTION, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TRANSPARENT,
38
WS_POPUP, WS_THICKFRAME,
37
39
};
38
40
use windows::core::{BOOL, PCWSTR, w};
39
41
@@ -105,7 +107,11 @@ pub fn set_activatable(handle: NativeHandle, activatable: bool) {
105
107
unsafe {
106
108
let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);
107
109
let flag = WS_EX_NOACTIVATE.0 as isize;
108
let updated = if activatable { style & !flag } else { style | flag };
110
let updated = if activatable {
111
style & !flag
112
} else {
113
style | flag
114
};
109
115
SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated);
110
116
if activatable {
111
117
let _ = SetForegroundWindow(hwnd(handle));
@@ -155,8 +161,19 @@ pub fn work_area_at(x: i32, y: i32) -> Option<WorkArea> {
155
161
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
156
162
_ => 1.,
157
163
};
158
let RECT { left, top, right, bottom } = info.rcWork;
159
Some(WorkArea { left, top, right, bottom, scale })
164
let RECT {
165
left,
166
top,
167
right,
168
bottom,
169
} = info.rcWork;
170
Some(WorkArea {
171
left,
172
top,
173
right,
174
bottom,
175
scale,
176
})
160
177
}
161
178
}
162
179
@@ -244,7 +261,13 @@ fn screen_frame(index: u32) -> Option<ScreenRect> {
244
261
dmSize: size_of::<DEVMODEW>() as u16,
245
262
..Default::default()
246
263
};
247
if !EnumDisplaySettingsW(PCWSTR(device.DeviceName.as_ptr()), ENUM_CURRENT_SETTINGS, &mut mode).as_bool() {
264
if !EnumDisplaySettingsW(
265
PCWSTR(device.DeviceName.as_ptr()),
266
ENUM_CURRENT_SETTINGS,
267
&mut mode,
268
)
269
.as_bool()
270
{
248
271
return None;
249
272
}
250
273
let position = mode.Anonymous1.Anonymous2.dmPosition;
@@ -278,10 +301,21 @@ fn geometry_around(target: ScreenRect) -> Option<ShareGeometry> {
278
301
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,
279
302
_ => 1.,
280
303
};
281
let RECT { left, top, right, bottom } = info.rcWork;
304
let RECT {
305
left,
306
top,
307
right,
308
bottom,
309
} = info.rcWork;
282
310
Some(ShareGeometry {
283
311
target,
284
work: WorkArea { left, top, right, bottom, scale },
312
work: WorkArea {
313
left,
314
top,
315
right,
316
bottom,
317
scale,
318
},
285
319
})
286
320
}
287
321
}
@@ -348,7 +382,8 @@ pub fn stop_flash(handle: NativeHandle) {
348
382
349
383
pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {
350
384
unsafe {
351
let Ok(taskbar) = CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
385
let Ok(taskbar) =
386
CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)
352
387
else {
353
388
return;
354
389
};
@@ -442,7 +477,11 @@ fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {
442
477
};
443
478
while !flag.load(Ordering::SeqCst) {
444
479
let player = rodio::Player::connect_new(sink.mixer());
445
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));
480
player.append(rodio::buffer::SamplesBuffer::new(
481
channels,
482
rate,
483
cycle.clone(),
484
));
446
485
while !player.empty() {
447
486
if flag.load(Ordering::SeqCst) {
448
487
player.stop();
@@ -570,7 +609,8 @@ fn tray_icons() -> Option<(Icon, Icon)> {
570
609
let size = TRAY_ICON_SIZE as f32;
571
610
let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);
572
611
for (column, row, pixel) in dotted.enumerate_pixels_mut() {
573
let distance = ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
612
let distance =
613
((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();
574
614
if distance <= TRAY_DOT_RADIUS {
575
615
*pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);
576
616
}
@@ -12,28 +12,30 @@ use tray_icon::menu::{CheckMenuItem, Menu, MenuEvent, MenuItem, PredefinedMenuIt12
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, POINT, 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,16
DWMWCP_DONOTROUND, DwmGetWindowAttribute, DwmSetWindowAttribute,16
DWMWA_WINDOW_CORNER_PREFERENCE, DWMWCP_DONOTROUND, DwmGetWindowAttribute,17
DwmSetWindowAttribute,17
};18
};18
use windows::Win32::Graphics::Gdi::{19
use windows::Win32::Graphics::Gdi::{19
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject, ENUM_CURRENT_SETTINGS,20
CreateBitmap, DEVMODEW, DISPLAY_DEVICE_ACTIVE, DISPLAY_DEVICEW, DeleteObject,20
EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ, MONITOR_DEFAULTTONEAREST, MONITORINFO,21
ENUM_CURRENT_SETTINGS, EnumDisplayDevicesW, EnumDisplaySettingsW, GetMonitorInfoW, HGDIOBJ,21
MonitorFromPoint, MonitorFromRect, MonitorFromWindow,22
MONITOR_DEFAULTTONEAREST, MONITORINFO, MonitorFromPoint, MonitorFromRect, MonitorFromWindow,22
};23
};23
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};24
use windows::Win32::System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance};24
use windows::Win32::UI::HiDpi::{GetDpiForWindow, GetDpiForMonitor, MDT_EFFECTIVE_DPI};25
use windows::Win32::UI::HiDpi::{GetDpiForMonitor, GetDpiForWindow, MDT_EFFECTIVE_DPI};25
use windows::Win32::UI::Shell::{26
use windows::Win32::UI::Shell::{26
ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME, QUNS_RUNNING_D3D_FULL_SCREEN,27
ITaskbarList3, QUNS_BUSY, QUNS_PRESENTATION_MODE, QUNS_QUIET_TIME,27
SHQueryUserNotificationState, TaskbarList,28
QUNS_RUNNING_D3D_FULL_SCREEN, SHQueryUserNotificationState, TaskbarList,28
};29
};29
use windows::Win32::UI::WindowsAndMessaging::{30
use windows::Win32::UI::WindowsAndMessaging::{30
CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO, FlashWindowEx, GWL_EXSTYLE, GWL_STYLE,31
CreateIconIndirect, DestroyIcon, FLASHW_STOP, FLASHW_TIMERNOFG, FLASHW_TRAY, FLASHWINFO,31
GetWindowLongPtrW, HICON, HWND_TOPMOST, ICONINFO, IsIconic, SW_HIDE, SW_RESTORE, SW_SHOW, SWP_NOACTIVATE,32
FlashWindowEx, GWL_EXSTYLE, GWL_STYLE, GetWindowLongPtrW, GetWindowRect, HICON, HWND_TOPMOST,32
SPI_GETCLIENTAREAANIMATION, SWP_FRAMECHANGED, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE,33
ICONINFO, IsIconic, LWA_ALPHA, SPI_GETCLIENTAREAANIMATION, SW_HIDE, SW_RESTORE, SW_SHOW,33
SWP_NOZORDER, WS_CAPTION, WS_POPUP, WS_THICKFRAME, SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetForegroundWindow,34
SWP_FRAMECHANGED, SWP_NOACTIVATE, SWP_NOMOVE, SWP_NOOWNERZORDER, SWP_NOSIZE, SWP_NOZORDER,34
SetWindowLongPtrW, SetWindowPos, ShowWindow, SystemParametersInfoW,35
SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SetForegroundWindow, SetLayeredWindowAttributes,35
WS_EX_NOACTIVATE, WS_EX_LAYERED, WS_EX_TRANSPARENT, LWA_ALPHA, SetLayeredWindowAttributes, SetWindowDisplayAffinity,36
SetWindowDisplayAffinity, SetWindowLongPtrW, SetWindowPos, ShowWindow, SystemParametersInfoW,36
WDA_EXCLUDEFROMCAPTURE, GetWindowRect,37
WDA_EXCLUDEFROMCAPTURE, WS_CAPTION, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_TRANSPARENT,38
WS_POPUP, WS_THICKFRAME,37
};39
};38
use windows::core::{BOOL, PCWSTR, w};40
use windows::core::{BOOL, PCWSTR, w};39
41
@@ -105,7 +107,11 @@ pub fn set_activatable(handle: NativeHandle, activatable: bool) {105
unsafe {107
unsafe {106
let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);108
let style = GetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE);107
let flag = WS_EX_NOACTIVATE.0 as isize;109
let flag = WS_EX_NOACTIVATE.0 as isize;108
let updated = if activatable { style & !flag } else { style | flag };110
let updated = if activatable {111
style & !flag112
} else {113
style | flag114
};109
SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated);115
SetWindowLongPtrW(hwnd(handle), GWL_EXSTYLE, updated);110
if activatable {116
if activatable {111
let _ = SetForegroundWindow(hwnd(handle));117
let _ = SetForegroundWindow(hwnd(handle));@@ -155,8 +161,19 @@ pub fn work_area_at(x: i32, y: i32) -> Option<WorkArea> {155
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,161
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,156
_ => 1.,162
_ => 1.,157
};163
};158
let RECT { left, top, right, bottom } = info.rcWork;164
let RECT {159
Some(WorkArea { left, top, right, bottom, scale })165
left,166
top,167
right,168
bottom,169
} = info.rcWork;170
Some(WorkArea {171
left,172
top,173
right,174
bottom,175
scale,176
})160
}177
}161
}178
}162
179
@@ -244,7 +261,13 @@ fn screen_frame(index: u32) -> Option<ScreenRect> {244
dmSize: size_of::<DEVMODEW>() as u16,261
dmSize: size_of::<DEVMODEW>() as u16,245
..Default::default()262
..Default::default()246
};263
};247
if !EnumDisplaySettingsW(PCWSTR(device.DeviceName.as_ptr()), ENUM_CURRENT_SETTINGS, &mut mode).as_bool() {264
if !EnumDisplaySettingsW(265
PCWSTR(device.DeviceName.as_ptr()),266
ENUM_CURRENT_SETTINGS,267
&mut mode,268
)269
.as_bool()270
{248
return None;271
return None;249
}272
}250
let position = mode.Anonymous1.Anonymous2.dmPosition;273
let position = mode.Anonymous1.Anonymous2.dmPosition;@@ -278,10 +301,21 @@ fn geometry_around(target: ScreenRect) -> Option<ShareGeometry> {278
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,301
Ok(()) if dpi_x > 0 => dpi_x as f32 / BASE_DPI,279
_ => 1.,302
_ => 1.,280
};303
};281
let RECT { left, top, right, bottom } = info.rcWork;304
let RECT {305
left,306
top,307
right,308
bottom,309
} = info.rcWork;282
Some(ShareGeometry {310
Some(ShareGeometry {283
target,311
target,284
work: WorkArea { left, top, right, bottom, scale },312
work: WorkArea {313
left,314
top,315
right,316
bottom,317
scale,318
},285
})319
})286
}320
}287
}321
}@@ -348,7 +382,8 @@ pub fn stop_flash(handle: NativeHandle) {348
382
349
pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {383
pub fn set_badge(handle: NativeHandle, badge: Option<&Badge>) {350
unsafe {384
unsafe {351
let Ok(taskbar) = CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)385
let Ok(taskbar) =386
CoCreateInstance::<_, ITaskbarList3>(&TaskbarList, None, CLSCTX_INPROC_SERVER)352
else {387
else {353
return;388
return;354
};389
};@@ -442,7 +477,11 @@ fn start_cycle(cycle: Vec<f32>) -> Option<RingTone> {442
};477
};443
while !flag.load(Ordering::SeqCst) {478
while !flag.load(Ordering::SeqCst) {444
let player = rodio::Player::connect_new(sink.mixer());479
let player = rodio::Player::connect_new(sink.mixer());445
player.append(rodio::buffer::SamplesBuffer::new(channels, rate, cycle.clone()));480
player.append(rodio::buffer::SamplesBuffer::new(481
channels,482
rate,483
cycle.clone(),484
));446
while !player.empty() {485
while !player.empty() {447
if flag.load(Ordering::SeqCst) {486
if flag.load(Ordering::SeqCst) {448
player.stop();487
player.stop();@@ -570,7 +609,8 @@ fn tray_icons() -> Option<(Icon, Icon)> {570
let size = TRAY_ICON_SIZE as f32;609
let size = TRAY_ICON_SIZE as f32;571
let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);610
let center = (size - TRAY_DOT_RADIUS - 1., size - TRAY_DOT_RADIUS - 1.);572
for (column, row, pixel) in dotted.enumerate_pixels_mut() {611
for (column, row, pixel) in dotted.enumerate_pixels_mut() {573
let distance = ((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();612
let distance =613
((column as f32 - center.0).powi(2) + (row as f32 - center.1).powi(2)).sqrt();574
if distance <= TRAY_DOT_RADIUS {614
if distance <= TRAY_DOT_RADIUS {575
*pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);615
*pixel = image::Rgba([0xef, 0x44, 0x44, 0xff]);576
}616
}@@ -46,14 +46,26 @@ impl Ringtone {
46
46
}
47
47
48
48
pub fn from_key(key: &str) -> Option<Ringtone> {
49
Ringtone::ALL.into_iter().find(|ringtone| ringtone.key() == key)
49
Ringtone::ALL
50
.into_iter()
51
.find(|ringtone| ringtone.key() == key)
50
52
}
51
53
52
54
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {
53
55
match self {
54
56
Ringtone::Default => ring_cycle(sample_rate),
55
Ringtone::Chime => tone_cycle(sample_rate, &CHIME_NOTES, CHIME_NOTE_SECONDS, CHIME_CYCLE_SECONDS),
56
Ringtone::Pulse => tone_cycle(sample_rate, &PULSE_NOTES, PULSE_NOTE_SECONDS, PULSE_CYCLE_SECONDS),
57
Ringtone::Chime => tone_cycle(
58
sample_rate,
59
&CHIME_NOTES,
60
CHIME_NOTE_SECONDS,
61
CHIME_CYCLE_SECONDS,
62
),
63
Ringtone::Pulse => tone_cycle(
64
sample_rate,
65
&PULSE_NOTES,
66
PULSE_NOTE_SECONDS,
67
PULSE_CYCLE_SECONDS,
68
),
57
69
}
58
70
}
59
71
}
@@ -63,10 +75,20 @@ pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {
63
75
}
64
76
65
77
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {
66
tone_cycle(sample_rate, &[RINGBACK_HZ], RINGBACK_ON_SECONDS, RINGBACK_CYCLE_SECONDS)
78
tone_cycle(
79
sample_rate,
80
&[RINGBACK_HZ],
81
RINGBACK_ON_SECONDS,
82
RINGBACK_CYCLE_SECONDS,
83
)
67
84
}
68
85
69
fn tone_cycle(sample_rate: u32, frequencies: &[f32], tone_seconds: f32, cycle_seconds: f32) -> Vec<f32> {
86
fn tone_cycle(
87
sample_rate: u32,
88
frequencies: &[f32],
89
tone_seconds: f32,
90
cycle_seconds: f32,
91
) -> Vec<f32> {
70
92
let total = (cycle_seconds * sample_rate as f32) as usize;
71
93
let tone = (tone_seconds * sample_rate as f32) as usize;
72
94
let fade = (FADE_SECONDS * sample_rate as f32) as usize;
@@ -90,7 +112,11 @@ mod tests {
90
112
fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {
91
113
let samples = ring_cycle(SAMPLE_RATE);
92
114
assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);
93
assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));
115
assert!(
116
samples
117
.iter()
118
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)
119
);
94
120
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
95
121
}
96
122
@@ -121,9 +147,16 @@ mod tests {
121
147
let samples = ringback_cycle(SAMPLE_RATE);
122
148
let rate = SAMPLE_RATE as usize;
123
149
assert_eq!(samples.len(), 5 * rate);
124
assert!(samples[..rate].iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
150
assert!(
151
samples[..rate]
152
.iter()
153
.any(|sample| sample.abs() > AMPLITUDE * 0.9)
154
);
125
155
assert!(samples[rate..].iter().all(|sample| *sample == 0.));
126
let crossings = samples[..rate].windows(2).filter(|pair| pair[0] < 0. && pair[1] >= 0.).count();
156
let crossings = samples[..rate]
157
.windows(2)
158
.filter(|pair| pair[0] < 0. && pair[1] >= 0.)
159
.count();
127
160
assert!((424..=426).contains(&crossings));
128
161
}
129
162
@@ -131,12 +164,22 @@ mod tests {
131
164
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {
132
165
for ringtone in Ringtone::ALL {
133
166
let samples = ringtone.cycle(SAMPLE_RATE);
134
assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));
167
assert!(
168
samples
169
.iter()
170
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)
171
);
135
172
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));
136
173
assert_eq!(samples.last().copied(), Some(0.));
137
174
}
138
assert_ne!(Ringtone::Default.cycle(SAMPLE_RATE), Ringtone::Chime.cycle(SAMPLE_RATE));
139
assert_ne!(Ringtone::Chime.cycle(SAMPLE_RATE), Ringtone::Pulse.cycle(SAMPLE_RATE));
175
assert_ne!(
176
Ringtone::Default.cycle(SAMPLE_RATE),
177
Ringtone::Chime.cycle(SAMPLE_RATE)
178
);
179
assert_ne!(
180
Ringtone::Chime.cycle(SAMPLE_RATE),
181
Ringtone::Pulse.cycle(SAMPLE_RATE)
182
);
140
183
}
141
184
142
185
#[test]
@@ -46,14 +46,26 @@ impl Ringtone {46
}46
}47
47
48
pub fn from_key(key: &str) -> Option<Ringtone> {48
pub fn from_key(key: &str) -> Option<Ringtone> {49
Ringtone::ALL.into_iter().find(|ringtone| ringtone.key() == key)49
Ringtone::ALL50
.into_iter()51
.find(|ringtone| ringtone.key() == key)50
}52
}51
53
52
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {54
pub fn cycle(self, sample_rate: u32) -> Vec<f32> {53
match self {55
match self {54
Ringtone::Default => ring_cycle(sample_rate),56
Ringtone::Default => ring_cycle(sample_rate),55
Ringtone::Chime => tone_cycle(sample_rate, &CHIME_NOTES, CHIME_NOTE_SECONDS, CHIME_CYCLE_SECONDS),57
Ringtone::Chime => tone_cycle(56
Ringtone::Pulse => tone_cycle(sample_rate, &PULSE_NOTES, PULSE_NOTE_SECONDS, PULSE_CYCLE_SECONDS),58
sample_rate,59
&CHIME_NOTES,60
CHIME_NOTE_SECONDS,61
CHIME_CYCLE_SECONDS,62
),63
Ringtone::Pulse => tone_cycle(64
sample_rate,65
&PULSE_NOTES,66
PULSE_NOTE_SECONDS,67
PULSE_CYCLE_SECONDS,68
),57
}69
}58
}70
}59
}71
}@@ -63,10 +75,20 @@ pub fn ring_cycle(sample_rate: u32) -> Vec<f32> {63
}75
}64
76
65
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {77
pub fn ringback_cycle(sample_rate: u32) -> Vec<f32> {66
tone_cycle(sample_rate, &[RINGBACK_HZ], RINGBACK_ON_SECONDS, RINGBACK_CYCLE_SECONDS)78
tone_cycle(79
sample_rate,80
&[RINGBACK_HZ],81
RINGBACK_ON_SECONDS,82
RINGBACK_CYCLE_SECONDS,83
)67
}84
}68
85
69
fn tone_cycle(sample_rate: u32, frequencies: &[f32], tone_seconds: f32, cycle_seconds: f32) -> Vec<f32> {86
fn tone_cycle(87
sample_rate: u32,88
frequencies: &[f32],89
tone_seconds: f32,90
cycle_seconds: f32,91
) -> Vec<f32> {70
let total = (cycle_seconds * sample_rate as f32) as usize;92
let total = (cycle_seconds * sample_rate as f32) as usize;71
let tone = (tone_seconds * sample_rate as f32) as usize;93
let tone = (tone_seconds * sample_rate as f32) as usize;72
let fade = (FADE_SECONDS * sample_rate as f32) as usize;94
let fade = (FADE_SECONDS * sample_rate as f32) as usize;@@ -90,7 +112,11 @@ mod tests {90
fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {112
fn a_cycle_lasts_two_and_a_half_seconds_at_most_and_stays_quiet() {91
let samples = ring_cycle(SAMPLE_RATE);113
let samples = ring_cycle(SAMPLE_RATE);92
assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);114
assert_eq!(samples.len(), (CYCLE_SECONDS * SAMPLE_RATE as f32) as usize);93
assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));115
assert!(116
samples117
.iter()118
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)119
);94
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));120
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));95
}121
}96
122
@@ -121,9 +147,16 @@ mod tests {121
let samples = ringback_cycle(SAMPLE_RATE);147
let samples = ringback_cycle(SAMPLE_RATE);122
let rate = SAMPLE_RATE as usize;148
let rate = SAMPLE_RATE as usize;123
assert_eq!(samples.len(), 5 * rate);149
assert_eq!(samples.len(), 5 * rate);124
assert!(samples[..rate].iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));150
assert!(151
samples[..rate]152
.iter()153
.any(|sample| sample.abs() > AMPLITUDE * 0.9)154
);125
assert!(samples[rate..].iter().all(|sample| *sample == 0.));155
assert!(samples[rate..].iter().all(|sample| *sample == 0.));126
let crossings = samples[..rate].windows(2).filter(|pair| pair[0] < 0. && pair[1] >= 0.).count();156
let crossings = samples[..rate]157
.windows(2)158
.filter(|pair| pair[0] < 0. && pair[1] >= 0.)159
.count();127
assert!((424..=426).contains(&crossings));160
assert!((424..=426).contains(&crossings));128
}161
}129
162
@@ -131,12 +164,22 @@ mod tests {131
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {164
fn every_ringtone_is_quiet_ends_in_silence_and_differs_from_the_others() {132
for ringtone in Ringtone::ALL {165
for ringtone in Ringtone::ALL {133
let samples = ringtone.cycle(SAMPLE_RATE);166
let samples = ringtone.cycle(SAMPLE_RATE);134
assert!(samples.iter().all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON));167
assert!(168
samples169
.iter()170
.all(|sample| sample.abs() <= AMPLITUDE + f32::EPSILON)171
);135
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));172
assert!(samples.iter().any(|sample| sample.abs() > AMPLITUDE * 0.9));136
assert_eq!(samples.last().copied(), Some(0.));173
assert_eq!(samples.last().copied(), Some(0.));137
}174
}138
assert_ne!(Ringtone::Default.cycle(SAMPLE_RATE), Ringtone::Chime.cycle(SAMPLE_RATE));175
assert_ne!(139
assert_ne!(Ringtone::Chime.cycle(SAMPLE_RATE), Ringtone::Pulse.cycle(SAMPLE_RATE));176
Ringtone::Default.cycle(SAMPLE_RATE),177
Ringtone::Chime.cycle(SAMPLE_RATE)178
);179
assert_ne!(180
Ringtone::Chime.cycle(SAMPLE_RATE),181
Ringtone::Pulse.cycle(SAMPLE_RATE)182
);140
}183
}141
184
142
#[test]185
#[test]@@ -39,7 +39,12 @@ impl RingView {
39
39
}
40
40
}
41
41
42
fn answer_button(id: &'static str, label: &str, glyph: IconName, fill: Hsla) -> Stateful<gpui_kit::Div> {
42
fn answer_button(
43
id: &'static str,
44
label: &str,
45
glyph: IconName,
46
fill: Hsla,
47
) -> Stateful<gpui_kit::Div> {
43
48
h_flex()
44
49
.id(id)
45
50
.h(px(BUTTON_HEIGHT))
@@ -79,7 +84,10 @@ impl Render for RingView {
79
84
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
80
85
let state = self.app.read(cx);
81
86
let Some(entry) = state.rings.get(self.ring_id).cloned() else {
82
return div().size_full().bg(theme::surface_raised()).into_any_element();
87
return div()
88
.size_full()
89
.bg(theme::surface_raised())
90
.into_any_element();
83
91
};
84
92
window.set_window_title(&format!("{}: {}", entry.caller_name(), entry.subtitle()));
85
93
let ends_current = state.call.is_some();
@@ -87,23 +95,36 @@ impl Render for RingView {
87
95
let ring_id = self.ring_id;
88
96
let decline_app = self.app.clone();
89
97
let accept_app = self.app.clone();
90
let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red()).on_click(
91
move |_, _, cx| {
98
let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red())
99
.on_click(move |_, _, cx| {
92
100
cx.stop_propagation();
93
101
decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));
94
},
95
);
96
let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(
97
move |_, _, cx| {
98
cx.stop_propagation();
99
accept_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Audio, cx));
100
},
101
);
102
});
103
let accept = answer_button(
104
"ring-accept",
105
entry.accept_label(),
106
IconName::Phone,
107
theme::green(),
108
)
109
.on_click(move |_, _, cx| {
110
cx.stop_propagation();
111
accept_app.update(cx, |state, cx| {
112
state.accept_ring(ring_id, AcceptMode::Audio, cx)
113
});
114
});
102
115
let video_app = self.app.clone();
103
116
let accept_video = entry.ring.video.then(|| {
104
answer_button("ring-accept-video", "Video", IconName::Video, theme::green()).on_click(move |_, _, cx| {
117
answer_button(
118
"ring-accept-video",
119
"Video",
120
IconName::Video,
121
theme::green(),
122
)
123
.on_click(move |_, _, cx| {
105
124
cx.stop_propagation();
106
video_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Video, cx));
125
video_app.update(cx, |state, cx| {
126
state.accept_ring(ring_id, AcceptMode::Video, cx)
127
});
107
128
})
108
129
});
109
130
div()
@@ -148,7 +169,14 @@ impl Render for RingView {
148
169
.child(ENDS_CURRENT_CALL),
149
170
)
150
171
})
151
.child(h_flex().mt(px(8.)).gap(px(6.)).child(decline).child(accept).children(accept_video)),
172
.child(
173
h_flex()
174
.mt(px(8.))
175
.gap(px(6.))
176
.child(decline)
177
.child(accept)
178
.children(accept_video),
179
),
152
180
),
153
181
),
154
182
)
@@ -39,7 +39,12 @@ impl RingView {39
}39
}40
}40
}41
41
42
fn answer_button(id: &'static str, label: &str, glyph: IconName, fill: Hsla) -> Stateful<gpui_kit::Div> {42
fn answer_button(43
id: &'static str,44
label: &str,45
glyph: IconName,46
fill: Hsla,47
) -> Stateful<gpui_kit::Div> {43
h_flex()48
h_flex()44
.id(id)49
.id(id)45
.h(px(BUTTON_HEIGHT))50
.h(px(BUTTON_HEIGHT))@@ -79,7 +84,10 @@ impl Render for RingView {79
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {84
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {80
let state = self.app.read(cx);85
let state = self.app.read(cx);81
let Some(entry) = state.rings.get(self.ring_id).cloned() else {86
let Some(entry) = state.rings.get(self.ring_id).cloned() else {82
return div().size_full().bg(theme::surface_raised()).into_any_element();87
return div()88
.size_full()89
.bg(theme::surface_raised())90
.into_any_element();83
};91
};84
window.set_window_title(&format!("{}: {}", entry.caller_name(), entry.subtitle()));92
window.set_window_title(&format!("{}: {}", entry.caller_name(), entry.subtitle()));85
let ends_current = state.call.is_some();93
let ends_current = state.call.is_some();@@ -87,23 +95,36 @@ impl Render for RingView {87
let ring_id = self.ring_id;95
let ring_id = self.ring_id;88
let decline_app = self.app.clone();96
let decline_app = self.app.clone();89
let accept_app = self.app.clone();97
let accept_app = self.app.clone();90
let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red()).on_click(98
let decline = answer_button("ring-decline", "Decline", IconName::PhoneOff, theme::red())91
move |_, _, cx| {99
.on_click(move |_, _, cx| {92
cx.stop_propagation();100
cx.stop_propagation();93
decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));101
decline_app.update(cx, |state, cx| state.decline_ring(ring_id, cx));94
},102
});95
);103
let accept = answer_button(96
let accept = answer_button("ring-accept", entry.accept_label(), IconName::Phone, theme::green()).on_click(104
"ring-accept",97
move |_, _, cx| {105
entry.accept_label(),98
cx.stop_propagation();106
IconName::Phone,99
accept_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Audio, cx));107
theme::green(),100
},108
)101
);109
.on_click(move |_, _, cx| {110
cx.stop_propagation();111
accept_app.update(cx, |state, cx| {112
state.accept_ring(ring_id, AcceptMode::Audio, cx)113
});114
});102
let video_app = self.app.clone();115
let video_app = self.app.clone();103
let accept_video = entry.ring.video.then(|| {116
let accept_video = entry.ring.video.then(|| {104
answer_button("ring-accept-video", "Video", IconName::Video, theme::green()).on_click(move |_, _, cx| {117
answer_button(118
"ring-accept-video",119
"Video",120
IconName::Video,121
theme::green(),122
)123
.on_click(move |_, _, cx| {105
cx.stop_propagation();124
cx.stop_propagation();106
video_app.update(cx, |state, cx| state.accept_ring(ring_id, AcceptMode::Video, cx));125
video_app.update(cx, |state, cx| {126
state.accept_ring(ring_id, AcceptMode::Video, cx)127
});107
})128
})108
});129
});109
div()130
div()@@ -148,7 +169,14 @@ impl Render for RingView {148
.child(ENDS_CURRENT_CALL),169
.child(ENDS_CURRENT_CALL),149
)170
)150
})171
})151
.child(h_flex().mt(px(8.)).gap(px(6.)).child(decline).child(accept).children(accept_video)),172
.child(173
h_flex()174
.mt(px(8.))175
.gap(px(6.))176
.child(decline)177
.child(accept)178
.children(accept_video),179
),152
),180
),153
),181
),154
)182
)@@ -1,8 +1,8 @@
1
1
use std::collections::HashMap;
2
2
use std::time::{Duration, Instant};
3
3
4
use chrono::{DateTime, Utc};
5
4
use calling::Progress;
5
use chrono::{DateTime, Utc};
6
6
use store::{ChannelNotificationLevel, ChannelNotifications};
7
7
8
8
use super::ring_tone::Ringtone;
@@ -345,12 +345,29 @@ mod tests {
345
345
};
346
346
let since = std::time::Instant::now();
347
347
assert!(!should_ringback(None));
348
assert!(!should_ringback(Some(&outgoing(None, CallState::Connecting))));
349
assert!(should_ringback(Some(&outgoing(Some(Progress::Calling), CallState::Connecting))));
350
assert!(should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connecting))));
351
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connected { since }))));
352
let ended = CallState::Ended { reason: EndReason::LocalHangup };
353
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), ended))));
348
assert!(!should_ringback(Some(&outgoing(
349
None,
350
CallState::Connecting
351
))));
352
assert!(should_ringback(Some(&outgoing(
353
Some(Progress::Calling),
354
CallState::Connecting
355
))));
356
assert!(should_ringback(Some(&outgoing(
357
Some(Progress::Ringing),
358
CallState::Connecting
359
))));
360
assert!(!should_ringback(Some(&outgoing(
361
Some(Progress::Ringing),
362
CallState::Connected { since }
363
))));
364
let ended = CallState::Ended {
365
reason: EndReason::LocalHangup,
366
};
367
assert!(!should_ringback(Some(&outgoing(
368
Some(Progress::Ringing),
369
ended
370
))));
354
371
let mut meeting = CallModel::meeting("Standup", false);
355
372
meeting.progress = Some(Progress::Calling);
356
373
assert!(!should_ringback(Some(&meeting)));
@@ -1,8 +1,8 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
use std::time::{Duration, Instant};2
use std::time::{Duration, Instant};3
3
4
use chrono::{DateTime, Utc};5
use calling::Progress;4
use calling::Progress;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::ring_tone::Ringtone;@@ -345,12 +345,29 @@ mod tests {345
};345
};346
let since = std::time::Instant::now();346
let since = std::time::Instant::now();347
assert!(!should_ringback(None));347
assert!(!should_ringback(None));348
assert!(!should_ringback(Some(&outgoing(None, CallState::Connecting))));348
assert!(!should_ringback(Some(&outgoing(349
assert!(should_ringback(Some(&outgoing(Some(Progress::Calling), CallState::Connecting))));349
None,350
assert!(should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connecting))));350
CallState::Connecting351
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), CallState::Connected { since }))));351
))));352
let ended = CallState::Ended { reason: EndReason::LocalHangup };352
assert!(should_ringback(Some(&outgoing(353
assert!(!should_ringback(Some(&outgoing(Some(Progress::Ringing), ended))));353
Some(Progress::Calling),354
CallState::Connecting355
))));356
assert!(should_ringback(Some(&outgoing(357
Some(Progress::Ringing),358
CallState::Connecting359
))));360
assert!(!should_ringback(Some(&outgoing(361
Some(Progress::Ringing),362
CallState::Connected { since }363
))));364
let ended = CallState::Ended {365
reason: EndReason::LocalHangup,366
};367
assert!(!should_ringback(Some(&outgoing(368
Some(Progress::Ringing),369
ended370
))));354
let mut meeting = CallModel::meeting("Standup", false);371
let mut meeting = CallModel::meeting("Standup", false);355
meeting.progress = Some(Progress::Calling);372
meeting.progress = Some(Progress::Calling);356
assert!(!should_ringback(Some(&meeting)));373
assert!(!should_ringback(Some(&meeting)));@@ -9,7 +9,7 @@ use gpui_kit::component::{
9
9
};
10
10
use gpui_kit::prelude::FluentBuilder as _;
11
11
use gpui_kit::*;
12
use mcp::install::{Homes, InstallReport, InstallState, Location, Target};
12
use mcp::install::{InstallReport, InstallState, Location, Target};
13
13
use mcp::{Access, AgentPolicy};
14
14
15
15
use super::settings_view::{control_row, switch, titled_with};
@@ -305,8 +305,9 @@ impl McpView {
305
305
let Some(endpoint) = agent_api::configured_endpoint(cx) else {
306
306
return;
307
307
};
308
let demo = agent_api::is_demo(cx);
308
309
let task = cx.background_spawn(async move {
309
let homes = Homes::detect();
310
let homes = agent_api::agent_homes(demo);
310
311
Target::ALL
311
312
.map(|target| mcp::install::status(target, &endpoint, &homes))
312
313
.to_vec()
@@ -333,8 +334,9 @@ impl McpView {
333
334
};
334
335
self.install_busy = Some((target, action));
335
336
self.install_errors.remove(&target);
337
let demo = agent_api::is_demo(cx);
336
338
let task = cx.background_spawn(async move {
337
let homes = Homes::detect();
339
let homes = agent_api::agent_homes(demo);
338
340
match action {
339
341
InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),
340
342
_ => mcp::install::install(target, &endpoint, &homes).map(Some),
@@ -9,7 +9,7 @@ use gpui_kit::component::{9
};9
};10
use gpui_kit::prelude::FluentBuilder as _;10
use gpui_kit::prelude::FluentBuilder as _;11
use gpui_kit::*;11
use gpui_kit::*;12
use mcp::install::{Homes, InstallReport, InstallState, Location, Target};12
use mcp::install::{InstallReport, InstallState, Location, Target};13
use mcp::{Access, AgentPolicy};13
use mcp::{Access, AgentPolicy};14
14
15
use super::settings_view::{control_row, switch, titled_with};15
use super::settings_view::{control_row, switch, titled_with};@@ -305,8 +305,9 @@ impl McpView {305
let Some(endpoint) = agent_api::configured_endpoint(cx) else {305
let Some(endpoint) = agent_api::configured_endpoint(cx) else {306
return;306
return;307
};307
};308
let demo = agent_api::is_demo(cx);308
let task = cx.background_spawn(async move {309
let task = cx.background_spawn(async move {309
let homes = Homes::detect();310
let homes = agent_api::agent_homes(demo);310
Target::ALL311
Target::ALL311
.map(|target| mcp::install::status(target, &endpoint, &homes))312
.map(|target| mcp::install::status(target, &endpoint, &homes))312
.to_vec()313
.to_vec()@@ -333,8 +334,9 @@ impl McpView {333
};334
};334
self.install_busy = Some((target, action));335
self.install_busy = Some((target, action));335
self.install_errors.remove(&target);336
self.install_errors.remove(&target);337
let demo = agent_api::is_demo(cx);336
let task = cx.background_spawn(async move {338
let task = cx.background_spawn(async move {337
let homes = Homes::detect();339
let homes = agent_api::agent_homes(demo);338
match action {340
match action {339
InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),341
InstallAction::Remove => mcp::install::uninstall(target, &homes).map(|_| None),340
_ => mcp::install::install(target, &endpoint, &homes).map(Some),342
_ => mcp::install::install(target, &endpoint, &homes).map(Some),@@ -42,7 +42,12 @@ pub(super) enum Section {
42
42
}
43
43
44
44
impl Section {
45
const ALL: [Section; 4] = [Section::Notifications, Section::Devices, Section::Agents, Section::Mcp];
45
const ALL: [Section; 4] = [
46
Section::Notifications,
47
Section::Devices,
48
Section::Agents,
49
Section::Mcp,
50
];
46
51
47
52
fn label(self) -> &'static str {
48
53
match self {
@@ -126,7 +131,11 @@ impl SettingsView {
126
131
let camera = state.call_camera.clone();
127
132
let preview_blocked = camera_in_call(state);
128
133
let background = Some(state.call_background.clone())
129
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))
134
.filter(|pick| {
135
preview_backgrounds(&state.call_backgrounds)
136
.iter()
137
.any(|(known, _)| known == pick)
138
})
130
139
.unwrap_or_default();
131
140
cx.spawn(async move |this, cx| {
132
141
while updates.recv().await.is_some() {
@@ -145,8 +154,8 @@ impl SettingsView {
145
154
}
146
155
})
147
156
.detach();
148
let agents = crate::agents::runs_handle(cx)
149
.map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
157
let agents =
158
crate::agents::runs_handle(cx).map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
150
159
SettingsView {
151
160
center,
152
161
section,
@@ -198,7 +207,10 @@ impl SettingsView {
198
207
return;
199
208
}
200
209
cx.spawn(async move |this, cx| {
201
let cameras = cx.background_executor().spawn(async { list_cameras() }).await;
210
let cameras = cx
211
.background_executor()
212
.spawn(async { list_cameras() })
213
.await;
202
214
this.update(cx, |view, cx| {
203
215
view.cameras = camera_entries(&cameras);
204
216
cx.notify();
@@ -345,7 +357,11 @@ fn section_tab(section: Section, active: bool, view: Entity<SettingsView>) -> St
345
357
.cursor_pointer()
346
358
.text_size(px(13.))
347
359
.font_weight(FontWeight::SEMIBOLD)
348
.text_color(if active { theme::on_accent() } else { theme::text() })
360
.text_color(if active {
361
theme::on_accent()
362
} else {
363
theme::text()
364
})
349
365
.when(active, |tab| tab.bg(theme::accent()))
350
366
.when(!active, |tab| tab.hover(|tab| tab.bg(theme::row_hover())))
351
367
.child(section.label())
@@ -370,14 +386,18 @@ impl SettingsView {
370
386
.dropdown_menu(move |menu, _, _| {
371
387
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {
372
388
let (center, ringtone) = (center.clone(), *ringtone);
373
menu.item(PopupMenuItem::new(ringtone.label()).checked(ringtone == current).on_click(
374
move |_, _, cx| {
375
center.update(cx, |center, cx| {
376
center.update_settings(cx, |settings| settings.ringtone = ringtone)
377
});
378
platform::play_preview(ringtone);
379
},
380
))
389
menu.item(
390
PopupMenuItem::new(ringtone.label())
391
.checked(ringtone == current)
392
.on_click(move |_, _, cx| {
393
center.update(cx, |center, cx| {
394
center.update_settings(cx, |settings| {
395
settings.ringtone = ringtone
396
})
397
});
398
platform::play_preview(ringtone);
399
}),
400
)
381
401
})
382
402
}),
383
403
)
@@ -395,7 +415,8 @@ impl SettingsView {
395
415
let cameras = self.cameras.clone();
396
416
let current_camera = self.camera.clone();
397
417
let camera_view = view.clone();
398
let backgrounds = preview_backgrounds(&self.center.read(cx).app().read(cx).call_backgrounds);
418
let backgrounds =
419
preview_backgrounds(&self.center.read(cx).app().read(cx).call_backgrounds);
399
420
let background_label = backgrounds
400
421
.iter()
401
422
.find(|(pick, _)| *pick == self.background)
@@ -409,7 +430,9 @@ impl SettingsView {
409
430
|| {
410
431
self.preview
411
432
.fps()
412
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))
433
.map_or("Starting camera...".to_owned(), |fps| {
434
format!("{fps:.0} fps")
435
})
413
436
},
414
437
|reason| format!("Camera could not start: {reason}"),
415
438
)
@@ -431,7 +454,9 @@ impl SettingsView {
431
454
PopupMenuItem::new(entry.label.clone())
432
455
.checked(entry.choice == current_camera)
433
456
.on_click(move |_, _, cx| {
434
view.update(cx, |view, cx| view.select_camera(choice.clone(), cx))
457
view.update(cx, |view, cx| {
458
view.select_camera(choice.clone(), cx)
459
})
435
460
}),
436
461
)
437
462
})
@@ -452,7 +477,9 @@ impl SettingsView {
452
477
PopupMenuItem::new(label.clone())
453
478
.checked(pick == current_background)
454
479
.on_click(move |_, _, cx| {
455
view.update(cx, |view, cx| view.select_background(pick.clone(), cx))
480
view.update(cx, |view, cx| {
481
view.select_background(pick.clone(), cx)
482
})
456
483
}),
457
484
)
458
485
})
@@ -481,7 +508,12 @@ impl SettingsView {
481
508
.rounded(px(PREVIEW_RADIUS))
482
509
})),
483
510
)
484
.child(div().text_size(px(12.)).text_color(theme::text_muted()).child(status)),
511
.child(
512
div()
513
.text_size(px(12.))
514
.text_color(theme::text_muted())
515
.child(status),
516
),
485
517
)
486
518
}
487
519
}
@@ -489,11 +521,9 @@ impl SettingsView {
489
521
impl Render for SettingsView {
490
522
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
491
523
let view = cx.entity();
492
let tabs = h_flex()
493
.w_full()
494
.px(px(20.))
495
.gap(px(8.))
496
.children(Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())));
524
let tabs = h_flex().w_full().px(px(20.)).gap(px(8.)).children(
525
Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())),
526
);
497
527
let body = match self.section {
498
528
Section::Notifications => self.notifications_section(cx).into_any_element(),
499
529
Section::Devices => self.devices_section(cx).into_any_element(),
@@ -578,14 +608,10 @@ impl SettingsView {
578
608
});
579
609
}),
580
610
))
581
.child(
582
h_flex()
583
.w_full()
584
.px(px(20.))
585
.pt(px(12.))
586
.child(button("Send test notification").on_click(move |_, _, cx| {
587
test_center.update(cx, |center, cx| center.send_test_notification(cx));
588
})),
589
)
611
.child(h_flex().w_full().px(px(20.)).pt(px(12.)).child(
612
button("Send test notification").on_click(move |_, _, cx| {
613
test_center.update(cx, |center, cx| center.send_test_notification(cx));
614
}),
615
))
590
616
}
591
617
}
@@ -42,7 +42,12 @@ pub(super) enum Section {42
}42
}43
43
44
impl Section {44
impl Section {45
const ALL: [Section; 4] = [Section::Notifications, Section::Devices, Section::Agents, Section::Mcp];45
const ALL: [Section; 4] = [46
Section::Notifications,47
Section::Devices,48
Section::Agents,49
Section::Mcp,50
];46
51
47
fn label(self) -> &'static str {52
fn label(self) -> &'static str {48
match self {53
match self {@@ -126,7 +131,11 @@ impl SettingsView {126
let camera = state.call_camera.clone();131
let camera = state.call_camera.clone();127
let preview_blocked = camera_in_call(state);132
let preview_blocked = camera_in_call(state);128
let background = Some(state.call_background.clone())133
let background = Some(state.call_background.clone())129
.filter(|pick| preview_backgrounds(&state.call_backgrounds).iter().any(|(known, _)| known == pick))134
.filter(|pick| {135
preview_backgrounds(&state.call_backgrounds)136
.iter()137
.any(|(known, _)| known == pick)138
})130
.unwrap_or_default();139
.unwrap_or_default();131
cx.spawn(async move |this, cx| {140
cx.spawn(async move |this, cx| {132
while updates.recv().await.is_some() {141
while updates.recv().await.is_some() {@@ -145,8 +154,8 @@ impl SettingsView {145
}154
}146
})155
})147
.detach();156
.detach();148
let agents = crate::agents::runs_handle(cx)157
let agents =149
.map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));158
crate::agents::runs_handle(cx).map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));150
SettingsView {159
SettingsView {151
center,160
center,152
section,161
section,@@ -198,7 +207,10 @@ impl SettingsView {198
return;207
return;199
}208
}200
cx.spawn(async move |this, cx| {209
cx.spawn(async move |this, cx| {201
let cameras = cx.background_executor().spawn(async { list_cameras() }).await;210
let cameras = cx211
.background_executor()212
.spawn(async { list_cameras() })213
.await;202
this.update(cx, |view, cx| {214
this.update(cx, |view, cx| {203
view.cameras = camera_entries(&cameras);215
view.cameras = camera_entries(&cameras);204
cx.notify();216
cx.notify();@@ -345,7 +357,11 @@ fn section_tab(section: Section, active: bool, view: Entity<SettingsView>) -> St345
.cursor_pointer()357
.cursor_pointer()346
.text_size(px(13.))358
.text_size(px(13.))347
.font_weight(FontWeight::SEMIBOLD)359
.font_weight(FontWeight::SEMIBOLD)348
.text_color(if active { theme::on_accent() } else { theme::text() })360
.text_color(if active {361
theme::on_accent()362
} else {363
theme::text()364
})349
.when(active, |tab| tab.bg(theme::accent()))365
.when(active, |tab| tab.bg(theme::accent()))350
.when(!active, |tab| tab.hover(|tab| tab.bg(theme::row_hover())))366
.when(!active, |tab| tab.hover(|tab| tab.bg(theme::row_hover())))351
.child(section.label())367
.child(section.label())@@ -370,14 +386,18 @@ impl SettingsView {370
.dropdown_menu(move |menu, _, _| {386
.dropdown_menu(move |menu, _, _| {371
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {387
Ringtone::ALL.iter().fold(menu, |menu, ringtone| {372
let (center, ringtone) = (center.clone(), *ringtone);388
let (center, ringtone) = (center.clone(), *ringtone);373
menu.item(PopupMenuItem::new(ringtone.label()).checked(ringtone == current).on_click(389
menu.item(374
move |_, _, cx| {390
PopupMenuItem::new(ringtone.label())375
center.update(cx, |center, cx| {391
.checked(ringtone == current)376
center.update_settings(cx, |settings| settings.ringtone = ringtone)392
.on_click(move |_, _, cx| {377
});393
center.update(cx, |center, cx| {378
platform::play_preview(ringtone);394
center.update_settings(cx, |settings| {379
},395
settings.ringtone = ringtone380
))396
})397
});398
platform::play_preview(ringtone);399
}),400
)381
})401
})382
}),402
}),383
)403
)@@ -395,7 +415,8 @@ impl SettingsView {395
let cameras = self.cameras.clone();415
let cameras = self.cameras.clone();396
let current_camera = self.camera.clone();416
let current_camera = self.camera.clone();397
let camera_view = view.clone();417
let camera_view = view.clone();398
let backgrounds = preview_backgrounds(&self.center.read(cx).app().read(cx).call_backgrounds);418
let backgrounds =419
preview_backgrounds(&self.center.read(cx).app().read(cx).call_backgrounds);399
let background_label = backgrounds420
let background_label = backgrounds400
.iter()421
.iter()401
.find(|(pick, _)| *pick == self.background)422
.find(|(pick, _)| *pick == self.background)@@ -409,7 +430,9 @@ impl SettingsView {409
|| {430
|| {410
self.preview431
self.preview411
.fps()432
.fps()412
.map_or("Starting camera...".to_owned(), |fps| format!("{fps:.0} fps"))433
.map_or("Starting camera...".to_owned(), |fps| {434
format!("{fps:.0} fps")435
})413
},436
},414
|reason| format!("Camera could not start: {reason}"),437
|reason| format!("Camera could not start: {reason}"),415
)438
)@@ -431,7 +454,9 @@ impl SettingsView {431
PopupMenuItem::new(entry.label.clone())454
PopupMenuItem::new(entry.label.clone())432
.checked(entry.choice == current_camera)455
.checked(entry.choice == current_camera)433
.on_click(move |_, _, cx| {456
.on_click(move |_, _, cx| {434
view.update(cx, |view, cx| view.select_camera(choice.clone(), cx))457
view.update(cx, |view, cx| {458
view.select_camera(choice.clone(), cx)459
})435
}),460
}),436
)461
)437
})462
})@@ -452,7 +477,9 @@ impl SettingsView {452
PopupMenuItem::new(label.clone())477
PopupMenuItem::new(label.clone())453
.checked(pick == current_background)478
.checked(pick == current_background)454
.on_click(move |_, _, cx| {479
.on_click(move |_, _, cx| {455
view.update(cx, |view, cx| view.select_background(pick.clone(), cx))480
view.update(cx, |view, cx| {481
view.select_background(pick.clone(), cx)482
})456
}),483
}),457
)484
)458
})485
})@@ -481,7 +508,12 @@ impl SettingsView {481
.rounded(px(PREVIEW_RADIUS))508
.rounded(px(PREVIEW_RADIUS))482
})),509
})),483
)510
)484
.child(div().text_size(px(12.)).text_color(theme::text_muted()).child(status)),511
.child(512
div()513
.text_size(px(12.))514
.text_color(theme::text_muted())515
.child(status),516
),485
)517
)486
}518
}487
}519
}@@ -489,11 +521,9 @@ impl SettingsView {489
impl Render for SettingsView {521
impl Render for SettingsView {490
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {522
fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {491
let view = cx.entity();523
let view = cx.entity();492
let tabs = h_flex()524
let tabs = h_flex().w_full().px(px(20.)).gap(px(8.)).children(493
.w_full()525
Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())),494
.px(px(20.))526
);495
.gap(px(8.))496
.children(Section::ALL.map(|section| section_tab(section, section == self.section, view.clone())));497
let body = match self.section {527
let body = match self.section {498
Section::Notifications => self.notifications_section(cx).into_any_element(),528
Section::Notifications => self.notifications_section(cx).into_any_element(),499
Section::Devices => self.devices_section(cx).into_any_element(),529
Section::Devices => self.devices_section(cx).into_any_element(),@@ -578,14 +608,10 @@ impl SettingsView {578
});608
});579
}),609
}),580
))610
))581
.child(611
.child(h_flex().w_full().px(px(20.)).pt(px(12.)).child(582
h_flex()612
button("Send test notification").on_click(move |_, _, cx| {583
.w_full()613
test_center.update(cx, |center, cx| center.send_test_notification(cx));584
.px(px(20.))614
}),585
.pt(px(12.))615
))586
.child(button("Send test notification").on_click(move |_, _, cx| {587
test_center.update(cx, |center, cx| center.send_test_notification(cx));588
})),589
)590
}616
}591
}617
}@@ -208,11 +208,9 @@ pub struct ToastStack {
208
208
209
209
impl ToastStack {
210
210
pub fn push(&mut self, incoming: &Incoming, now: Instant) -> PushOutcome {
211
if let Some(existing) = self
212
.toasts
213
.iter_mut()
214
.find(|toast| toast.agent.is_none() && toast.conversation_id == incoming.conversation_id)
215
{
211
if let Some(existing) = self.toasts.iter_mut().find(|toast| {
212
toast.agent.is_none() && toast.conversation_id == incoming.conversation_id
213
}) {
216
214
let became_mention = incoming.mentions_me && !existing.mentions_me;
217
215
existing.count += 1;
218
216
existing.mentions_me |= incoming.mentions_me;
@@ -305,9 +303,8 @@ impl ToastStack {
305
303
}
306
304
307
305
pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
308
let matches = |toast: &ToastModel| {
309
toast.agent.is_none() && toast.conversation_id == conversation_id
310
};
306
let matches =
307
|toast: &ToastModel| toast.agent.is_none() && toast.conversation_id == conversation_id;
311
308
let ids: Vec<u64> = self
312
309
.toasts
313
310
.iter()
@@ -506,8 +503,16 @@ mod tests {
506
503
stack.remove(ids[0]);
507
504
stack.promote(later, FADE_IN);
508
505
assert_eq!(visible_chats(&stack), ["b", "c", "d"]);
509
assert!(!stack.expired(later + Duration::from_secs(5)).contains(&ids[3]));
510
assert!(stack.expired(later + Duration::from_secs(6)).contains(&ids[3]));
506
assert!(
507
!stack
508
.expired(later + Duration::from_secs(5))
509
.contains(&ids[3])
510
);
511
assert!(
512
stack
513
.expired(later + Duration::from_secs(6))
514
.contains(&ids[3])
515
);
511
516
}
512
517
513
518
#[test]
@@ -208,11 +208,9 @@ pub struct ToastStack {208
208
209
impl ToastStack {209
impl ToastStack {210
pub fn push(&mut self, incoming: &Incoming, now: Instant) -> PushOutcome {210
pub fn push(&mut self, incoming: &Incoming, now: Instant) -> PushOutcome {211
if let Some(existing) = self211
if let Some(existing) = self.toasts.iter_mut().find(|toast| {212
.toasts212
toast.agent.is_none() && toast.conversation_id == incoming.conversation_id213
.iter_mut()213
}) {214
.find(|toast| toast.agent.is_none() && toast.conversation_id == incoming.conversation_id)215
{216
let became_mention = incoming.mentions_me && !existing.mentions_me;214
let became_mention = incoming.mentions_me && !existing.mentions_me;217
existing.count += 1;215
existing.count += 1;218
existing.mentions_me |= incoming.mentions_me;216
existing.mentions_me |= incoming.mentions_me;@@ -305,9 +303,8 @@ impl ToastStack {305
}303
}306
304
307
pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {305
pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {308
let matches = |toast: &ToastModel| {306
let matches =309
toast.agent.is_none() && toast.conversation_id == conversation_id307
|toast: &ToastModel| toast.agent.is_none() && toast.conversation_id == conversation_id;310
};311
let ids: Vec<u64> = self308
let ids: Vec<u64> = self312
.toasts309
.toasts313
.iter()310
.iter()@@ -506,8 +503,16 @@ mod tests {506
stack.remove(ids[0]);503
stack.remove(ids[0]);507
stack.promote(later, FADE_IN);504
stack.promote(later, FADE_IN);508
assert_eq!(visible_chats(&stack), ["b", "c", "d"]);505
assert_eq!(visible_chats(&stack), ["b", "c", "d"]);509
assert!(!stack.expired(later + Duration::from_secs(5)).contains(&ids[3]));506
assert!(510
assert!(stack.expired(later + Duration::from_secs(6)).contains(&ids[3]));507
!stack508
.expired(later + Duration::from_secs(5))509
.contains(&ids[3])510
);511
assert!(512
stack513
.expired(later + Duration::from_secs(6))514
.contains(&ids[3])515
);511
}516
}512
517
513
#[test]518
#[test]@@ -104,7 +104,10 @@ mod tests {
104
104
105
105
#[test]
106
106
fn direct_shows_sender_and_plain_preview() {
107
let text = describe(&model(ChatKind::Direct, Preview::Text("Hello".into())), true);
107
let text = describe(
108
&model(ChatKind::Direct, Preview::Text("Hello".into())),
109
true,
110
);
108
111
assert_eq!(text.title, "Priya Nair");
109
112
assert_eq!(text.subtitle, "Direct");
110
113
assert_eq!(text.preview, "Hello");
@@ -113,7 +116,10 @@ mod tests {
113
116
#[test]
114
117
fn group_shows_chat_title_and_prefixes_sender() {
115
118
let text = describe(
116
&model(ChatKind::Group { member_count: 5 }, Preview::Text("Hi".into())),
119
&model(
120
ChatKind::Group { member_count: 5 },
121
Preview::Text("Hi".into()),
122
),
117
123
true,
118
124
);
119
125
assert_eq!(text.title, "Retro-Team");
@@ -135,7 +141,10 @@ mod tests {
135
141
136
142
#[test]
137
143
fn preview_off_hides_content_but_keeps_name() {
138
let text = describe(&model(ChatKind::Direct, Preview::Text("geheim".into())), false);
144
let text = describe(
145
&model(ChatKind::Direct, Preview::Text("geheim".into())),
146
false,
147
);
139
148
assert_eq!(text.preview, "New message");
140
149
assert!(!text.narration().contains("geheim"));
141
150
}
@@ -150,7 +159,10 @@ mod tests {
150
159
#[test]
151
160
fn mention_ranges_cover_first_word_after_at() {
152
161
let text = "Ping @Jonas can you ask @Mara @";
153
let found: Vec<&str> = mention_ranges(text).into_iter().map(|range| &text[range]).collect();
162
let found: Vec<&str> = mention_ranges(text)
163
.into_iter()
164
.map(|range| &text[range])
165
.collect();
154
166
assert_eq!(found, ["@Jonas", "@Mara"]);
155
167
}
156
168
}
@@ -104,7 +104,10 @@ mod tests {104
104
105
#[test]105
#[test]106
fn direct_shows_sender_and_plain_preview() {106
fn direct_shows_sender_and_plain_preview() {107
let text = describe(&model(ChatKind::Direct, Preview::Text("Hello".into())), true);107
let text = describe(108
&model(ChatKind::Direct, Preview::Text("Hello".into())),109
true,110
);108
assert_eq!(text.title, "Priya Nair");111
assert_eq!(text.title, "Priya Nair");109
assert_eq!(text.subtitle, "Direct");112
assert_eq!(text.subtitle, "Direct");110
assert_eq!(text.preview, "Hello");113
assert_eq!(text.preview, "Hello");@@ -113,7 +116,10 @@ mod tests {113
#[test]116
#[test]114
fn group_shows_chat_title_and_prefixes_sender() {117
fn group_shows_chat_title_and_prefixes_sender() {115
let text = describe(118
let text = describe(116
&model(ChatKind::Group { member_count: 5 }, Preview::Text("Hi".into())),119
&model(120
ChatKind::Group { member_count: 5 },121
Preview::Text("Hi".into()),122
),117
true,123
true,118
);124
);119
assert_eq!(text.title, "Retro-Team");125
assert_eq!(text.title, "Retro-Team");@@ -135,7 +141,10 @@ mod tests {135
141
136
#[test]142
#[test]137
fn preview_off_hides_content_but_keeps_name() {143
fn preview_off_hides_content_but_keeps_name() {138
let text = describe(&model(ChatKind::Direct, Preview::Text("geheim".into())), false);144
let text = describe(145
&model(ChatKind::Direct, Preview::Text("geheim".into())),146
false,147
);139
assert_eq!(text.preview, "New message");148
assert_eq!(text.preview, "New message");140
assert!(!text.narration().contains("geheim"));149
assert!(!text.narration().contains("geheim"));141
}150
}@@ -150,7 +159,10 @@ mod tests {150
#[test]159
#[test]151
fn mention_ranges_cover_first_word_after_at() {160
fn mention_ranges_cover_first_word_after_at() {152
let text = "Ping @Jonas can you ask @Mara @";161
let text = "Ping @Jonas can you ask @Mara @";153
let found: Vec<&str> = mention_ranges(text).into_iter().map(|range| &text[range]).collect();162
let found: Vec<&str> = mention_ranges(text)163
.into_iter()164
.map(|range| &text[range])165
.collect();154
assert_eq!(found, ["@Jonas", "@Mara"]);166
assert_eq!(found, ["@Jonas", "@Mara"]);155
}167
}156
}168
}@@ -19,10 +19,10 @@ use super::rules::ChatKind;
19
19
use super::stack::{ReplyState, ToastModel};
20
20
use super::text::{ToastText, describe, mention_ranges};
21
21
use crate::sidebar_model::{AvatarSpec, Face};
22
use crate::theme;
22
23
use crate::views::avatar::{spec_avatar, with_presence};
23
24
use crate::views::composer::submitted_text;
24
25
use crate::views::widgets::symbol;
25
use crate::theme;
26
26
27
27
const CLOSE_SIZE: f32 = 24.;
28
28
const TOAST_RADIUS: f32 = 12.;
@@ -50,12 +50,16 @@ impl ToastView {
50
50
.placeholder("Reply ...")
51
51
});
52
52
let subscriptions = vec![
53
cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {
54
let value = input.read(cx).value();
55
if submitted_text(event, &value).is_some() {
56
this.submit(window, cx);
57
}
58
}),
53
cx.subscribe_in(
54
&input,
55
window,
56
|this, input, event: &InputEvent, window, cx| {
57
let value = input.read(cx).value();
58
if submitted_text(event, &value).is_some() {
59
this.submit(window, cx);
60
}
61
},
62
),
59
63
cx.observe(¢er, |_, _, cx| cx.notify()),
60
64
];
61
65
ToastView {
@@ -210,14 +214,21 @@ impl ToastView {
210
214
user_id: None,
211
215
name: model.chat_title.clone(),
212
216
};
213
spec_avatar(directory, &AvatarSpec::Pair(sender, chat), AVATAR_SIZE, fill)
217
spec_avatar(
218
directory,
219
&AvatarSpec::Pair(sender, chat),
220
AVATAR_SIZE,
221
fill,
222
)
214
223
}
215
224
_ => {
216
225
let presence = model
217
226
.sender_id
218
227
.as_deref()
219
228
.map(|user_id| directory.presence_of(user_id))
220
.unwrap_or(crate::data::Presence::Live(crate::data::PresenceKind::Unknown));
229
.unwrap_or(crate::data::Presence::Live(
230
crate::data::PresenceKind::Unknown,
231
));
221
232
let face = spec_avatar(directory, &AvatarSpec::Single(sender), AVATAR_SIZE, fill);
222
233
with_presence(face, presence, AVATAR_SIZE, fill).into_any_element()
223
234
}
@@ -390,11 +401,10 @@ impl ToastView {
390
401
theme::border_strong()
391
402
})
392
403
.child(
393
div().flex_1().min_w_0().child(
394
Textarea::new(&self.input)
395
.appearance(false)
396
.bordered(false),
397
),
404
div()
405
.flex_1()
406
.min_w_0()
407
.child(Textarea::new(&self.input).appearance(false).bordered(false)),
398
408
)
399
409
.child(send),
400
410
)
@@ -447,12 +457,14 @@ impl ToastView {
447
457
)
448
458
})
449
459
.when(!sent, |row| {
450
row.child(flat_button("Retry", "reply", true, false).on_click(cx.listener(
451
|this, _, _, cx| {
452
cx.stop_propagation();
453
this.retry(cx);
454
},
455
)))
460
row.child(
461
flat_button("Retry", "reply", true, false).on_click(cx.listener(
462
|this, _, _, cx| {
463
cx.stop_propagation();
464
this.retry(cx);
465
},
466
)),
467
)
456
468
})
457
469
}
458
470
}
@@ -548,10 +560,12 @@ impl Render for ToastView {
548
560
.on_click(move |_, _, cx| {
549
561
center.update(cx, |center, cx| center.activate(id, cx));
550
562
})
551
.capture_action(cx.listener(|this, _: &gpui_kit::component::input::Escape, window, cx| {
552
this.close_reply(window, cx);
553
cx.stop_propagation();
554
}))
563
.capture_action(cx.listener(
564
|this, _: &gpui_kit::component::input::Escape, window, cx| {
565
this.close_reply(window, cx);
566
cx.stop_propagation();
567
},
568
))
555
569
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
556
570
if event.keystroke.key == "escape" {
557
571
let id = this.id;
@@ -19,10 +19,10 @@ use super::rules::ChatKind;19
use super::stack::{ReplyState, ToastModel};19
use super::stack::{ReplyState, ToastModel};20
use super::text::{ToastText, describe, mention_ranges};20
use super::text::{ToastText, describe, mention_ranges};21
use crate::sidebar_model::{AvatarSpec, Face};21
use crate::sidebar_model::{AvatarSpec, Face};22
use crate::theme;22
use crate::views::avatar::{spec_avatar, with_presence};23
use crate::views::avatar::{spec_avatar, with_presence};23
use crate::views::composer::submitted_text;24
use crate::views::composer::submitted_text;24
use crate::views::widgets::symbol;25
use crate::views::widgets::symbol;25
use crate::theme;26
26
27
const CLOSE_SIZE: f32 = 24.;27
const CLOSE_SIZE: f32 = 24.;28
const TOAST_RADIUS: f32 = 12.;28
const TOAST_RADIUS: f32 = 12.;@@ -50,12 +50,16 @@ impl ToastView {50
.placeholder("Reply ...")50
.placeholder("Reply ...")51
});51
});52
let subscriptions = vec![52
let subscriptions = vec![53
cx.subscribe_in(&input, window, |this, input, event: &InputEvent, window, cx| {53
cx.subscribe_in(54
let value = input.read(cx).value();54
&input,55
if submitted_text(event, &value).is_some() {55
window,56
this.submit(window, cx);56
|this, input, event: &InputEvent, window, cx| {57
}57
let value = input.read(cx).value();58
}),58
if submitted_text(event, &value).is_some() {59
this.submit(window, cx);60
}61
},62
),59
cx.observe(¢er, |_, _, cx| cx.notify()),63
cx.observe(¢er, |_, _, cx| cx.notify()),60
];64
];61
ToastView {65
ToastView {@@ -210,14 +214,21 @@ impl ToastView {210
user_id: None,214
user_id: None,211
name: model.chat_title.clone(),215
name: model.chat_title.clone(),212
};216
};213
spec_avatar(directory, &AvatarSpec::Pair(sender, chat), AVATAR_SIZE, fill)217
spec_avatar(218
directory,219
&AvatarSpec::Pair(sender, chat),220
AVATAR_SIZE,221
fill,222
)214
}223
}215
_ => {224
_ => {216
let presence = model225
let presence = model217
.sender_id226
.sender_id218
.as_deref()227
.as_deref()219
.map(|user_id| directory.presence_of(user_id))228
.map(|user_id| directory.presence_of(user_id))220
.unwrap_or(crate::data::Presence::Live(crate::data::PresenceKind::Unknown));229
.unwrap_or(crate::data::Presence::Live(230
crate::data::PresenceKind::Unknown,231
));221
let face = spec_avatar(directory, &AvatarSpec::Single(sender), AVATAR_SIZE, fill);232
let face = spec_avatar(directory, &AvatarSpec::Single(sender), AVATAR_SIZE, fill);222
with_presence(face, presence, AVATAR_SIZE, fill).into_any_element()233
with_presence(face, presence, AVATAR_SIZE, fill).into_any_element()223
}234
}@@ -390,11 +401,10 @@ impl ToastView {390
theme::border_strong()401
theme::border_strong()391
})402
})392
.child(403
.child(393
div().flex_1().min_w_0().child(404
div()394
Textarea::new(&self.input)405
.flex_1()395
.appearance(false)406
.min_w_0()396
.bordered(false),407
.child(Textarea::new(&self.input).appearance(false).bordered(false)),397
),398
)408
)399
.child(send),409
.child(send),400
)410
)@@ -447,12 +457,14 @@ impl ToastView {447
)457
)448
})458
})449
.when(!sent, |row| {459
.when(!sent, |row| {450
row.child(flat_button("Retry", "reply", true, false).on_click(cx.listener(460
row.child(451
|this, _, _, cx| {461
flat_button("Retry", "reply", true, false).on_click(cx.listener(452
cx.stop_propagation();462
|this, _, _, cx| {453
this.retry(cx);463
cx.stop_propagation();454
},464
this.retry(cx);455
)))465
},466
)),467
)456
})468
})457
}469
}458
}470
}@@ -548,10 +560,12 @@ impl Render for ToastView {548
.on_click(move |_, _, cx| {560
.on_click(move |_, _, cx| {549
center.update(cx, |center, cx| center.activate(id, cx));561
center.update(cx, |center, cx| center.activate(id, cx));550
})562
})551
.capture_action(cx.listener(|this, _: &gpui_kit::component::input::Escape, window, cx| {563
.capture_action(cx.listener(552
this.close_reply(window, cx);564
|this, _: &gpui_kit::component::input::Escape, window, cx| {553
cx.stop_propagation();565
this.close_reply(window, cx);554
}))566
cx.stop_propagation();567
},568
))555
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {569
.on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {556
if event.keystroke.key == "escape" {570
if event.keystroke.key == "escape" {557
let id = this.id;571
let id = this.id;@@ -23,7 +23,11 @@ pub enum LinkSignal {
23
23
Disconnected,
24
24
}
25
25
26
pub fn report_due(down_for: Option<Duration>, since_last_report: Option<Duration>, activity_changed: bool) -> bool {
26
pub fn report_due(
27
down_for: Option<Duration>,
28
since_last_report: Option<Duration>,
29
activity_changed: bool,
30
) -> bool {
27
31
down_for.is_some_and(|down_for| down_for >= FALLBACK_AFTER)
28
32
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))
29
33
}
@@ -59,7 +63,8 @@ pub fn unregister_on_exit(timeout: Duration) {
59
63
if unregister.send(done).is_err() {
60
64
return;
61
65
}
62
let _ = crate::runtime::handle().block_on(async move { tokio::time::timeout(timeout, finished).await });
66
let _ = crate::runtime::handle()
67
.block_on(async move { tokio::time::timeout(timeout, finished).await });
63
68
}
64
69
65
70
#[derive(Default)]
@@ -106,7 +111,11 @@ struct Link<T: CardTransport> {
106
111
}
107
112
108
113
impl<T: CardTransport> Link<T> {
109
fn new(service: PresenceService<T>, activity: watch::Receiver<bool>, resend: Arc<Notify>) -> Self {
114
fn new(
115
service: PresenceService<T>,
116
activity: watch::Receiver<bool>,
117
resend: Arc<Notify>,
118
) -> Self {
110
119
Link {
111
120
service,
112
121
activity,
@@ -212,7 +221,9 @@ impl<T: CardTransport> Link<T> {
212
221
}
213
222
Err(error) => {
214
223
if let Some(message) = self.retry.failed(now, &error) {
215
crate::diagnostics::record(format!("presence: endpoint not registered: {message}"));
224
crate::diagnostics::record(format!(
225
"presence: endpoint not registered: {message}"
226
));
216
227
}
217
228
}
218
229
}
@@ -228,7 +239,11 @@ impl<T: CardTransport> Link<T> {
228
239
.register_endpoint(endpoint_id, ActivityReporting::Direct)
229
240
.await
230
241
.is_ok()
231
&& self.service.report_activity(endpoint_id, active).await.is_ok()
242
&& self
243
.service
244
.report_activity(endpoint_id, active)
245
.await
246
.is_ok()
232
247
{
233
248
return;
234
249
}
@@ -261,9 +276,16 @@ mod tests {
261
276
.as_ref()
262
277
.and_then(|body| body["activityReporting"].as_str())
263
278
.map(str::to_owned);
264
self.sent.lock().unwrap().push((request.method, request.url, reporting));
279
self.sent
280
.lock()
281
.unwrap()
282
.push((request.method, request.url, reporting));
265
283
let mut statuses = self.statuses.lock().unwrap();
266
let status = if statuses.is_empty() { 200 } else { statuses.remove(0) };
284
let status = if statuses.is_empty() {
285
200
286
} else {
287
statuses.remove(0)
288
};
267
289
Ok(ApiResponse {
268
290
status,
269
291
body: serde_json::Value::Null,
@@ -289,7 +311,11 @@ mod tests {
289
311
.iter()
290
312
.map(|(method, url, reporting)| {
291
313
let path = url.strip_prefix(PRESENCE).unwrap();
292
format!("{} {path} {}", method.as_str(), reporting.as_deref().unwrap_or("-"))
314
format!(
315
"{} {path} {}",
316
method.as_str(),
317
reporting.as_deref().unwrap_or("-")
318
)
293
319
})
294
320
.collect()
295
321
}
@@ -310,7 +336,9 @@ mod tests {
310
336
311
337
#[test]
312
338
fn retry_delay_doubles_up_to_four_minutes() {
313
let delays: Vec<u64> = (1..=6).map(|failures| retry_delay(failures).as_secs()).collect();
339
let delays: Vec<u64> = (1..=6)
340
.map(|failures| retry_delay(failures).as_secs())
341
.collect();
314
342
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);
315
343
}
316
344
@@ -357,7 +385,9 @@ mod tests {
357
385
link.apply(LinkSignal::Endpoint("a".into())).await;
358
386
link.apply(LinkSignal::Connected).await;
359
387
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);
360
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");
388
tokio::time::timeout(Duration::from_millis(500), resend.notified())
389
.await
390
.expect("resend");
361
391
}
362
392
363
393
#[tokio::test]
@@ -367,7 +397,11 @@ mod tests {
367
397
link.apply(LinkSignal::Endpoint("b".into())).await;
368
398
assert_eq!(
369
399
calls(&sent),
370
["PUT /endpoints/ Transport", "DELETE /endpoints/a -", "PUT /endpoints/ Transport"]
400
[
401
"PUT /endpoints/ Transport",
402
"DELETE /endpoints/a -",
403
"PUT /endpoints/ Transport"
404
]
371
405
);
372
406
}
373
407
@@ -375,8 +409,14 @@ mod tests {
375
409
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {
376
410
let (mut link, sent, resend) = link(vec![]);
377
411
link.apply(LinkSignal::Endpoint("a".into())).await;
378
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");
379
link.down_since = Some(Instant::now().checked_sub(seconds(130)).unwrap_or_else(Instant::now));
412
tokio::time::timeout(Duration::from_millis(500), resend.notified())
413
.await
414
.expect("resend");
415
link.down_since = Some(
416
Instant::now()
417
.checked_sub(seconds(130))
418
.unwrap_or_else(Instant::now),
419
);
380
420
link.reconcile(false).await;
381
421
link.apply(LinkSignal::Connected).await;
382
422
assert_eq!(
@@ -388,7 +428,9 @@ mod tests {
388
428
"PUT /endpoints/ Transport",
389
429
]
390
430
);
391
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");
431
tokio::time::timeout(Duration::from_millis(500), resend.notified())
432
.await
433
.expect("resend");
392
434
}
393
435
394
436
#[tokio::test]
@@ -23,7 +23,11 @@ pub enum LinkSignal {23
Disconnected,23
Disconnected,24
}24
}25
25
26
pub fn report_due(down_for: Option<Duration>, since_last_report: Option<Duration>, activity_changed: bool) -> bool {26
pub fn report_due(27
down_for: Option<Duration>,28
since_last_report: Option<Duration>,29
activity_changed: bool,30
) -> bool {27
down_for.is_some_and(|down_for| down_for >= FALLBACK_AFTER)31
down_for.is_some_and(|down_for| down_for >= FALLBACK_AFTER)28
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))32
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))29
}33
}@@ -59,7 +63,8 @@ pub fn unregister_on_exit(timeout: Duration) {59
if unregister.send(done).is_err() {63
if unregister.send(done).is_err() {60
return;64
return;61
}65
}62
let _ = crate::runtime::handle().block_on(async move { tokio::time::timeout(timeout, finished).await });66
let _ = crate::runtime::handle()67
.block_on(async move { tokio::time::timeout(timeout, finished).await });63
}68
}64
69
65
#[derive(Default)]70
#[derive(Default)]@@ -106,7 +111,11 @@ struct Link<T: CardTransport> {106
}111
}107
112
108
impl<T: CardTransport> Link<T> {113
impl<T: CardTransport> Link<T> {109
fn new(service: PresenceService<T>, activity: watch::Receiver<bool>, resend: Arc<Notify>) -> Self {114
fn new(115
service: PresenceService<T>,116
activity: watch::Receiver<bool>,117
resend: Arc<Notify>,118
) -> Self {110
Link {119
Link {111
service,120
service,112
activity,121
activity,@@ -212,7 +221,9 @@ impl<T: CardTransport> Link<T> {212
}221
}213
Err(error) => {222
Err(error) => {214
if let Some(message) = self.retry.failed(now, &error) {223
if let Some(message) = self.retry.failed(now, &error) {215
crate::diagnostics::record(format!("presence: endpoint not registered: {message}"));224
crate::diagnostics::record(format!(225
"presence: endpoint not registered: {message}"226
));216
}227
}217
}228
}218
}229
}@@ -228,7 +239,11 @@ impl<T: CardTransport> Link<T> {228
.register_endpoint(endpoint_id, ActivityReporting::Direct)239
.register_endpoint(endpoint_id, ActivityReporting::Direct)229
.await240
.await230
.is_ok()241
.is_ok()231
&& self.service.report_activity(endpoint_id, active).await.is_ok()242
&& self243
.service244
.report_activity(endpoint_id, active)245
.await246
.is_ok()232
{247
{233
return;248
return;234
}249
}@@ -261,9 +276,16 @@ mod tests {261
.as_ref()276
.as_ref()262
.and_then(|body| body["activityReporting"].as_str())277
.and_then(|body| body["activityReporting"].as_str())263
.map(str::to_owned);278
.map(str::to_owned);264
self.sent.lock().unwrap().push((request.method, request.url, reporting));279
self.sent280
.lock()281
.unwrap()282
.push((request.method, request.url, reporting));265
let mut statuses = self.statuses.lock().unwrap();283
let mut statuses = self.statuses.lock().unwrap();266
let status = if statuses.is_empty() { 200 } else { statuses.remove(0) };284
let status = if statuses.is_empty() {285
200286
} else {287
statuses.remove(0)288
};267
Ok(ApiResponse {289
Ok(ApiResponse {268
status,290
status,269
body: serde_json::Value::Null,291
body: serde_json::Value::Null,@@ -289,7 +311,11 @@ mod tests {289
.iter()311
.iter()290
.map(|(method, url, reporting)| {312
.map(|(method, url, reporting)| {291
let path = url.strip_prefix(PRESENCE).unwrap();313
let path = url.strip_prefix(PRESENCE).unwrap();292
format!("{} {path} {}", method.as_str(), reporting.as_deref().unwrap_or("-"))314
format!(315
"{} {path} {}",316
method.as_str(),317
reporting.as_deref().unwrap_or("-")318
)293
})319
})294
.collect()320
.collect()295
}321
}@@ -310,7 +336,9 @@ mod tests {310
336
311
#[test]337
#[test]312
fn retry_delay_doubles_up_to_four_minutes() {338
fn retry_delay_doubles_up_to_four_minutes() {313
let delays: Vec<u64> = (1..=6).map(|failures| retry_delay(failures).as_secs()).collect();339
let delays: Vec<u64> = (1..=6)340
.map(|failures| retry_delay(failures).as_secs())341
.collect();314
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);342
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);315
}343
}316
344
@@ -357,7 +385,9 @@ mod tests {357
link.apply(LinkSignal::Endpoint("a".into())).await;385
link.apply(LinkSignal::Endpoint("a".into())).await;358
link.apply(LinkSignal::Connected).await;386
link.apply(LinkSignal::Connected).await;359
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);387
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);360
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");388
tokio::time::timeout(Duration::from_millis(500), resend.notified())389
.await390
.expect("resend");361
}391
}362
392
363
#[tokio::test]393
#[tokio::test]@@ -367,7 +397,11 @@ mod tests {367
link.apply(LinkSignal::Endpoint("b".into())).await;397
link.apply(LinkSignal::Endpoint("b".into())).await;368
assert_eq!(398
assert_eq!(369
calls(&sent),399
calls(&sent),370
["PUT /endpoints/ Transport", "DELETE /endpoints/a -", "PUT /endpoints/ Transport"]400
[401
"PUT /endpoints/ Transport",402
"DELETE /endpoints/a -",403
"PUT /endpoints/ Transport"404
]371
);405
);372
}406
}373
407
@@ -375,8 +409,14 @@ mod tests {375
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {409
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {376
let (mut link, sent, resend) = link(vec![]);410
let (mut link, sent, resend) = link(vec![]);377
link.apply(LinkSignal::Endpoint("a".into())).await;411
link.apply(LinkSignal::Endpoint("a".into())).await;378
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");412
tokio::time::timeout(Duration::from_millis(500), resend.notified())379
link.down_since = Some(Instant::now().checked_sub(seconds(130)).unwrap_or_else(Instant::now));413
.await414
.expect("resend");415
link.down_since = Some(416
Instant::now()417
.checked_sub(seconds(130))418
.unwrap_or_else(Instant::now),419
);380
link.reconcile(false).await;420
link.reconcile(false).await;381
link.apply(LinkSignal::Connected).await;421
link.apply(LinkSignal::Connected).await;382
assert_eq!(422
assert_eq!(@@ -388,7 +428,9 @@ mod tests {388
"PUT /endpoints/ Transport",428
"PUT /endpoints/ Transport",389
]429
]390
);430
);391
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");431
tokio::time::timeout(Duration::from_millis(500), resend.notified())432
.await433
.expect("resend");392
}434
}393
435
394
#[tokio::test]436
#[tokio::test]@@ -10,11 +10,7 @@ pub struct ReadPlan {
10
10
pub clear_divider: bool,
11
11
}
12
12
13
pub fn plan_read(
14
window_active: bool,
15
chat_unread: bool,
16
trigger: ReadTrigger,
17
) -> Option<ReadPlan> {
13
pub fn plan_read(window_active: bool, chat_unread: bool, trigger: ReadTrigger) -> Option<ReadPlan> {
18
14
if !window_active || !chat_unread {
19
15
return None;
20
16
}
@@ -10,11 +10,7 @@ pub struct ReadPlan {10
pub clear_divider: bool,10
pub clear_divider: bool,11
}11
}12
12
13
pub fn plan_read(13
pub fn plan_read(window_active: bool, chat_unread: bool, trigger: ReadTrigger) -> Option<ReadPlan> {14
window_active: bool,15
chat_unread: bool,16
trigger: ReadTrigger,17
) -> Option<ReadPlan> {18
if !window_active || !chat_unread {14
if !window_active || !chat_unread {19
return None;15
return None;20
}16
}@@ -6,8 +6,8 @@ use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun,
6
6
use gpui_kit::*;
7
7
8
8
use super::blocks::CODE_PADDING;
9
use crate::views::profile_card::open_profile_link;
10
9
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};
10
use crate::views::profile_card::open_profile_link;
11
11
12
12
const WRAP_TOLERANCE: f32 = 0.5;
13
13
@@ -6,8 +6,8 @@ use gpui_kit::base::{TextSelection, TextSelectionRegistration, TextSelectionRun,6
use gpui_kit::*;6
use gpui_kit::*;7
7
8
use super::blocks::CODE_PADDING;8
use super::blocks::CODE_PADDING;9
use crate::views::profile_card::open_profile_link;10
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};9
use super::selectable::{HIT_SLOP, PILL_INSET_Y, PILL_OUTSET, Participant, Pill, TIME_ROOM};10
use crate::views::profile_card::open_profile_link;11
11
12
const WRAP_TOLERANCE: f32 = 0.5;12
const WRAP_TOLERANCE: f32 = 0.5;13
13
@@ -976,7 +976,10 @@ mod tests {
976
976
row.translation,
977
977
Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"
978
978
));
979
assert_eq!(row.blocks, layout_blocks(&linked_message_spans(&record("a", None, 8, 6))));
979
assert_eq!(
980
row.blocks,
981
layout_blocks(&linked_message_spans(&record("a", None, 8, 6)))
982
);
980
983
}
981
984
982
985
#[test]
@@ -1008,7 +1011,10 @@ mod tests {
1008
1011
fn own_messages_get_no_offer() {
1009
1012
let mut own = record("a", None, 8, 6);
1010
1013
own.sender_id = Some("me".into());
1011
assert_eq!(message_row(&own, &translation_context(false)).translation, None);
1014
assert_eq!(
1015
message_row(&own, &translation_context(false)).translation,
1016
None
1017
);
1012
1018
}
1013
1019
1014
1020
#[test]
@@ -976,7 +976,10 @@ mod tests {976
row.translation,976
row.translation,977
Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"977
Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"978
));978
));979
assert_eq!(row.blocks, layout_blocks(&linked_message_spans(&record("a", None, 8, 6))));979
assert_eq!(980
row.blocks,981
layout_blocks(&linked_message_spans(&record("a", None, 8, 6)))982
);980
}983
}981
984
982
#[test]985
#[test]@@ -1008,7 +1011,10 @@ mod tests {1008
fn own_messages_get_no_offer() {1011
fn own_messages_get_no_offer() {1009
let mut own = record("a", None, 8, 6);1012
let mut own = record("a", None, 8, 6);1010
own.sender_id = Some("me".into());1013
own.sender_id = Some("me".into());1011
assert_eq!(message_row(&own, &translation_context(false)).translation, None);1014
assert_eq!(1015
message_row(&own, &translation_context(false)).translation,1016
None1017
);1012
}1018
}1013
1019
1014
#[test]1020
#[test]@@ -400,28 +400,33 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {
400
400
.teams
401
401
.iter()
402
402
.any(|entry| entry.hidden && holds_selection(entry));
403
let teams = input
404
.teams
405
.iter()
406
.filter(|entry| !entry.hidden)
407
.chain(
408
input
409
.teams
410
.iter()
411
.filter(|entry| entry.hidden && hidden_teams_shown),
412
);
403
let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(
404
input
405
.teams
406
.iter()
407
.filter(|entry| entry.hidden && hidden_teams_shown),
408
);
413
409
for entry in teams {
414
410
if input.collapsed_teams.contains(&entry.team.id) {
415
411
continue;
416
412
}
417
413
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);
418
let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
414
let is_selected =
415
|channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;
419
416
let revealed = input.revealed_channel_teams.contains(&entry.team.id);
420
for channel in entry.channels.iter().filter(|channel| !is_hidden(channel) || is_selected(channel)) {
417
for channel in entry
418
.channels
419
.iter()
420
.filter(|channel| !is_hidden(channel) || is_selected(channel))
421
{
421
422
push(&channel.id);
422
423
}
423
424
if revealed {
424
for channel in entry.channels.iter().filter(|channel| is_hidden(channel) && !is_selected(channel)) {
425
for channel in entry
426
.channels
427
.iter()
428
.filter(|channel| is_hidden(channel) && !is_selected(channel))
429
{
425
430
push(&channel.id);
426
431
}
427
432
}
@@ -604,11 +609,17 @@ mod tests {
604
609
fn stepping_follows_the_visible_order_without_wrapping() {
605
610
let ids = ["a", "b", "c"];
606
611
assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));
607
assert_eq!(step_id(&ids, Some("b"), Step::Previous), Some("a".to_owned()));
612
assert_eq!(
613
step_id(&ids, Some("b"), Step::Previous),
614
Some("a".to_owned())
615
);
608
616
assert_eq!(step_id(&ids, Some("c"), Step::Next), None);
609
617
assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);
610
618
assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));
611
assert_eq!(step_id(&ids, Some("gone"), Step::Previous), Some("c".to_owned()));
619
assert_eq!(
620
step_id(&ids, Some("gone"), Step::Previous),
621
Some("c".to_owned())
622
);
612
623
assert_eq!(step_id(&[], None, Step::Next), None);
613
624
}
614
625
@@ -638,7 +649,12 @@ mod tests {
638
649
assert_eq!(visible_chat_ids(§ions), vec!["fav", "other"]);
639
650
}
640
651
641
fn team(id: &str, hidden: bool, channel_ids: &[&str], hidden_channel_ids: &[&str]) -> SidebarTeam {
652
fn team(
653
id: &str,
654
hidden: bool,
655
channel_ids: &[&str],
656
hidden_channel_ids: &[&str],
657
) -> SidebarTeam {
642
658
SidebarTeam {
643
659
team: store::TeamRecord {
644
660
id: id.into(),
@@ -656,7 +672,10 @@ mod tests {
656
672
})
657
673
.collect(),
658
674
hidden,
659
hidden_channel_ids: hidden_channel_ids.iter().map(|id| (*id).to_owned()).collect(),
675
hidden_channel_ids: hidden_channel_ids
676
.iter()
677
.map(|id| (*id).to_owned())
678
.collect(),
660
679
notifications: HashMap::new(),
661
680
}
662
681
}
@@ -673,7 +692,11 @@ mod tests {
673
692
hidden_teams_open: bool,
674
693
collapsed: &[&str],
675
694
revealed: &[&str]| {
676
let to_set = |ids: &[&str]| ids.iter().map(|id| (*id).to_owned()).collect::<HashSet<_>>();
695
let to_set = |ids: &[&str]| {
696
ids.iter()
697
.map(|id| (*id).to_owned())
698
.collect::<HashSet<_>>()
699
};
677
700
let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));
678
701
let input = ChannelOrderInput {
679
702
teams: &teams,
@@ -683,13 +706,25 @@ mod tests {
683
706
hidden_teams_open,
684
707
selected_channel: selected,
685
708
};
686
visible_channel_ids(&input).into_iter().map(str::to_owned).collect::<Vec<_>>()
709
visible_channel_ids(&input)
710
.into_iter()
711
.map(str::to_owned)
712
.collect::<Vec<_>>()
687
713
};
688
714
assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);
689
assert_eq!(order(Some("b"), false, &[], &[]), vec!["e", "a", "b", "c", "d"]);
690
assert_eq!(order(Some("f"), false, &[], &[]), vec!["e", "a", "c", "d", "f"]);
715
assert_eq!(
716
order(Some("b"), false, &[], &[]),
717
vec!["e", "a", "b", "c", "d"]
718
);
719
assert_eq!(
720
order(Some("f"), false, &[], &[]),
721
vec!["e", "a", "c", "d", "f"]
722
);
691
723
assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);
692
assert_eq!(order(None, true, &["t2"], &["t1"]), vec!["e", "a", "c", "b", "f"]);
724
assert_eq!(
725
order(None, true, &["t2"], &["t1"]),
726
vec!["e", "a", "c", "b", "f"]
727
);
693
728
}
694
729
695
730
#[test]
@@ -400,28 +400,33 @@ pub fn visible_channel_ids<'a>(input: &ChannelOrderInput<'a>) -> Vec<&'a str> {400
.teams400
.teams401
.iter()401
.iter()402
.any(|entry| entry.hidden && holds_selection(entry));402
.any(|entry| entry.hidden && holds_selection(entry));403
let teams = input403
let teams = input.teams.iter().filter(|entry| !entry.hidden).chain(404
.teams404
input405
.iter()405
.teams406
.filter(|entry| !entry.hidden)406
.iter()407
.chain(407
.filter(|entry| entry.hidden && hidden_teams_shown),408
input408
);409
.teams410
.iter()411
.filter(|entry| entry.hidden && hidden_teams_shown),412
);413
for entry in teams {409
for entry in teams {414
if input.collapsed_teams.contains(&entry.team.id) {410
if input.collapsed_teams.contains(&entry.team.id) {415
continue;411
continue;416
}412
}417
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);413
let is_hidden = |channel: &ChannelRecord| entry.hidden_channel_ids.contains(&channel.id);418
let is_selected = |channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;414
let is_selected =415
|channel: &ChannelRecord| Some(channel.id.as_str()) == input.selected_channel;419
let revealed = input.revealed_channel_teams.contains(&entry.team.id);416
let revealed = input.revealed_channel_teams.contains(&entry.team.id);420
for channel in entry.channels.iter().filter(|channel| !is_hidden(channel) || is_selected(channel)) {417
for channel in entry418
.channels419
.iter()420
.filter(|channel| !is_hidden(channel) || is_selected(channel))421
{421
push(&channel.id);422
push(&channel.id);422
}423
}423
if revealed {424
if revealed {424
for channel in entry.channels.iter().filter(|channel| is_hidden(channel) && !is_selected(channel)) {425
for channel in entry426
.channels427
.iter()428
.filter(|channel| is_hidden(channel) && !is_selected(channel))429
{425
push(&channel.id);430
push(&channel.id);426
}431
}427
}432
}@@ -604,11 +609,17 @@ mod tests {604
fn stepping_follows_the_visible_order_without_wrapping() {609
fn stepping_follows_the_visible_order_without_wrapping() {605
let ids = ["a", "b", "c"];610
let ids = ["a", "b", "c"];606
assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));611
assert_eq!(step_id(&ids, Some("a"), Step::Next), Some("b".to_owned()));607
assert_eq!(step_id(&ids, Some("b"), Step::Previous), Some("a".to_owned()));612
assert_eq!(613
step_id(&ids, Some("b"), Step::Previous),614
Some("a".to_owned())615
);608
assert_eq!(step_id(&ids, Some("c"), Step::Next), None);616
assert_eq!(step_id(&ids, Some("c"), Step::Next), None);609
assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);617
assert_eq!(step_id(&ids, Some("a"), Step::Previous), None);610
assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));618
assert_eq!(step_id(&ids, None, Step::Next), Some("a".to_owned()));611
assert_eq!(step_id(&ids, Some("gone"), Step::Previous), Some("c".to_owned()));619
assert_eq!(620
step_id(&ids, Some("gone"), Step::Previous),621
Some("c".to_owned())622
);612
assert_eq!(step_id(&[], None, Step::Next), None);623
assert_eq!(step_id(&[], None, Step::Next), None);613
}624
}614
625
@@ -638,7 +649,12 @@ mod tests {638
assert_eq!(visible_chat_ids(§ions), vec!["fav", "other"]);649
assert_eq!(visible_chat_ids(§ions), vec!["fav", "other"]);639
}650
}640
651
641
fn team(id: &str, hidden: bool, channel_ids: &[&str], hidden_channel_ids: &[&str]) -> SidebarTeam {652
fn team(653
id: &str,654
hidden: bool,655
channel_ids: &[&str],656
hidden_channel_ids: &[&str],657
) -> SidebarTeam {642
SidebarTeam {658
SidebarTeam {643
team: store::TeamRecord {659
team: store::TeamRecord {644
id: id.into(),660
id: id.into(),@@ -656,7 +672,10 @@ mod tests {656
})672
})657
.collect(),673
.collect(),658
hidden,674
hidden,659
hidden_channel_ids: hidden_channel_ids.iter().map(|id| (*id).to_owned()).collect(),675
hidden_channel_ids: hidden_channel_ids676
.iter()677
.map(|id| (*id).to_owned())678
.collect(),660
notifications: HashMap::new(),679
notifications: HashMap::new(),661
}680
}662
}681
}@@ -673,7 +692,11 @@ mod tests {673
hidden_teams_open: bool,692
hidden_teams_open: bool,674
collapsed: &[&str],693
collapsed: &[&str],675
revealed: &[&str]| {694
revealed: &[&str]| {676
let to_set = |ids: &[&str]| ids.iter().map(|id| (*id).to_owned()).collect::<HashSet<_>>();695
let to_set = |ids: &[&str]| {696
ids.iter()697
.map(|id| (*id).to_owned())698
.collect::<HashSet<_>>()699
};677
let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));700
let (collapsed, revealed) = (to_set(collapsed), to_set(revealed));678
let input = ChannelOrderInput {701
let input = ChannelOrderInput {679
teams: &teams,702
teams: &teams,@@ -683,13 +706,25 @@ mod tests {683
hidden_teams_open,706
hidden_teams_open,684
selected_channel: selected,707
selected_channel: selected,685
};708
};686
visible_channel_ids(&input).into_iter().map(str::to_owned).collect::<Vec<_>>()709
visible_channel_ids(&input)710
.into_iter()711
.map(str::to_owned)712
.collect::<Vec<_>>()687
};713
};688
assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);714
assert_eq!(order(None, false, &[], &[]), vec!["e", "a", "c", "d"]);689
assert_eq!(order(Some("b"), false, &[], &[]), vec!["e", "a", "b", "c", "d"]);715
assert_eq!(690
assert_eq!(order(Some("f"), false, &[], &[]), vec!["e", "a", "c", "d", "f"]);716
order(Some("b"), false, &[], &[]),717
vec!["e", "a", "b", "c", "d"]718
);719
assert_eq!(720
order(Some("f"), false, &[], &[]),721
vec!["e", "a", "c", "d", "f"]722
);691
assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);723
assert_eq!(order(None, true, &[], &[]), vec!["e", "a", "c", "d", "f"]);692
assert_eq!(order(None, true, &["t2"], &["t1"]), vec!["e", "a", "c", "b", "f"]);724
assert_eq!(725
order(None, true, &["t2"], &["t1"]),726
vec!["e", "a", "c", "b", "f"]727
);693
}728
}694
729
695
#[test]730
#[test]@@ -2,7 +2,10 @@ use std::sync::Arc;
2
2
use std::sync::atomic::{AtomicU64, Ordering};
3
3
use std::time::{Duration, Instant};
4
4
5
use gpui_kit::{DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};
5
use gpui_kit::{
6
DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent,
7
canvas,
8
};
6
9
use tokio::sync::watch;
7
10
8
11
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
@@ -68,7 +71,11 @@ pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {
68
71
)
69
72
}
70
73
71
pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {
74
pub fn latest_input(
75
app_input: Option<Instant>,
76
system_idle: Option<Duration>,
77
now: Instant,
78
) -> Option<Instant> {
72
79
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));
73
80
app_input.max(system_input)
74
81
}
@@ -77,7 +84,12 @@ pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration
77
84
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)
78
85
}
79
86
80
pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {
87
pub fn activity_change(
88
previous: bool,
89
last_input: Option<Instant>,
90
now: Instant,
91
idle_after: Duration,
92
) -> Option<bool> {
81
93
let current = is_active(last_input, now, idle_after);
82
94
(current != previous).then_some(current)
83
95
}
@@ -130,15 +142,30 @@ mod tests {
130
142
#[test]
131
143
fn active_until_the_idle_threshold() {
132
144
let last_input = Instant::now();
133
assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));
134
assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));
135
assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));
145
assert!(is_active(
146
Some(last_input),
147
last_input + seconds(299),
148
IDLE_AFTER
149
));
150
assert!(!is_active(
151
Some(last_input),
152
last_input + seconds(300),
153
IDLE_AFTER
154
));
155
assert!(is_active(
156
Some(last_input + seconds(10)),
157
last_input,
158
IDLE_AFTER
159
));
136
160
}
137
161
138
162
#[test]
139
163
fn without_any_input_the_user_is_inactive() {
140
164
assert!(!is_active(None, Instant::now(), IDLE_AFTER));
141
assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);
165
assert_eq!(
166
activity_change(false, None, Instant::now(), IDLE_AFTER),
167
None
168
);
142
169
}
143
170
144
171
#[test]
@@ -146,20 +173,38 @@ mod tests {
146
173
let last_input = Some(Instant::now());
147
174
let at = |offset: u64| last_input.unwrap() + seconds(offset);
148
175
assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);
149
assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));
150
assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);
151
assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));
152
assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));
176
assert_eq!(
177
activity_change(true, last_input, at(301), IDLE_AFTER),
178
Some(false)
179
);
180
assert_eq!(
181
activity_change(false, last_input, at(301), IDLE_AFTER),
182
None
183
);
184
assert_eq!(
185
activity_change(false, Some(at(400)), at(401), IDLE_AFTER),
186
Some(true)
187
);
188
assert_eq!(
189
activity_change(false, last_input, at(10), IDLE_AFTER),
190
Some(true)
191
);
153
192
}
154
193
155
194
#[test]
156
195
fn system_input_counts_when_newer_than_app_input() {
157
196
let now = Instant::now() + seconds(1000);
158
197
let app_input = Some(now - seconds(900));
159
assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));
198
assert_eq!(
199
latest_input(app_input, Some(seconds(20)), now),
200
Some(now - seconds(20))
201
);
160
202
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
161
203
assert_eq!(latest_input(app_input, None, now), app_input);
162
assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));
204
assert_eq!(
205
latest_input(None, Some(seconds(20)), now),
206
Some(now - seconds(20))
207
);
163
208
assert_eq!(latest_input(None, None, now), None);
164
209
}
165
210
@@ -2,7 +2,10 @@ use std::sync::Arc;2
use std::sync::atomic::{AtomicU64, Ordering};2
use std::sync::atomic::{AtomicU64, Ordering};3
use std::time::{Duration, Instant};3
use std::time::{Duration, Instant};4
4
5
use gpui_kit::{DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};5
use gpui_kit::{6
DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent,7
canvas,8
};6
use tokio::sync::watch;9
use tokio::sync::watch;7
10
8
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);11
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);@@ -68,7 +71,11 @@ pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {68
)71
)69
}72
}70
73
71
pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {74
pub fn latest_input(75
app_input: Option<Instant>,76
system_idle: Option<Duration>,77
now: Instant,78
) -> Option<Instant> {72
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));79
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));73
app_input.max(system_input)80
app_input.max(system_input)74
}81
}@@ -77,7 +84,12 @@ pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration77
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)84
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)78
}85
}79
86
80
pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {87
pub fn activity_change(88
previous: bool,89
last_input: Option<Instant>,90
now: Instant,91
idle_after: Duration,92
) -> Option<bool> {81
let current = is_active(last_input, now, idle_after);93
let current = is_active(last_input, now, idle_after);82
(current != previous).then_some(current)94
(current != previous).then_some(current)83
}95
}@@ -130,15 +142,30 @@ mod tests {130
#[test]142
#[test]131
fn active_until_the_idle_threshold() {143
fn active_until_the_idle_threshold() {132
let last_input = Instant::now();144
let last_input = Instant::now();133
assert!(is_active(Some(last_input), last_input + seconds(299), IDLE_AFTER));145
assert!(is_active(134
assert!(!is_active(Some(last_input), last_input + seconds(300), IDLE_AFTER));146
Some(last_input),135
assert!(is_active(Some(last_input + seconds(10)), last_input, IDLE_AFTER));147
last_input + seconds(299),148
IDLE_AFTER149
));150
assert!(!is_active(151
Some(last_input),152
last_input + seconds(300),153
IDLE_AFTER154
));155
assert!(is_active(156
Some(last_input + seconds(10)),157
last_input,158
IDLE_AFTER159
));136
}160
}137
161
138
#[test]162
#[test]139
fn without_any_input_the_user_is_inactive() {163
fn without_any_input_the_user_is_inactive() {140
assert!(!is_active(None, Instant::now(), IDLE_AFTER));164
assert!(!is_active(None, Instant::now(), IDLE_AFTER));141
assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);165
assert_eq!(166
activity_change(false, None, Instant::now(), IDLE_AFTER),167
None168
);142
}169
}143
170
144
#[test]171
#[test]@@ -146,20 +173,38 @@ mod tests {146
let last_input = Some(Instant::now());173
let last_input = Some(Instant::now());147
let at = |offset: u64| last_input.unwrap() + seconds(offset);174
let at = |offset: u64| last_input.unwrap() + seconds(offset);148
assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);175
assert_eq!(activity_change(true, last_input, at(10), IDLE_AFTER), None);149
assert_eq!(activity_change(true, last_input, at(301), IDLE_AFTER), Some(false));176
assert_eq!(150
assert_eq!(activity_change(false, last_input, at(301), IDLE_AFTER), None);177
activity_change(true, last_input, at(301), IDLE_AFTER),151
assert_eq!(activity_change(false, Some(at(400)), at(401), IDLE_AFTER), Some(true));178
Some(false)152
assert_eq!(activity_change(false, last_input, at(10), IDLE_AFTER), Some(true));179
);180
assert_eq!(181
activity_change(false, last_input, at(301), IDLE_AFTER),182
None183
);184
assert_eq!(185
activity_change(false, Some(at(400)), at(401), IDLE_AFTER),186
Some(true)187
);188
assert_eq!(189
activity_change(false, last_input, at(10), IDLE_AFTER),190
Some(true)191
);153
}192
}154
193
155
#[test]194
#[test]156
fn system_input_counts_when_newer_than_app_input() {195
fn system_input_counts_when_newer_than_app_input() {157
let now = Instant::now() + seconds(1000);196
let now = Instant::now() + seconds(1000);158
let app_input = Some(now - seconds(900));197
let app_input = Some(now - seconds(900));159
assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));198
assert_eq!(199
latest_input(app_input, Some(seconds(20)), now),200
Some(now - seconds(20))201
);160
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);202
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);161
assert_eq!(latest_input(app_input, None, now), app_input);203
assert_eq!(latest_input(app_input, None, now), app_input);162
assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));204
assert_eq!(205
latest_input(None, Some(seconds(20)), now),206
Some(now - seconds(20))207
);163
assert_eq!(latest_input(None, None, now), None);208
assert_eq!(latest_input(None, None, now), None);164
}209
}165
210
@@ -165,13 +165,7 @@ impl ActivityPanel {
165
165
})),
166
166
),
167
167
)
168
.child(
169
h_flex()
170
.px(px(16.))
171
.pb(px(12.))
172
.gap(px(6.))
173
.children(pills),
174
)
168
.child(h_flex().px(px(16.)).pb(px(12.)).gap(px(6.)).children(pills))
175
169
}
176
170
177
171
fn row(
@@ -442,20 +436,16 @@ impl Render for ActivityPanel {
442
436
.into_any_element(),
443
437
);
444
438
}
445
v_flex()
446
.flex_1()
447
.min_h_0()
448
.child(self.header(cx))
449
.child(
450
v_flex()
451
.id("activity-list")
452
.flex_1()
453
.min_h_0()
454
.pb(px(12.))
455
.overflow_y_scroll()
456
.track_scroll(&self.scroll)
457
.children(rows),
458
)
439
v_flex().flex_1().min_h_0().child(self.header(cx)).child(
440
v_flex()
441
.id("activity-list")
442
.flex_1()
443
.min_h_0()
444
.pb(px(12.))
445
.overflow_y_scroll()
446
.track_scroll(&self.scroll)
447
.children(rows),
448
)
459
449
}
460
450
}
461
451
@@ -165,13 +165,7 @@ impl ActivityPanel {165
})),165
})),166
),166
),167
)167
)168
.child(168
.child(h_flex().px(px(16.)).pb(px(12.)).gap(px(6.)).children(pills))169
h_flex()170
.px(px(16.))171
.pb(px(12.))172
.gap(px(6.))173
.children(pills),174
)175
}169
}176
170
177
fn row(171
fn row(@@ -442,20 +436,16 @@ impl Render for ActivityPanel {442
.into_any_element(),436
.into_any_element(),443
);437
);444
}438
}445
v_flex()439
v_flex().flex_1().min_h_0().child(self.header(cx)).child(446
.flex_1()440
v_flex()447
.min_h_0()441
.id("activity-list")448
.child(self.header(cx))442
.flex_1()449
.child(443
.min_h_0()450
v_flex()444
.pb(px(12.))451
.id("activity-list")445
.overflow_y_scroll()452
.flex_1()446
.track_scroll(&self.scroll)453
.min_h_0()447
.children(rows),454
.pb(px(12.))448
)455
.overflow_y_scroll()456
.track_scroll(&self.scroll)457
.children(rows),458
)459
}449
}460
}450
}461
451
@@ -301,15 +301,11 @@ impl AttachmentTray {
301
301
302
302
pub fn image(&self, id: u64) -> Option<PreviewImage> {
303
303
self.items.iter().find_map(|item| match &item.kind {
304
ItemKind::Image { image, dimensions } if item.id == id => {
305
Some(PreviewImage::Inline {
306
image: image.clone(),
307
dimensions: *dimensions,
308
})
309
}
310
ItemKind::Remote(remote) if item.id == id => {
311
Some(PreviewImage::Remote(remote.clone()))
312
}
304
ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage::Inline {
305
image: image.clone(),
306
dimensions: *dimensions,
307
}),
308
ItemKind::Remote(remote) if item.id == id => Some(PreviewImage::Remote(remote.clone())),
313
309
_ => None,
314
310
})
315
311
}
@@ -509,10 +505,8 @@ impl AttachmentTray {
509
505
510
506
pub fn keep_images_only(&mut self) -> Vec<UploadedFile> {
511
507
self.notice = None;
512
let (images, others): (Vec<_>, Vec<_>) = self
513
.items
514
.drain(..)
515
.partition(|item| item.kind.is_object());
508
let (images, others): (Vec<_>, Vec<_>) =
509
self.items.drain(..).partition(|item| item.kind.is_object());
516
510
self.items = images;
517
511
others
518
512
.into_iter()
@@ -301,15 +301,11 @@ impl AttachmentTray {301
301
302
pub fn image(&self, id: u64) -> Option<PreviewImage> {302
pub fn image(&self, id: u64) -> Option<PreviewImage> {303
self.items.iter().find_map(|item| match &item.kind {303
self.items.iter().find_map(|item| match &item.kind {304
ItemKind::Image { image, dimensions } if item.id == id => {304
ItemKind::Image { image, dimensions } if item.id == id => Some(PreviewImage::Inline {305
Some(PreviewImage::Inline {305
image: image.clone(),306
image: image.clone(),306
dimensions: *dimensions,307
dimensions: *dimensions,307
}),308
})308
ItemKind::Remote(remote) if item.id == id => Some(PreviewImage::Remote(remote.clone())),309
}310
ItemKind::Remote(remote) if item.id == id => {311
Some(PreviewImage::Remote(remote.clone()))312
}313
_ => None,309
_ => None,314
})310
})315
}311
}@@ -509,10 +505,8 @@ impl AttachmentTray {509
505
510
pub fn keep_images_only(&mut self) -> Vec<UploadedFile> {506
pub fn keep_images_only(&mut self) -> Vec<UploadedFile> {511
self.notice = None;507
self.notice = None;512
let (images, others): (Vec<_>, Vec<_>) = self508
let (images, others): (Vec<_>, Vec<_>) =513
.items509
self.items.drain(..).partition(|item| item.kind.is_object());514
.drain(..)515
.partition(|item| item.kind.is_object());516
self.items = images;510
self.items = images;517
others511
others518
.into_iter()512
.into_iter()@@ -46,9 +46,7 @@ fn fit_image_within(size: Option<(u32, u32)>, max_height: f32) -> (f32, f32) {
46
46
return IMAGE_FALLBACK;
47
47
};
48
48
let (width, height) = (width as f32, height as f32);
49
let scale = (IMAGE_MAX_WIDTH / width)
50
.min(max_height / height)
51
.min(1.);
49
let scale = (IMAGE_MAX_WIDTH / width).min(max_height / height).min(1.);
52
50
(
53
51
(width * scale).max(IMAGE_MIN_SIDE).round(),
54
52
(height * scale).max(IMAGE_MIN_SIDE).round(),
@@ -403,11 +401,9 @@ pub fn attachments_view(
403
401
v_flex()
404
402
.gap(px(6.))
405
403
.items_start()
406
.children(
407
unplaced_images.into_iter().map(|(index, image)| {
408
image_view(image, format!("{id}-image-{index}"), directory, open_image)
409
}),
410
)
404
.children(unplaced_images.into_iter().map(|(index, image)| {
405
image_view(image, format!("{id}-image-{index}"), directory, open_image)
406
}))
411
407
.children(
412
408
unplaced_local.into_iter().map(|(index, image)| {
413
409
local_image_view(image, format!("{id}-local-image-{index}"))
@@ -46,9 +46,7 @@ fn fit_image_within(size: Option<(u32, u32)>, max_height: f32) -> (f32, f32) {46
return IMAGE_FALLBACK;46
return IMAGE_FALLBACK;47
};47
};48
let (width, height) = (width as f32, height as f32);48
let (width, height) = (width as f32, height as f32);49
let scale = (IMAGE_MAX_WIDTH / width)49
let scale = (IMAGE_MAX_WIDTH / width).min(max_height / height).min(1.);50
.min(max_height / height)51
.min(1.);52
(50
(53
(width * scale).max(IMAGE_MIN_SIDE).round(),51
(width * scale).max(IMAGE_MIN_SIDE).round(),54
(height * scale).max(IMAGE_MIN_SIDE).round(),52
(height * scale).max(IMAGE_MIN_SIDE).round(),@@ -403,11 +401,9 @@ pub fn attachments_view(403
v_flex()401
v_flex()404
.gap(px(6.))402
.gap(px(6.))405
.items_start()403
.items_start()406
.children(404
.children(unplaced_images.into_iter().map(|(index, image)| {407
unplaced_images.into_iter().map(|(index, image)| {405
image_view(image, format!("{id}-image-{index}"), directory, open_image)408
image_view(image, format!("{id}-image-{index}"), directory, open_image)406
}))409
}),410
)411
.children(407
.children(412
unplaced_local.into_iter().map(|(index, image)| {408
unplaced_local.into_iter().map(|(index, image)| {413
local_image_view(image, format!("{id}-local-image-{index}"))409
local_image_view(image, format!("{id}-local-image-{index}"))@@ -255,20 +255,20 @@ pub fn member_stack(directory: &Directory, faces: &[Face], total: usize) -> Div
255
255
div().id(ElementId::Name(format!("member-face-{index}").into())),
256
256
face.user_id.as_deref(),
257
257
)
258
.when(index > 0, |element| element.ml(px(-OVERLAP)))
259
.size(px(SIZE))
260
.flex_none()
261
.flex()
262
.items_center()
263
.justify_center()
264
.rounded_full()
265
.bg(theme::surface())
266
.child(face_circle(
267
directory,
268
face,
269
SIZE - 2. * PRESENCE_RING,
270
0.45,
271
)),
258
.when(index > 0, |element| element.ml(px(-OVERLAP)))
259
.size(px(SIZE))
260
.flex_none()
261
.flex()
262
.items_center()
263
.justify_center()
264
.rounded_full()
265
.bg(theme::surface())
266
.child(face_circle(
267
directory,
268
face,
269
SIZE - 2. * PRESENCE_RING,
270
0.45,
271
)),
272
272
);
273
273
}
274
274
if total > LIMIT {
@@ -255,20 +255,20 @@ pub fn member_stack(directory: &Directory, faces: &[Face], total: usize) -> Div255
div().id(ElementId::Name(format!("member-face-{index}").into())),255
div().id(ElementId::Name(format!("member-face-{index}").into())),256
face.user_id.as_deref(),256
face.user_id.as_deref(),257
)257
)258
.when(index > 0, |element| element.ml(px(-OVERLAP)))258
.when(index > 0, |element| element.ml(px(-OVERLAP)))259
.size(px(SIZE))259
.size(px(SIZE))260
.flex_none()260
.flex_none()261
.flex()261
.flex()262
.items_center()262
.items_center()263
.justify_center()263
.justify_center()264
.rounded_full()264
.rounded_full()265
.bg(theme::surface())265
.bg(theme::surface())266
.child(face_circle(266
.child(face_circle(267
directory,267
directory,268
face,268
face,269
SIZE - 2. * PRESENCE_RING,269
SIZE - 2. * PRESENCE_RING,270
0.45,270
0.45,271
)),271
)),272
);272
);273
}273
}274
if total > LIMIT {274
if total > LIMIT {@@ -14,7 +14,11 @@ const BUTTON_SIZE: f32 = 30.;
14
14
const GLYPH_SIZE: f32 = 16.;
15
15
const JOIN_HEIGHT: f32 = 30.;
16
16
17
pub fn header_call_controls(app: &Entity<AppState>, state: &AppState, selection: &Selection) -> Vec<AnyElement> {
17
pub fn header_call_controls(
18
app: &Entity<AppState>,
19
state: &AppState,
20
selection: &Selection,
21
) -> Vec<AnyElement> {
18
22
let conversation_id = selection.conversation_id().to_owned();
19
23
let mut controls = Vec::new();
20
24
if state.running_meeting(&conversation_id).is_some() {
@@ -14,7 +14,11 @@ const BUTTON_SIZE: f32 = 30.;14
const GLYPH_SIZE: f32 = 16.;14
const GLYPH_SIZE: f32 = 16.;15
const JOIN_HEIGHT: f32 = 30.;15
const JOIN_HEIGHT: f32 = 30.;16
16
17
pub fn header_call_controls(app: &Entity<AppState>, state: &AppState, selection: &Selection) -> Vec<AnyElement> {17
pub fn header_call_controls(18
app: &Entity<AppState>,19
state: &AppState,20
selection: &Selection,21
) -> Vec<AnyElement> {18
let conversation_id = selection.conversation_id().to_owned();22
let conversation_id = selection.conversation_id().to_owned();19
let mut controls = Vec::new();23
let mut controls = Vec::new();20
if state.running_meeting(&conversation_id).is_some() {24
if state.running_meeting(&conversation_id).is_some() {@@ -58,18 +58,36 @@ pub fn return_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEle
58
58
59
59
pub fn room_chip(model: &CallModel) -> Option<AnyElement> {
60
60
model.breakout.as_ref()?;
61
Some(div().flex_none().text_size(px(13.)).text_color(theme::text_muted()).child("Breakout room").into_any_element())
61
Some(
62
div()
63
.flex_none()
64
.text_size(px(13.))
65
.text_color(theme::text_muted())
66
.child("Breakout room")
67
.into_any_element(),
68
)
62
69
}
63
70
64
71
pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
65
72
let (title, detail) = match model.hold {
66
73
HoldState::Active => return None,
67
HoldState::Local => ("On hold".to_owned(), format!("{} cannot hear you and you cannot hear them.", model.peer_name)),
68
HoldState::Remote => ("You're on hold".to_owned(), format!("{} put the call on hold.", model.peer_name)),
74
HoldState::Local => (
75
"On hold".to_owned(),
76
format!(
77
"{} cannot hear you and you cannot hear them.",
78
model.peer_name
79
),
80
),
81
HoldState::Remote => (
82
"You're on hold".to_owned(),
83
format!("{} put the call on hold.", model.peer_name),
84
),
69
85
};
70
86
let resume = (model.hold == HoldState::Local).then(|| {
71
87
let app = app.clone();
72
Button::new("call-resume").label("Resume").on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))
88
Button::new("call-resume")
89
.label("Resume")
90
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))
73
91
});
74
92
Some(
75
93
v_flex()
@@ -89,8 +107,18 @@ pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
89
107
.bg(theme::surface_raised())
90
108
.child(icon(IconName::Clock, 48., theme::text())),
91
109
)
92
.child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(title))
93
.child(div().text_size(px(14.)).text_color(theme::text_muted()).child(detail))
110
.child(
111
div()
112
.text_size(px(22.))
113
.font_weight(FontWeight::SEMIBOLD)
114
.child(title),
115
)
116
.child(
117
div()
118
.text_size(px(14.))
119
.text_color(theme::text_muted())
120
.child(detail),
121
)
94
122
.children(resume)
95
123
.into_any_element(),
96
124
)
@@ -118,7 +146,12 @@ pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<Any
118
146
.bg(hsla(0., 0., 0.04, 1.))
119
147
.text_color(theme::white())
120
148
.child(icon(IconName::Pencil, 56., theme::white()))
121
.child(div().text_size(px(18.)).font_weight(FontWeight::SEMIBOLD).child(label))
149
.child(
150
div()
151
.text_size(px(18.))
152
.font_weight(FontWeight::SEMIBOLD)
153
.child(label),
154
)
122
155
.children(open)
123
156
.into_any_element(),
124
157
)
@@ -131,7 +164,9 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle
131
164
let (transfer_app, cancel_app) = (app.clone(), app.clone());
132
165
let transfer = pill("call-consult-transfer", "Transfer now", true);
133
166
let transfer = if ready {
134
transfer.on_click(move |_, _, cx| transfer_app.update(cx, |state, cx| state.transfer_consulted(cx)))
167
transfer.on_click(move |_, _, cx| {
168
transfer_app.update(cx, |state, cx| state.transfer_consulted(cx))
169
})
135
170
} else {
136
171
transfer.opacity(0.5).cursor_default()
137
172
};
@@ -151,7 +186,11 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle
151
186
.font_weight(FontWeight::SEMIBOLD)
152
187
.child(text)
153
188
.child(transfer)
154
.child(pill("call-consult-cancel", "Cancel", false).on_click(move |_, _, cx| cancel_app.update(cx, |state, cx| state.cancel_consult(cx))))
189
.child(
190
pill("call-consult-cancel", "Cancel", false).on_click(move |_, _, cx| {
191
cancel_app.update(cx, |state, cx| state.cancel_consult(cx))
192
}),
193
)
155
194
.into_any_element(),
156
195
)
157
196
}
@@ -171,7 +210,16 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
171
210
.flex()
172
211
.items_center()
173
212
.justify_center()
174
.child(div().id("call-consent-backdrop").absolute().top_0().left_0().size_full().bg(black().opacity(BACKDROP_OPACITY)).occlude())
213
.child(
214
div()
215
.id("call-consent-backdrop")
216
.absolute()
217
.top_0()
218
.left_0()
219
.size_full()
220
.bg(black().opacity(BACKDROP_OPACITY))
221
.occlude(),
222
)
175
223
.child(
176
224
v_flex()
177
225
.id("call-consent-card")
@@ -188,7 +236,12 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
188
236
.gap(px(8.))
189
237
.items_center()
190
238
.child(div().size(px(10.)).rounded_full().bg(theme::red()))
191
.child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child("This meeting is being recorded")),
239
.child(
240
div()
241
.text_size(px(16.))
242
.font_weight(FontWeight::SEMIBOLD)
243
.child("This meeting is being recorded"),
244
),
192
245
)
193
246
.child(
194
247
div()
@@ -200,7 +253,9 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
200
253
h_flex().w_full().justify_end().child(
201
254
Button::new("call-consent-ok")
202
255
.label("OK")
203
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.accept_recording_notice(cx))),
256
.on_click(move |_, _, cx| {
257
app.update(cx, |state, cx| state.accept_recording_notice(cx))
258
}),
204
259
),
205
260
),
206
261
)
@@ -244,13 +299,30 @@ impl BackgroundMenu {
244
299
let library = &state.call_backgrounds;
245
300
BackgroundMenu {
246
301
pick: state.call_background.clone(),
247
images: library.shown().iter().map(|image| (image.id.clone(), image.name.clone(), library.thumbnail(image))).collect(),
302
images: library
303
.shown()
304
.iter()
305
.map(|image| {
306
(
307
image.id.clone(),
308
image.name.clone(),
309
library.thumbnail(image),
310
)
311
})
312
.collect(),
248
313
customs: library.customs.clone(),
249
314
}
250
315
}
251
316
}
252
317
253
fn thumbnail(app: &Entity<AppState>, index: usize, label: String, path: Option<PathBuf>, selected: bool, pick: BackgroundPick) -> AnyElement {
318
fn thumbnail(
319
app: &Entity<AppState>,
320
index: usize,
321
label: String,
322
path: Option<PathBuf>,
323
selected: bool,
324
pick: BackgroundPick,
325
) -> AnyElement {
254
326
let app = app.clone();
255
327
let tooltip = label.clone();
256
328
div()
@@ -261,43 +333,99 @@ fn thumbnail(app: &Entity<AppState>, index: usize, label: String, path: Option<P
261
333
.overflow_hidden()
262
334
.rounded(px(6.))
263
335
.border_2()
264
.border_color(if selected { theme::accent() } else { transparent_black() })
336
.border_color(if selected {
337
theme::accent()
338
} else {
339
transparent_black()
340
})
265
341
.bg(theme::surface())
266
342
.cursor_pointer()
267
343
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
268
344
.child(match path {
269
Some(path) => img(path).size_full().object_fit(ObjectFit::Cover).into_any_element(),
345
Some(path) => img(path)
346
.size_full()
347
.object_fit(ObjectFit::Cover)
348
.into_any_element(),
270
349
None => div().size_full().into_any_element(),
271
350
})
272
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_background(pick.clone(), cx)))
351
.on_click(move |_, _, cx| {
352
app.update(cx, |state, cx| state.set_call_background(pick.clone(), cx))
353
})
273
354
.into_any_element()
274
355
}
275
356
276
pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &BackgroundMenu) -> PopupMenu {
277
let (none_app, blur_app, add_app, grid_app) = (app.clone(), app.clone(), app.clone(), app.clone());
357
pub fn background_items(
358
popup: PopupMenu,
359
app: &Entity<AppState>,
360
menu: &BackgroundMenu,
361
) -> PopupMenu {
362
let (none_app, blur_app, add_app, grid_app) =
363
(app.clone(), app.clone(), app.clone(), app.clone());
278
364
let grid_menu = menu.clone();
279
365
let mut popup = popup
280
366
.separator()
281
367
.item(PopupMenuItem::label("Background"))
282
.item(PopupMenuItem::new("None").checked(menu.pick == BackgroundPick::None).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx))))
283
.item(PopupMenuItem::new("Blur").checked(menu.pick.is_blur()).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx))));
368
.item(
369
PopupMenuItem::new("None")
370
.checked(menu.pick == BackgroundPick::None)
371
.on_click(move |_, _, cx| {
372
none_app.update(cx, |state, cx| {
373
state.set_call_background(BackgroundPick::None, cx)
374
})
375
}),
376
)
377
.item(
378
PopupMenuItem::new("Blur")
379
.checked(menu.pick.is_blur())
380
.on_click(move |_, _, cx| {
381
blur_app.update(cx, |state, cx| {
382
state.set_call_background(BackgroundPick::Blur, cx)
383
})
384
}),
385
);
284
386
if !menu.images.is_empty() || !menu.customs.is_empty() {
285
387
popup = popup.item(PopupMenuItem::element(move |_, _| {
286
let defaults = grid_menu.images.iter().enumerate().map(|(index, (id, name, path))| {
287
let pick = BackgroundPick::Default(id.clone());
288
thumbnail(&grid_app, index, name.clone(), path.clone(), grid_menu.pick == pick, pick)
289
});
388
let defaults = grid_menu
389
.images
390
.iter()
391
.enumerate()
392
.map(|(index, (id, name, path))| {
393
let pick = BackgroundPick::Default(id.clone());
394
thumbnail(
395
&grid_app,
396
index,
397
name.clone(),
398
path.clone(),
399
grid_menu.pick == pick,
400
pick,
401
)
402
});
290
403
let customs = grid_menu.customs.iter().enumerate().map(|(index, path)| {
291
404
let pick = BackgroundPick::Custom(path.clone());
292
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());
293
thumbnail(&grid_app, grid_menu.images.len() + index, name, Some(path.clone()), grid_menu.pick == pick, pick)
405
let name = path
406
.file_name()
407
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());
408
thumbnail(
409
&grid_app,
410
grid_menu.images.len() + index,
411
name,
412
Some(path.clone()),
413
grid_menu.pick == pick,
414
pick,
415
)
294
416
});
295
h_flex().w(px(MENU_WIDTH - MENU_PADDING)).flex_wrap().gap(px(THUMBNAIL_GAP)).children(defaults.chain(customs))
417
h_flex()
418
.w(px(MENU_WIDTH - MENU_PADDING))
419
.flex_wrap()
420
.gap(px(THUMBNAIL_GAP))
421
.children(defaults.chain(customs))
296
422
}));
297
423
}
298
424
popup.item(
299
425
PopupMenuItem::new("Add image...")
300
426
.icon(IconName::Plus)
301
.on_click(move |_, _, cx| add_app.update(cx, |state, cx| state.add_call_background(cx))),
427
.on_click(move |_, _, cx| {
428
add_app.update(cx, |state, cx| state.add_call_background(cx))
429
}),
302
430
)
303
431
}
@@ -58,18 +58,36 @@ pub fn return_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEle58
58
59
pub fn room_chip(model: &CallModel) -> Option<AnyElement> {59
pub fn room_chip(model: &CallModel) -> Option<AnyElement> {60
model.breakout.as_ref()?;60
model.breakout.as_ref()?;61
Some(div().flex_none().text_size(px(13.)).text_color(theme::text_muted()).child("Breakout room").into_any_element())61
Some(62
div()63
.flex_none()64
.text_size(px(13.))65
.text_color(theme::text_muted())66
.child("Breakout room")67
.into_any_element(),68
)62
}69
}63
70
64
pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {71
pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {65
let (title, detail) = match model.hold {72
let (title, detail) = match model.hold {66
HoldState::Active => return None,73
HoldState::Active => return None,67
HoldState::Local => ("On hold".to_owned(), format!("{} cannot hear you and you cannot hear them.", model.peer_name)),74
HoldState::Local => (68
HoldState::Remote => ("You're on hold".to_owned(), format!("{} put the call on hold.", model.peer_name)),75
"On hold".to_owned(),76
format!(77
"{} cannot hear you and you cannot hear them.",78
model.peer_name79
),80
),81
HoldState::Remote => (82
"You're on hold".to_owned(),83
format!("{} put the call on hold.", model.peer_name),84
),69
};85
};70
let resume = (model.hold == HoldState::Local).then(|| {86
let resume = (model.hold == HoldState::Local).then(|| {71
let app = app.clone();87
let app = app.clone();72
Button::new("call-resume").label("Resume").on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))88
Button::new("call-resume")89
.label("Resume")90
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))73
});91
});74
Some(92
Some(75
v_flex()93
v_flex()@@ -89,8 +107,18 @@ pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen89
.bg(theme::surface_raised())107
.bg(theme::surface_raised())90
.child(icon(IconName::Clock, 48., theme::text())),108
.child(icon(IconName::Clock, 48., theme::text())),91
)109
)92
.child(div().text_size(px(22.)).font_weight(FontWeight::SEMIBOLD).child(title))110
.child(93
.child(div().text_size(px(14.)).text_color(theme::text_muted()).child(detail))111
div()112
.text_size(px(22.))113
.font_weight(FontWeight::SEMIBOLD)114
.child(title),115
)116
.child(117
div()118
.text_size(px(14.))119
.text_color(theme::text_muted())120
.child(detail),121
)94
.children(resume)122
.children(resume)95
.into_any_element(),123
.into_any_element(),96
)124
)@@ -118,7 +146,12 @@ pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<Any118
.bg(hsla(0., 0., 0.04, 1.))146
.bg(hsla(0., 0., 0.04, 1.))119
.text_color(theme::white())147
.text_color(theme::white())120
.child(icon(IconName::Pencil, 56., theme::white()))148
.child(icon(IconName::Pencil, 56., theme::white()))121
.child(div().text_size(px(18.)).font_weight(FontWeight::SEMIBOLD).child(label))149
.child(150
div()151
.text_size(px(18.))152
.font_weight(FontWeight::SEMIBOLD)153
.child(label),154
)122
.children(open)155
.children(open)123
.into_any_element(),156
.into_any_element(),124
)157
)@@ -131,7 +164,9 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle131
let (transfer_app, cancel_app) = (app.clone(), app.clone());164
let (transfer_app, cancel_app) = (app.clone(), app.clone());132
let transfer = pill("call-consult-transfer", "Transfer now", true);165
let transfer = pill("call-consult-transfer", "Transfer now", true);133
let transfer = if ready {166
let transfer = if ready {134
transfer.on_click(move |_, _, cx| transfer_app.update(cx, |state, cx| state.transfer_consulted(cx)))167
transfer.on_click(move |_, _, cx| {168
transfer_app.update(cx, |state, cx| state.transfer_consulted(cx))169
})135
} else {170
} else {136
transfer.opacity(0.5).cursor_default()171
transfer.opacity(0.5).cursor_default()137
};172
};@@ -151,7 +186,11 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle151
.font_weight(FontWeight::SEMIBOLD)186
.font_weight(FontWeight::SEMIBOLD)152
.child(text)187
.child(text)153
.child(transfer)188
.child(transfer)154
.child(pill("call-consult-cancel", "Cancel", false).on_click(move |_, _, cx| cancel_app.update(cx, |state, cx| state.cancel_consult(cx))))189
.child(190
pill("call-consult-cancel", "Cancel", false).on_click(move |_, _, cx| {191
cancel_app.update(cx, |state, cx| state.cancel_consult(cx))192
}),193
)155
.into_any_element(),194
.into_any_element(),156
)195
)157
}196
}@@ -171,7 +210,16 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE171
.flex()210
.flex()172
.items_center()211
.items_center()173
.justify_center()212
.justify_center()174
.child(div().id("call-consent-backdrop").absolute().top_0().left_0().size_full().bg(black().opacity(BACKDROP_OPACITY)).occlude())213
.child(214
div()215
.id("call-consent-backdrop")216
.absolute()217
.top_0()218
.left_0()219
.size_full()220
.bg(black().opacity(BACKDROP_OPACITY))221
.occlude(),222
)175
.child(223
.child(176
v_flex()224
v_flex()177
.id("call-consent-card")225
.id("call-consent-card")@@ -188,7 +236,12 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE188
.gap(px(8.))236
.gap(px(8.))189
.items_center()237
.items_center()190
.child(div().size(px(10.)).rounded_full().bg(theme::red()))238
.child(div().size(px(10.)).rounded_full().bg(theme::red()))191
.child(div().text_size(px(16.)).font_weight(FontWeight::SEMIBOLD).child("This meeting is being recorded")),239
.child(240
div()241
.text_size(px(16.))242
.font_weight(FontWeight::SEMIBOLD)243
.child("This meeting is being recorded"),244
),192
)245
)193
.child(246
.child(194
div()247
div()@@ -200,7 +253,9 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE200
h_flex().w_full().justify_end().child(253
h_flex().w_full().justify_end().child(201
Button::new("call-consent-ok")254
Button::new("call-consent-ok")202
.label("OK")255
.label("OK")203
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.accept_recording_notice(cx))),256
.on_click(move |_, _, cx| {257
app.update(cx, |state, cx| state.accept_recording_notice(cx))258
}),204
),259
),205
),260
),206
)261
)@@ -244,13 +299,30 @@ impl BackgroundMenu {244
let library = &state.call_backgrounds;299
let library = &state.call_backgrounds;245
BackgroundMenu {300
BackgroundMenu {246
pick: state.call_background.clone(),301
pick: state.call_background.clone(),247
images: library.shown().iter().map(|image| (image.id.clone(), image.name.clone(), library.thumbnail(image))).collect(),302
images: library303
.shown()304
.iter()305
.map(|image| {306
(307
image.id.clone(),308
image.name.clone(),309
library.thumbnail(image),310
)311
})312
.collect(),248
customs: library.customs.clone(),313
customs: library.customs.clone(),249
}314
}250
}315
}251
}316
}252
317
253
fn thumbnail(app: &Entity<AppState>, index: usize, label: String, path: Option<PathBuf>, selected: bool, pick: BackgroundPick) -> AnyElement {318
fn thumbnail(319
app: &Entity<AppState>,320
index: usize,321
label: String,322
path: Option<PathBuf>,323
selected: bool,324
pick: BackgroundPick,325
) -> AnyElement {254
let app = app.clone();326
let app = app.clone();255
let tooltip = label.clone();327
let tooltip = label.clone();256
div()328
div()@@ -261,43 +333,99 @@ fn thumbnail(app: &Entity<AppState>, index: usize, label: String, path: Option<P261
.overflow_hidden()333
.overflow_hidden()262
.rounded(px(6.))334
.rounded(px(6.))263
.border_2()335
.border_2()264
.border_color(if selected { theme::accent() } else { transparent_black() })336
.border_color(if selected {337
theme::accent()338
} else {339
transparent_black()340
})265
.bg(theme::surface())341
.bg(theme::surface())266
.cursor_pointer()342
.cursor_pointer()267
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))343
.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))268
.child(match path {344
.child(match path {269
Some(path) => img(path).size_full().object_fit(ObjectFit::Cover).into_any_element(),345
Some(path) => img(path)346
.size_full()347
.object_fit(ObjectFit::Cover)348
.into_any_element(),270
None => div().size_full().into_any_element(),349
None => div().size_full().into_any_element(),271
})350
})272
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_background(pick.clone(), cx)))351
.on_click(move |_, _, cx| {352
app.update(cx, |state, cx| state.set_call_background(pick.clone(), cx))353
})273
.into_any_element()354
.into_any_element()274
}355
}275
356
276
pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &BackgroundMenu) -> PopupMenu {357
pub fn background_items(277
let (none_app, blur_app, add_app, grid_app) = (app.clone(), app.clone(), app.clone(), app.clone());358
popup: PopupMenu,359
app: &Entity<AppState>,360
menu: &BackgroundMenu,361
) -> PopupMenu {362
let (none_app, blur_app, add_app, grid_app) =363
(app.clone(), app.clone(), app.clone(), app.clone());278
let grid_menu = menu.clone();364
let grid_menu = menu.clone();279
let mut popup = popup365
let mut popup = popup280
.separator()366
.separator()281
.item(PopupMenuItem::label("Background"))367
.item(PopupMenuItem::label("Background"))282
.item(PopupMenuItem::new("None").checked(menu.pick == BackgroundPick::None).on_click(move |_, _, cx| none_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::None, cx))))368
.item(283
.item(PopupMenuItem::new("Blur").checked(menu.pick.is_blur()).on_click(move |_, _, cx| blur_app.update(cx, |state, cx| state.set_call_background(BackgroundPick::Blur, cx))));369
PopupMenuItem::new("None")370
.checked(menu.pick == BackgroundPick::None)371
.on_click(move |_, _, cx| {372
none_app.update(cx, |state, cx| {373
state.set_call_background(BackgroundPick::None, cx)374
})375
}),376
)377
.item(378
PopupMenuItem::new("Blur")379
.checked(menu.pick.is_blur())380
.on_click(move |_, _, cx| {381
blur_app.update(cx, |state, cx| {382
state.set_call_background(BackgroundPick::Blur, cx)383
})384
}),385
);284
if !menu.images.is_empty() || !menu.customs.is_empty() {386
if !menu.images.is_empty() || !menu.customs.is_empty() {285
popup = popup.item(PopupMenuItem::element(move |_, _| {387
popup = popup.item(PopupMenuItem::element(move |_, _| {286
let defaults = grid_menu.images.iter().enumerate().map(|(index, (id, name, path))| {388
let defaults = grid_menu287
let pick = BackgroundPick::Default(id.clone());389
.images288
thumbnail(&grid_app, index, name.clone(), path.clone(), grid_menu.pick == pick, pick)390
.iter()289
});391
.enumerate()392
.map(|(index, (id, name, path))| {393
let pick = BackgroundPick::Default(id.clone());394
thumbnail(395
&grid_app,396
index,397
name.clone(),398
path.clone(),399
grid_menu.pick == pick,400
pick,401
)402
});290
let customs = grid_menu.customs.iter().enumerate().map(|(index, path)| {403
let customs = grid_menu.customs.iter().enumerate().map(|(index, path)| {291
let pick = BackgroundPick::Custom(path.clone());404
let pick = BackgroundPick::Custom(path.clone());292
let name = path.file_name().map_or_else(String::new, |name| name.to_string_lossy().into_owned());405
let name = path293
thumbnail(&grid_app, grid_menu.images.len() + index, name, Some(path.clone()), grid_menu.pick == pick, pick)406
.file_name()407
.map_or_else(String::new, |name| name.to_string_lossy().into_owned());408
thumbnail(409
&grid_app,410
grid_menu.images.len() + index,411
name,412
Some(path.clone()),413
grid_menu.pick == pick,414
pick,415
)294
});416
});295
h_flex().w(px(MENU_WIDTH - MENU_PADDING)).flex_wrap().gap(px(THUMBNAIL_GAP)).children(defaults.chain(customs))417
h_flex()418
.w(px(MENU_WIDTH - MENU_PADDING))419
.flex_wrap()420
.gap(px(THUMBNAIL_GAP))421
.children(defaults.chain(customs))296
}));422
}));297
}423
}298
popup.item(424
popup.item(299
PopupMenuItem::new("Add image...")425
PopupMenuItem::new("Add image...")300
.icon(IconName::Plus)426
.icon(IconName::Plus)301
.on_click(move |_, _, cx| add_app.update(cx, |state, cx| state.add_call_background(cx))),427
.on_click(move |_, _, cx| {428
add_app.update(cx, |state, cx| state.add_call_background(cx))429
}),302
)430
)303
}431
}@@ -97,9 +97,16 @@ pub fn render_call_mini(app: &Entity<AppState>, state: &AppState) -> Option<AnyE
97
97
.font_weight(FontWeight::SEMIBOLD)
98
98
.child(model.title.clone()),
99
99
)
100
.child(div().text_size(px(12.)).text_color(status_color).child(status)),
100
.child(
101
div()
102
.text_size(px(12.))
103
.text_color(status_color)
104
.child(status),
105
),
101
106
)
102
.when(model.local_share.is_some(), |mini| mini.child(sharing_badge(app)))
107
.when(model.local_share.is_some(), |mini| {
108
mini.child(sharing_badge(app))
109
})
103
110
.child(
104
111
h_flex()
105
112
.gap(px(8.))
@@ -97,9 +97,16 @@ pub fn render_call_mini(app: &Entity<AppState>, state: &AppState) -> Option<AnyE97
.font_weight(FontWeight::SEMIBOLD)97
.font_weight(FontWeight::SEMIBOLD)98
.child(model.title.clone()),98
.child(model.title.clone()),99
)99
)100
.child(div().text_size(px(12.)).text_color(status_color).child(status)),100
.child(101
div()102
.text_size(px(12.))103
.text_color(status_color)104
.child(status),105
),101
)106
)102
.when(model.local_share.is_some(), |mini| mini.child(sharing_badge(app)))107
.when(model.local_share.is_some(), |mini| {108
mini.child(sharing_badge(app))109
})103
.child(110
.child(104
h_flex()111
h_flex()105
.gap(px(8.))112
.gap(px(8.))@@ -47,13 +47,22 @@ impl MiniWindowView {
47
47
}
48
48
49
49
pub fn speaker_tile(model: &CallModel) -> Option<&Tile> {
50
let present: Vec<&Tile> = model.visible_tiles().into_iter().filter(|tile| tile.state == TileState::Present).collect();
50
let present: Vec<&Tile> = model
51
.visible_tiles()
52
.into_iter()
53
.filter(|tile| tile.state == TileState::Present)
54
.collect();
51
55
let focused = model
52
56
.focus()
53
57
.filter(|focus| !focus.own)
54
58
.and_then(|focus| present.iter().find(|tile| tile.mri == focus.mri).copied());
55
59
focused
56
.or_else(|| present.iter().find(|tile| model.tile_speaking(tile)).copied())
60
.or_else(|| {
61
present
62
.iter()
63
.find(|tile| model.tile_speaking(tile))
64
.copied()
65
})
57
66
.or_else(|| present.first().copied())
58
67
}
59
68
@@ -72,7 +81,9 @@ fn chip(text: String) -> Div {
72
81
}
73
82
74
83
fn cover(image: std::sync::Arc<RenderImage>) -> Img {
75
img(ImageSource::Render(image)).size_full().object_fit(ObjectFit::Cover)
84
img(ImageSource::Render(image))
85
.size_full()
86
.object_fit(ObjectFit::Cover)
76
87
}
77
88
78
89
fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElement {
@@ -86,7 +97,13 @@ fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElemen
86
97
.justify_center()
87
98
.gap(px(8.))
88
99
.child(icon(IconName::Phone, 28., theme::accent_text()))
89
.child(div().max_w_full().truncate().text_size(px(13.)).child(model.title.clone()))
100
.child(
101
div()
102
.max_w_full()
103
.truncate()
104
.text_size(px(13.))
105
.child(model.title.clone()),
106
)
90
107
.into_any_element();
91
108
};
92
109
let video = (tile.has_video || model.is_one_to_one())
@@ -99,8 +116,20 @@ fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElemen
99
116
.items_center()
100
117
.justify_center()
101
118
.gap(px(8.))
102
.child(person_avatar(&state.directory, tile.user_id.as_deref(), &tile.name, SPEAKER_AVATAR))
103
.child(div().max_w_full().truncate().text_size(px(13.)).font_weight(FontWeight::SEMIBOLD).child(tile.name.clone()))
119
.child(person_avatar(
120
&state.directory,
121
tile.user_id.as_deref(),
122
&tile.name,
123
SPEAKER_AVATAR,
124
))
125
.child(
126
div()
127
.max_w_full()
128
.truncate()
129
.text_size(px(13.))
130
.font_weight(FontWeight::SEMIBOLD)
131
.child(tile.name.clone()),
132
)
104
133
.into_any_element(),
105
134
}
106
135
}
@@ -148,7 +177,11 @@ impl Render for MiniWindowView {
148
177
.rounded(px(WINDOW_RADIUS))
149
178
.bg(theme::surface())
150
179
.border_2()
151
.border_color(if speaking { theme::green() } else { theme::border_strong() })
180
.border_color(if speaking {
181
theme::green()
182
} else {
183
theme::border_strong()
184
})
152
185
.text_color(theme::text())
153
186
.child(speaker_layer(state, model, now))
154
187
.child(
@@ -161,8 +194,20 @@ impl Render for MiniWindowView {
161
194
.bottom(px(CONTROLS_HEIGHT))
162
195
.window_control_area(WindowControlArea::Drag)
163
196
.on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move())
164
.child(div().absolute().top(px(8.)).left(px(8.)).child(chip(status)))
165
.children(speaker_name.map(|name| div().absolute().bottom(px(6.)).left(px(8.)).child(chip(name))))
197
.child(
198
div()
199
.absolute()
200
.top(px(8.))
201
.left(px(8.))
202
.child(chip(status)),
203
)
204
.children(speaker_name.map(|name| {
205
div()
206
.absolute()
207
.bottom(px(6.))
208
.left(px(8.))
209
.child(chip(name))
210
}))
166
211
.children(self_view(state, model, now)),
167
212
)
168
213
.child(
@@ -178,15 +223,32 @@ impl Render for MiniWindowView {
178
223
.bg(hsla(0., 0., 0., SHADE_BACKGROUND))
179
224
.opacity(0.)
180
225
.group_hover("call-mini-window", |controls| controls.opacity(1.))
181
.child(mute_button(&self.app, model, "call-mini-window-mute", CONTROL_SIZE))
226
.child(mute_button(
227
&self.app,
228
model,
229
"call-mini-window-mute",
230
CONTROL_SIZE,
231
))
182
232
.child(camera_button(&self.app, model).size(px(CONTROL_SIZE)))
183
233
.child(
184
round_control("call-mini-window-back", IconName::Maximize2, theme::surface_raised(), theme::text())
185
.size(px(CONTROL_SIZE))
186
.tooltip(|window, cx| Tooltip::new("Back to call").build(window, cx))
187
.on_click(move |_, _, cx| windows.update(cx, |windows, cx| windows.return_to_call(cx))),
234
round_control(
235
"call-mini-window-back",
236
IconName::Maximize2,
237
theme::surface_raised(),
238
theme::text(),
239
)
240
.size(px(CONTROL_SIZE))
241
.tooltip(|window, cx| Tooltip::new("Back to call").build(window, cx))
242
.on_click(move |_, _, cx| {
243
windows.update(cx, |windows, cx| windows.return_to_call(cx))
244
}),
188
245
)
189
.child(leave_button(&self.app, model, "call-mini-window-leave", true)),
246
.child(leave_button(
247
&self.app,
248
model,
249
"call-mini-window-leave",
250
true,
251
)),
190
252
)
191
253
.into_any_element()
192
254
}
@@ -208,9 +270,15 @@ mod tests {
208
270
fn speaker_is_the_speaking_tile_before_the_first_one() {
209
271
let mut model = CallModel::test();
210
272
model.tiles = vec![present("8:a", "Ada"), present("8:b", "Bo")];
211
assert_eq!(speaker_tile(&model).map(|tile| tile.name.as_str()), Some("Ada"));
273
assert_eq!(
274
speaker_tile(&model).map(|tile| tile.name.as_str()),
275
Some("Ada")
276
);
212
277
model.speaking_mris = vec!["8:b".to_owned()];
213
assert_eq!(speaker_tile(&model).map(|tile| tile.name.as_str()), Some("Bo"));
278
assert_eq!(
279
speaker_tile(&model).map(|tile| tile.name.as_str()),
280
Some("Bo")
281
);
214
282
}
215
283
216
284
#[test]
@@ -219,7 +287,10 @@ mod tests {
219
287
model.tiles = vec![present("8:a", "Ada"), present("8:b", "Bo")];
220
288
model.speaking_mris = vec!["8:b".to_owned()];
221
289
model.toggle_pin("8:a");
222
assert_eq!(speaker_tile(&model).map(|tile| tile.name.as_str()), Some("Ada"));
290
assert_eq!(
291
speaker_tile(&model).map(|tile| tile.name.as_str()),
292
Some("Ada")
293
);
223
294
}
224
295
225
296
#[test]
@@ -47,13 +47,22 @@ impl MiniWindowView {47
}47
}48
48
49
pub fn speaker_tile(model: &CallModel) -> Option<&Tile> {49
pub fn speaker_tile(model: &CallModel) -> Option<&Tile> {50
let present: Vec<&Tile> = model.visible_tiles().into_iter().filter(|tile| tile.state == TileState::Present).collect();50
let present: Vec<&Tile> = model51
.visible_tiles()52
.into_iter()53
.filter(|tile| tile.state == TileState::Present)54
.collect();51
let focused = model55
let focused = model52
.focus()56
.focus()53
.filter(|focus| !focus.own)57
.filter(|focus| !focus.own)54
.and_then(|focus| present.iter().find(|tile| tile.mri == focus.mri).copied());58
.and_then(|focus| present.iter().find(|tile| tile.mri == focus.mri).copied());55
focused59
focused56
.or_else(|| present.iter().find(|tile| model.tile_speaking(tile)).copied())60
.or_else(|| {61
present62
.iter()63
.find(|tile| model.tile_speaking(tile))64
.copied()65
})57
.or_else(|| present.first().copied())66
.or_else(|| present.first().copied())58
}67
}59
68
@@ -72,7 +81,9 @@ fn chip(text: String) -> Div {72
}81
}73
82
74
fn cover(image: std::sync::Arc<RenderImage>) -> Img {83
fn cover(image: std::sync::Arc<RenderImage>) -> Img {75
img(ImageSource::Render(image)).size_full().object_fit(ObjectFit::Cover)84
img(ImageSource::Render(image))85
.size_full()86
.object_fit(ObjectFit::Cover)76
}87
}77
88
78
fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElement {89
fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElement {@@ -86,7 +97,13 @@ fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElemen86
.justify_center()97
.justify_center()87
.gap(px(8.))98
.gap(px(8.))88
.child(icon(IconName::Phone, 28., theme::accent_text()))99
.child(icon(IconName::Phone, 28., theme::accent_text()))89
.child(div().max_w_full().truncate().text_size(px(13.)).child(model.title.clone()))100
.child(101
div()102
.max_w_full()103
.truncate()104
.text_size(px(13.))105
.child(model.title.clone()),106
)90
.into_any_element();107
.into_any_element();91
};108
};92
let video = (tile.has_video || model.is_one_to_one())109
let video = (tile.has_video || model.is_one_to_one())@@ -99,8 +116,20 @@ fn speaker_layer(state: &AppState, model: &CallModel, now: Instant) -> AnyElemen99
.items_center()116
.items_center()100
.justify_center()117
.justify_center()101
.gap(px(8.))118
.gap(px(8.))102
.child(person_avatar(&state.directory, tile.user_id.as_deref(), &tile.name, SPEAKER_AVATAR))119
.child(person_avatar(103
.child(div().max_w_full().truncate().text_size(px(13.)).font_weight(FontWeight::SEMIBOLD).child(tile.name.clone()))120
&state.directory,121
tile.user_id.as_deref(),122
&tile.name,123
SPEAKER_AVATAR,124
))125
.child(126
div()127
.max_w_full()128
.truncate()129
.text_size(px(13.))130
.font_weight(FontWeight::SEMIBOLD)131
.child(tile.name.clone()),132
)104
.into_any_element(),133
.into_any_element(),105
}134
}106
}135
}@@ -148,7 +177,11 @@ impl Render for MiniWindowView {148
.rounded(px(WINDOW_RADIUS))177
.rounded(px(WINDOW_RADIUS))149
.bg(theme::surface())178
.bg(theme::surface())150
.border_2()179
.border_2()151
.border_color(if speaking { theme::green() } else { theme::border_strong() })180
.border_color(if speaking {181
theme::green()182
} else {183
theme::border_strong()184
})152
.text_color(theme::text())185
.text_color(theme::text())153
.child(speaker_layer(state, model, now))186
.child(speaker_layer(state, model, now))154
.child(187
.child(@@ -161,8 +194,20 @@ impl Render for MiniWindowView {161
.bottom(px(CONTROLS_HEIGHT))194
.bottom(px(CONTROLS_HEIGHT))162
.window_control_area(WindowControlArea::Drag)195
.window_control_area(WindowControlArea::Drag)163
.on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move())196
.on_mouse_down(MouseButton::Left, |_, window, _| window.start_window_move())164
.child(div().absolute().top(px(8.)).left(px(8.)).child(chip(status)))197
.child(165
.children(speaker_name.map(|name| div().absolute().bottom(px(6.)).left(px(8.)).child(chip(name))))198
div()199
.absolute()200
.top(px(8.))201
.left(px(8.))202
.child(chip(status)),203
)204
.children(speaker_name.map(|name| {205
div()206
.absolute()207
.bottom(px(6.))208
.left(px(8.))209
.child(chip(name))210
}))166
.children(self_view(state, model, now)),211
.children(self_view(state, model, now)),167
)212
)168
.child(213
.child(@@ -178,15 +223,32 @@ impl Render for MiniWindowView {178
.bg(hsla(0., 0., 0., SHADE_BACKGROUND))223
.bg(hsla(0., 0., 0., SHADE_BACKGROUND))179
.opacity(0.)224
.opacity(0.)180
.group_hover("call-mini-window", |controls| controls.opacity(1.))225
.group_hover("call-mini-window", |controls| controls.opacity(1.))181
.child(mute_button(&self.app, model, "call-mini-window-mute", CONTROL_SIZE))226
.child(mute_button(227
&self.app,228
model,229
"call-mini-window-mute",230
CONTROL_SIZE,231
))182
.child(camera_button(&self.app, model).size(px(CONTROL_SIZE)))232
.child(camera_button(&self.app, model).size(px(CONTROL_SIZE)))183
.child(233
.child(184
round_control("call-mini-window-back", IconName::Maximize2, theme::surface_raised(), theme::text())234
round_control(185
.size(px(CONTROL_SIZE))235
"call-mini-window-back",186
.tooltip(|window, cx| Tooltip::new("Back to call").build(window, cx))236
IconName::Maximize2,187
.on_click(move |_, _, cx| windows.update(cx, |windows, cx| windows.return_to_call(cx))),237
theme::surface_raised(),238
theme::text(),239
)240
.size(px(CONTROL_SIZE))241
.tooltip(|window, cx| Tooltip::new("Back to call").build(window, cx))242
.on_click(move |_, _, cx| {243
windows.update(cx, |windows, cx| windows.return_to_call(cx))244
}),188
)245
)189
.child(leave_button(&self.app, model, "call-mini-window-leave", true)),246
.child(leave_button(247
&self.app,248
model,249
"call-mini-window-leave",250
true,251
)),190
)252
)191
.into_any_element()253
.into_any_element()192
}254
}@@ -208,9 +270,15 @@ mod tests {208
fn speaker_is_the_speaking_tile_before_the_first_one() {270
fn speaker_is_the_speaking_tile_before_the_first_one() {209
let mut model = CallModel::test();271
let mut model = CallModel::test();210
model.tiles = vec![present("8:a", "Ada"), present("8:b", "Bo")];272
model.tiles = vec![present("8:a", "Ada"), present("8:b", "Bo")];211
assert_eq!(speaker_tile(&model).map(|tile| tile.name.as_str()), Some("Ada"));273
assert_eq!(274
speaker_tile(&model).map(|tile| tile.name.as_str()),275
Some("Ada")276
);212
model.speaking_mris = vec!["8:b".to_owned()];277
model.speaking_mris = vec!["8:b".to_owned()];213
assert_eq!(speaker_tile(&model).map(|tile| tile.name.as_str()), Some("Bo"));278
assert_eq!(279
speaker_tile(&model).map(|tile| tile.name.as_str()),280
Some("Bo")281
);214
}282
}215
283
216
#[test]284
#[test]@@ -219,7 +287,10 @@ mod tests {219
model.tiles = vec![present("8:a", "Ada"), present("8:b", "Bo")];287
model.tiles = vec![present("8:a", "Ada"), present("8:b", "Bo")];220
model.speaking_mris = vec!["8:b".to_owned()];288
model.speaking_mris = vec!["8:b".to_owned()];221
model.toggle_pin("8:a");289
model.toggle_pin("8:a");222
assert_eq!(speaker_tile(&model).map(|tile| tile.name.as_str()), Some("Ada"));290
assert_eq!(291
speaker_tile(&model).map(|tile| tile.name.as_str()),292
Some("Ada")293
);223
}294
}224
295
225
#[test]296
#[test]@@ -12,7 +12,9 @@ use gpui_kit::prelude::FluentBuilder as _;
12
12
use gpui_kit::*;
13
13
14
14
use super::avatar::person_avatar;
15
use super::call_extras::{BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker};
15
use super::call_extras::{
16
BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker,
17
};
16
18
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};
17
19
use super::widgets::icon;
18
20
use crate::app_state::AppState;
@@ -40,7 +42,11 @@ fn dark_text() -> Hsla {
40
42
}
41
43
42
44
pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {
43
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (dark_text().opacity(0.12), dark_text()) };
45
let (background, foreground) = if filled {
46
(dark_text(), theme::white())
47
} else {
48
(dark_text().opacity(0.12), dark_text())
49
};
44
50
div()
45
51
.id(id)
46
52
.h(px(PILL_HEIGHT))
@@ -66,33 +72,54 @@ pub fn lobby_text(waiting: usize) -> String {
66
72
}
67
73
68
74
fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {
69
v_flex().w(px(LOBBY_LIST_WIDTH)).gap(px(6.)).children(guests.iter().map(|(mri, name)| {
70
let (admit_app, deny_app) = (app.clone(), app.clone());
71
let (admit_mri, deny_mri) = (mri.clone(), mri.clone());
72
h_flex()
73
.w_full()
74
.gap(px(8.))
75
.items_center()
76
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(truncated(name, LOBBY_NAME_LIMIT)))
77
.child(
78
Button::new(SharedString::from(format!("lobby-admit-{mri}")))
79
.label("Admit")
80
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))),
81
)
82
.child(
83
Button::new(SharedString::from(format!("lobby-deny-{mri}")))
84
.label("Deny")
85
.ghost()
86
.on_click(move |_, _, cx| deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))),
87
)
88
}))
75
v_flex()
76
.w(px(LOBBY_LIST_WIDTH))
77
.gap(px(6.))
78
.children(guests.iter().map(|(mri, name)| {
79
let (admit_app, deny_app) = (app.clone(), app.clone());
80
let (admit_mri, deny_mri) = (mri.clone(), mri.clone());
81
h_flex()
82
.w_full()
83
.gap(px(8.))
84
.items_center()
85
.child(
86
div()
87
.flex_1()
88
.min_w_0()
89
.truncate()
90
.text_size(px(14.))
91
.child(truncated(name, LOBBY_NAME_LIMIT)),
92
)
93
.child(
94
Button::new(SharedString::from(format!("lobby-admit-{mri}")))
95
.label("Admit")
96
.on_click(move |_, _, cx| {
97
admit_app.update(cx, |state, cx| {
98
state.admit_call_guest(admit_mri.clone(), cx)
99
})
100
}),
101
)
102
.child(
103
Button::new(SharedString::from(format!("lobby-deny-{mri}")))
104
.label("Deny")
105
.ghost()
106
.on_click(move |_, _, cx| {
107
deny_app
108
.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
109
}),
110
)
111
}))
89
112
}
90
113
91
114
pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {
92
115
if !model.can_admit() {
93
116
return None;
94
117
}
95
let guests: Vec<(String, String)> = model.lobby_guests().into_iter().map(|tile| (tile.mri.clone(), tile.name.clone())).collect();
118
let guests: Vec<(String, String)> = model
119
.lobby_guests()
120
.into_iter()
121
.map(|tile| (tile.mri.clone(), tile.name.clone()))
122
.collect();
96
123
if guests.is_empty() {
97
124
return None;
98
125
}
@@ -117,29 +144,50 @@ pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElem
117
144
Popover::new("call-lobby-popover")
118
145
.anchor(Anchor::TopLeft)
119
146
.offset(px(8.))
120
.trigger(Button::new("call-lobby-view").ghost().p_0().h(px(PILL_HEIGHT)).rounded_full().child(pill("call-lobby-view-face", "View", false)))
147
.trigger(
148
Button::new("call-lobby-view")
149
.ghost()
150
.p_0()
151
.h(px(PILL_HEIGHT))
152
.rounded_full()
153
.child(pill("call-lobby-view-face", "View", false)),
154
)
121
155
.content(move |_, _, _| lobby_list(&list_app, &guests)),
122
156
)
123
157
.child(
124
pill("call-lobby-admit-all", "Admit all", true)
125
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_all_call_guests(cx))),
158
pill("call-lobby-admit-all", "Admit all", true).on_click(move |_, _, cx| {
159
admit_app.update(cx, |state, cx| state.admit_all_call_guests(cx))
160
}),
126
161
)
127
162
.into_any_element(),
128
163
)
129
164
}
130
165
131
fn confirm_remove(app: &Entity<AppState>, mri: &str, name: &str, window: &mut Window, cx: &mut App) {
166
fn confirm_remove(
167
app: &Entity<AppState>,
168
mri: &str,
169
name: &str,
170
window: &mut Window,
171
cx: &mut App,
172
) {
132
173
let app = app.clone();
133
174
let mri = mri.to_owned();
134
175
let heading = format!("Remove {} from the meeting?", truncated(name, NAME_LIMIT));
135
176
window.open_alert_dialog(cx, move |alert, _, _| {
136
177
let app = app.clone();
137
178
let mri = mri.clone();
138
let cancel = Button::new("remove-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));
139
let remove = Button::new("remove-confirm").label("Remove").danger().on_click(move |_, window, cx| {
140
app.update(cx, |state, cx| state.remove_call_participant(mri.clone(), cx));
141
window.close_dialog(cx);
142
});
179
let cancel = Button::new("remove-cancel")
180
.label("Cancel")
181
.on_click(|_, window, cx| window.close_dialog(cx));
182
let remove = Button::new("remove-confirm")
183
.label("Remove")
184
.danger()
185
.on_click(move |_, window, cx| {
186
app.update(cx, |state, cx| {
187
state.remove_call_participant(mri.clone(), cx)
188
});
189
window.close_dialog(cx);
190
});
143
191
alert
144
192
.title(heading.clone())
145
193
.description("They leave the call and can only come back if they join again.")
@@ -148,11 +196,22 @@ fn confirm_remove(app: &Entity<AppState>, mri: &str, name: &str, window: &mut Wi
148
196
});
149
197
}
150
198
151
pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> PopupMenu {
199
pub fn tile_menu(
200
popup: PopupMenu,
201
app: &Entity<AppState>,
202
model: &CallModel,
203
mri: &str,
204
name: &str,
205
own: bool,
206
) -> PopupMenu {
152
207
let pinned = model.is_pinned(mri);
153
208
let spotlighted = model.is_spotlighted(mri);
154
209
let organizes = model.organizes_meeting();
155
let raised = !own && model.tiles.iter().any(|tile| tile.mri == mri && tile.hand.is_some());
210
let raised = !own
211
&& model
212
.tiles
213
.iter()
214
.any(|tile| tile.mri == mri && tile.hand.is_some());
156
215
let muted = model.tiles.iter().any(|tile| tile.mri == mri && tile.muted);
157
216
let mut popup = popup.min_w(px(MENU_WIDTH));
158
217
let pin_app = app.clone();
@@ -160,14 +219,24 @@ pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mr
160
219
popup = popup.item(
161
220
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin for me" })
162
221
.icon(IconName::Frame)
163
.on_click(move |_, _, cx| pin_app.update(cx, |state, cx| state.toggle_call_pin(&pin_mri, cx))),
222
.on_click(move |_, _, cx| {
223
pin_app.update(cx, |state, cx| state.toggle_call_pin(&pin_mri, cx))
224
}),
164
225
);
165
226
if organizes {
166
227
let (spotlight_app, spotlight_mri) = (app.clone(), mri.to_owned());
167
228
popup = popup.item(
168
PopupMenuItem::new(if spotlighted { "Stop spotlight" } else { "Spotlight for everyone" })
169
.icon(IconName::Star)
170
.on_click(move |_, _, cx| spotlight_app.update(cx, |state, cx| state.toggle_call_spotlight(spotlight_mri.clone(), cx))),
229
PopupMenuItem::new(if spotlighted {
230
"Stop spotlight"
231
} else {
232
"Spotlight for everyone"
233
})
234
.icon(IconName::Star)
235
.on_click(move |_, _, cx| {
236
spotlight_app.update(cx, |state, cx| {
237
state.toggle_call_spotlight(spotlight_mri.clone(), cx)
238
})
239
}),
171
240
);
172
241
}
173
242
if organizes && !own {
@@ -176,55 +245,104 @@ pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mr
176
245
PopupMenuItem::new("Mute")
177
246
.icon(IconName::MicOff)
178
247
.disabled(muted)
179
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_call_participant(mute_mri.clone(), cx))),
248
.on_click(move |_, _, cx| {
249
mute_app.update(cx, |state, cx| {
250
state.mute_call_participant(mute_mri.clone(), cx)
251
})
252
}),
180
253
);
181
254
}
182
255
if organizes && raised {
183
256
let (hand_app, hand_mri) = (app.clone(), mri.to_owned());
184
popup = popup.item(
185
PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| hand_app.update(cx, |state, cx| state.lower_call_hand(hand_mri.clone(), cx))),
186
);
257
popup = popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {
258
hand_app.update(cx, |state, cx| state.lower_call_hand(hand_mri.clone(), cx))
259
}));
187
260
}
188
261
if organizes && !own {
189
262
let (remove_app, remove_mri, remove_name) = (app.clone(), mri.to_owned(), name.to_owned());
190
263
popup = popup.separator().item(
191
264
PopupMenuItem::new("Remove from meeting...")
192
265
.icon(IconName::Close)
193
.on_click(move |_, window, cx| confirm_remove(&remove_app, &remove_mri, &remove_name, window, cx)),
266
.on_click(move |_, window, cx| {
267
confirm_remove(&remove_app, &remove_mri, &remove_name, window, cx)
268
}),
194
269
);
195
270
}
196
271
popup
197
272
}
198
273
199
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {
200
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());
201
div().absolute().top(px(6.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(
202
Button::new(SharedString::from(format!("call-tile-more-{mri}")))
203
.icon(IconName::Ellipsis)
204
.ghost()
205
.xsmall()
206
.size(px(MORE_SIZE))
207
.rounded_full()
208
.bg(black().opacity(0.55))
209
.text_color(theme::white())
210
.tooltip("More")
211
.dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| tile_menu(popup, &app, &model, &mri_owned, &name, own)),
212
)
274
fn more_overlay(
275
app: &Entity<AppState>,
276
model: &CallModel,
277
mri: &str,
278
name: &str,
279
own: bool,
280
group: SharedString,
281
) -> Div {
282
let (app, model, mri_owned, name) =
283
(app.clone(), model.clone(), mri.to_owned(), name.to_owned());
284
div()
285
.absolute()
286
.top(px(6.))
287
.right(px(38.))
288
.opacity(0.)
289
.group_hover(group, |more| more.opacity(1.))
290
.child(
291
Button::new(SharedString::from(format!("call-tile-more-{mri}")))
292
.icon(IconName::Ellipsis)
293
.ghost()
294
.xsmall()
295
.size(px(MORE_SIZE))
296
.rounded_full()
297
.bg(black().opacity(0.55))
298
.text_color(theme::white())
299
.tooltip("More")
300
.dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
301
tile_menu(popup, &app, &model, &mri_owned, &name, own)
302
}),
303
)
213
304
}
214
305
215
306
/// Adds the right-click menu and a "..." button that shows while the pointer is over the tile.
216
pub fn attach_tile_menu(tile: Stateful<Div>, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> AnyElement {
307
pub fn attach_tile_menu(
308
tile: Stateful<Div>,
309
app: &Entity<AppState>,
310
model: &CallModel,
311
mri: &str,
312
name: &str,
313
own: bool,
314
) -> AnyElement {
217
315
let group = SharedString::from(format!("call-tile-group-{mri}"));
218
let (context_app, context_model, context_mri, context_name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());
316
let (context_app, context_model, context_mri, context_name) =
317
(app.clone(), model.clone(), mri.to_owned(), name.to_owned());
219
318
tile.group(group.clone())
220
319
.relative()
221
320
.child(more_overlay(app, model, mri, name, own, group))
222
.context_menu(move |popup, _, _| tile_menu(popup, &context_app, &context_model, &context_mri, &context_name, own))
321
.context_menu(move |popup, _, _| {
322
tile_menu(
323
popup,
324
&context_app,
325
&context_model,
326
&context_mri,
327
&context_name,
328
own,
329
)
330
})
223
331
.into_any_element()
224
332
}
225
333
226
pub fn with_tile_menu(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, tile: AnyElement) -> AnyElement {
227
let wrapper = div().id(SharedString::from(format!("call-tile-{mri}"))).flex_none().child(tile);
334
pub fn with_tile_menu(
335
app: &Entity<AppState>,
336
model: &CallModel,
337
mri: &str,
338
name: &str,
339
own: bool,
340
tile: AnyElement,
341
) -> AnyElement {
342
let wrapper = div()
343
.id(SharedString::from(format!("call-tile-{mri}")))
344
.flex_none()
345
.child(tile);
228
346
attach_tile_menu(wrapper, app, model, mri, name, own)
229
347
}
230
348
@@ -241,8 +359,15 @@ pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
241
359
.p_0()
242
360
.size(px(CONTROL_SIZE))
243
361
.rounded_full()
244
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))
245
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| more_menu(popup, &app, &model))
362
.child(round_control(
363
"call-more-face",
364
IconName::Ellipsis,
365
theme::surface_raised(),
366
theme::text(),
367
))
368
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
369
more_menu(popup, &app, &model)
370
})
246
371
.into_any_element(),
247
372
)
248
373
}
@@ -274,7 +399,8 @@ fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallMo
274
399
}
275
400
276
401
fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
277
let (mute_app, captions_app, record_app, board_app) = (app.clone(), app.clone(), app.clone(), app.clone());
402
let (mute_app, captions_app, record_app, board_app) =
403
(app.clone(), app.clone(), app.clone(), app.clone());
278
404
let captions_on = model.captions_on();
279
405
if model.organizes_meeting() {
280
406
popup = popup.item(
@@ -286,32 +412,52 @@ fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel
286
412
if model.can_record() {
287
413
let recording = model.recording;
288
414
popup = popup.item(
289
PopupMenuItem::new(if recording { "Stop recording" } else { "Start recording" })
290
.icon(IconName::Video)
291
.on_click(move |_, window, cx| {
292
if recording {
293
confirm_stop_recording(&record_app, window, cx);
294
} else {
295
record_app.update(cx, |state, cx| state.set_call_recording(true, cx));
296
}
297
}),
415
PopupMenuItem::new(if recording {
416
"Stop recording"
417
} else {
418
"Start recording"
419
})
420
.icon(IconName::Video)
421
.on_click(move |_, window, cx| {
422
if recording {
423
confirm_stop_recording(&record_app, window, cx);
424
} else {
425
record_app.update(cx, |state, cx| state.set_call_recording(true, cx));
426
}
427
}),
298
428
);
299
429
}
300
430
if model.can_open_whiteboard() {
301
431
popup = popup.item(
302
432
PopupMenuItem::new("Whiteboard")
303
433
.icon(IconName::Frame)
304
.on_click(move |_, _, cx| board_app.update(cx, |state, cx| state.open_call_whiteboard(cx))),
434
.on_click(move |_, _, cx| {
435
board_app.update(cx, |state, cx| state.open_call_whiteboard(cx))
436
}),
305
437
);
306
438
}
307
439
popup.item(
308
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })
309
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })
310
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),
440
PopupMenuItem::new(if captions_on {
441
"Turn off live captions"
442
} else {
443
"Turn on live captions"
444
})
445
.icon(if captions_on {
446
IconName::CaptionsOff
447
} else {
448
IconName::Captions
449
})
450
.on_click(move |_, _, cx| {
451
captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))
452
}),
311
453
)
312
454
}
313
455
314
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds: BackgroundMenu) -> Option<AnyElement> {
456
pub fn camera_menu_button(
457
app: &Entity<AppState>,
458
model: &CallModel,
459
backgrounds: BackgroundMenu,
460
) -> Option<AnyElement> {
315
461
if !model.can_use_camera() {
316
462
return None;
317
463
}
@@ -334,17 +480,30 @@ pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds
334
480
.justify_center()
335
481
.child(icon(IconName::ChevronUp, 16., theme::text())),
336
482
)
337
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))
483
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
484
camera_menu(popup, &app, &model, &backgrounds)
485
})
338
486
.into_any_element(),
339
487
)
340
488
}
341
489
342
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, backgrounds: &BackgroundMenu) -> PopupMenu {
490
fn camera_menu(
491
popup: PopupMenu,
492
app: &Entity<AppState>,
493
model: &CallModel,
494
backgrounds: &BackgroundMenu,
495
) -> PopupMenu {
343
496
let camera_app = app.clone();
344
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {
345
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));
346
});
347
let mut popup = popup.min_w(px(MENU_WIDTH)).item(PopupMenuItem::label("Camera"));
497
let cameras = super::call_view::device_items(
498
calling::camera_entries(&model.cameras),
499
&model.camera,
500
move |choice, cx| {
501
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));
502
},
503
);
504
let mut popup = popup
505
.min_w(px(MENU_WIDTH))
506
.item(PopupMenuItem::label("Camera"));
348
507
for item in cameras {
349
508
popup = popup.item(item);
350
509
}
@@ -385,7 +544,12 @@ pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
385
544
.opacity(fade)
386
545
.gap(px(8.))
387
546
.items_start()
388
.child(div().flex_none().font_weight(FontWeight::BOLD).child(format!("{}:", line.speaker)))
547
.child(
548
div()
549
.flex_none()
550
.font_weight(FontWeight::BOLD)
551
.child(format!("{}:", line.speaker)),
552
)
389
553
.child(div().flex_1().min_w_0().child(line.text.clone()))
390
554
})),
391
555
)
@@ -413,28 +577,58 @@ pub fn spotlight_chip() -> Div {
413
577
}
414
578
415
579
pub fn pin_chip() -> Div {
416
focus_chip("Pinned", IconName::Frame, hsla(0., 0., 0., 0.6), theme::white())
580
focus_chip(
581
"Pinned",
582
IconName::Frame,
583
hsla(0., 0., 0., 0.6),
584
theme::white(),
585
)
417
586
}
418
587
419
pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focus, now: Instant) -> Option<AnyElement> {
588
pub fn render_focus_stage(
589
app: &Entity<AppState>,
590
state: &AppState,
591
focus: &Focus,
592
now: Instant,
593
) -> Option<AnyElement> {
420
594
let call = state.call.as_ref()?;
421
595
let model = &call.model;
422
596
let me = state.directory.me.as_ref();
423
597
let (name, user_id, speaking, muted, key) = if focus.own {
424
("You".to_owned(), me.map(|person| person.user_id.clone()), model.local_speaking, model.muted, VideoKey::LocalCamera)
598
(
599
"You".to_owned(),
600
me.map(|person| person.user_id.clone()),
601
model.local_speaking,
602
model.muted,
603
VideoKey::LocalCamera,
604
)
425
605
} else {
426
606
let tile = model.tiles.iter().find(|tile| tile.mri == focus.mri)?;
427
(tile.name.clone(), tile.user_id.clone(), model.tile_speaking(tile), tile.muted, VideoKey::Person(tile.mri.clone()))
607
(
608
tile.name.clone(),
609
tile.user_id.clone(),
610
model.tile_speaking(tile),
611
tile.muted,
612
VideoKey::Person(tile.mri.clone()),
613
)
428
614
};
429
615
let image: Option<Arc<RenderImage>> = call.pictures.live(&key, now);
430
616
let picture = match image {
431
Some(image) => img(ImageSource::Render(image)).size_full().object_fit(ObjectFit::Contain).into_any_element(),
617
Some(image) => img(ImageSource::Render(image))
618
.size_full()
619
.object_fit(ObjectFit::Contain)
620
.into_any_element(),
432
621
None => div()
433
622
.size_full()
434
623
.flex()
435
624
.items_center()
436
625
.justify_center()
437
.child(person_avatar(&state.directory, user_id.as_deref(), &name, FOCUS_AVATAR))
626
.child(person_avatar(
627
&state.directory,
628
user_id.as_deref(),
629
&name,
630
FOCUS_AVATAR,
631
))
438
632
.into_any_element(),
439
633
};
440
634
let stage = div()
@@ -447,7 +641,11 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu
447
641
.rounded(px(FOCUS_RADIUS))
448
642
.bg(hsla(0., 0., 0.04, 1.))
449
643
.border_2()
450
.border_color(if speaking { theme::green() } else { transparent_black() })
644
.border_color(if speaking {
645
theme::green()
646
} else {
647
transparent_black()
648
})
451
649
.child(picture)
452
650
.child(
453
651
h_flex()
@@ -472,9 +670,13 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu
472
670
.text_size(px(13.))
473
671
.font_weight(FontWeight::SEMIBOLD)
474
672
.child(name.clone())
475
.when(muted, |plate| plate.child(icon(IconName::MicOff, 14., theme::red()))),
673
.when(muted, |plate| {
674
plate.child(icon(IconName::MicOff, 14., theme::red()))
675
}),
476
676
);
477
Some(attach_tile_menu(stage, app, model, &focus.mri, &name, focus.own))
677
Some(attach_tile_menu(
678
stage, app, model, &focus.mri, &name, focus.own,
679
))
478
680
}
479
681
480
682
pub fn captions_state_hint(model: &CallModel) -> Option<&'static str> {
@@ -12,7 +12,9 @@ use gpui_kit::prelude::FluentBuilder as _;12
use gpui_kit::*;12
use gpui_kit::*;13
13
14
use super::avatar::person_avatar;14
use super::avatar::person_avatar;15
use super::call_extras::{BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker};15
use super::call_extras::{16
BackgroundMenu, background_items, confirm_stop_recording, open_transfer_picker,17
};16
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};18
use super::call_view::{BANNER_HEIGHT, CONTROL_SIZE, MENU_WIDTH, round_control};17
use super::widgets::icon;19
use super::widgets::icon;18
use crate::app_state::AppState;20
use crate::app_state::AppState;@@ -40,7 +42,11 @@ fn dark_text() -> Hsla {40
}42
}41
43
42
pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {44
pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {43
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (dark_text().opacity(0.12), dark_text()) };45
let (background, foreground) = if filled {46
(dark_text(), theme::white())47
} else {48
(dark_text().opacity(0.12), dark_text())49
};44
div()50
div()45
.id(id)51
.id(id)46
.h(px(PILL_HEIGHT))52
.h(px(PILL_HEIGHT))@@ -66,33 +72,54 @@ pub fn lobby_text(waiting: usize) -> String {66
}72
}67
73
68
fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {74
fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {69
v_flex().w(px(LOBBY_LIST_WIDTH)).gap(px(6.)).children(guests.iter().map(|(mri, name)| {75
v_flex()70
let (admit_app, deny_app) = (app.clone(), app.clone());76
.w(px(LOBBY_LIST_WIDTH))71
let (admit_mri, deny_mri) = (mri.clone(), mri.clone());77
.gap(px(6.))72
h_flex()78
.children(guests.iter().map(|(mri, name)| {73
.w_full()79
let (admit_app, deny_app) = (app.clone(), app.clone());74
.gap(px(8.))80
let (admit_mri, deny_mri) = (mri.clone(), mri.clone());75
.items_center()81
h_flex()76
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(truncated(name, LOBBY_NAME_LIMIT)))82
.w_full()77
.child(83
.gap(px(8.))78
Button::new(SharedString::from(format!("lobby-admit-{mri}")))84
.items_center()79
.label("Admit")85
.child(80
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))),86
div()81
)87
.flex_1()82
.child(88
.min_w_0()83
Button::new(SharedString::from(format!("lobby-deny-{mri}")))89
.truncate()84
.label("Deny")90
.text_size(px(14.))85
.ghost()91
.child(truncated(name, LOBBY_NAME_LIMIT)),86
.on_click(move |_, _, cx| deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))),92
)87
)93
.child(88
}))94
Button::new(SharedString::from(format!("lobby-admit-{mri}")))95
.label("Admit")96
.on_click(move |_, _, cx| {97
admit_app.update(cx, |state, cx| {98
state.admit_call_guest(admit_mri.clone(), cx)99
})100
}),101
)102
.child(103
Button::new(SharedString::from(format!("lobby-deny-{mri}")))104
.label("Deny")105
.ghost()106
.on_click(move |_, _, cx| {107
deny_app108
.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))109
}),110
)111
}))89
}112
}90
113
91
pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {114
pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElement> {92
if !model.can_admit() {115
if !model.can_admit() {93
return None;116
return None;94
}117
}95
let guests: Vec<(String, String)> = model.lobby_guests().into_iter().map(|tile| (tile.mri.clone(), tile.name.clone())).collect();118
let guests: Vec<(String, String)> = model119
.lobby_guests()120
.into_iter()121
.map(|tile| (tile.mri.clone(), tile.name.clone()))122
.collect();96
if guests.is_empty() {123
if guests.is_empty() {97
return None;124
return None;98
}125
}@@ -117,29 +144,50 @@ pub fn lobby_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElem117
Popover::new("call-lobby-popover")144
Popover::new("call-lobby-popover")118
.anchor(Anchor::TopLeft)145
.anchor(Anchor::TopLeft)119
.offset(px(8.))146
.offset(px(8.))120
.trigger(Button::new("call-lobby-view").ghost().p_0().h(px(PILL_HEIGHT)).rounded_full().child(pill("call-lobby-view-face", "View", false)))147
.trigger(148
Button::new("call-lobby-view")149
.ghost()150
.p_0()151
.h(px(PILL_HEIGHT))152
.rounded_full()153
.child(pill("call-lobby-view-face", "View", false)),154
)121
.content(move |_, _, _| lobby_list(&list_app, &guests)),155
.content(move |_, _, _| lobby_list(&list_app, &guests)),122
)156
)123
.child(157
.child(124
pill("call-lobby-admit-all", "Admit all", true)158
pill("call-lobby-admit-all", "Admit all", true).on_click(move |_, _, cx| {125
.on_click(move |_, _, cx| admit_app.update(cx, |state, cx| state.admit_all_call_guests(cx))),159
admit_app.update(cx, |state, cx| state.admit_all_call_guests(cx))160
}),126
)161
)127
.into_any_element(),162
.into_any_element(),128
)163
)129
}164
}130
165
131
fn confirm_remove(app: &Entity<AppState>, mri: &str, name: &str, window: &mut Window, cx: &mut App) {166
fn confirm_remove(167
app: &Entity<AppState>,168
mri: &str,169
name: &str,170
window: &mut Window,171
cx: &mut App,172
) {132
let app = app.clone();173
let app = app.clone();133
let mri = mri.to_owned();174
let mri = mri.to_owned();134
let heading = format!("Remove {} from the meeting?", truncated(name, NAME_LIMIT));175
let heading = format!("Remove {} from the meeting?", truncated(name, NAME_LIMIT));135
window.open_alert_dialog(cx, move |alert, _, _| {176
window.open_alert_dialog(cx, move |alert, _, _| {136
let app = app.clone();177
let app = app.clone();137
let mri = mri.clone();178
let mri = mri.clone();138
let cancel = Button::new("remove-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));179
let cancel = Button::new("remove-cancel")139
let remove = Button::new("remove-confirm").label("Remove").danger().on_click(move |_, window, cx| {180
.label("Cancel")140
app.update(cx, |state, cx| state.remove_call_participant(mri.clone(), cx));181
.on_click(|_, window, cx| window.close_dialog(cx));141
window.close_dialog(cx);182
let remove = Button::new("remove-confirm")142
});183
.label("Remove")184
.danger()185
.on_click(move |_, window, cx| {186
app.update(cx, |state, cx| {187
state.remove_call_participant(mri.clone(), cx)188
});189
window.close_dialog(cx);190
});143
alert191
alert144
.title(heading.clone())192
.title(heading.clone())145
.description("They leave the call and can only come back if they join again.")193
.description("They leave the call and can only come back if they join again.")@@ -148,11 +196,22 @@ fn confirm_remove(app: &Entity<AppState>, mri: &str, name: &str, window: &mut Wi148
});196
});149
}197
}150
198
151
pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> PopupMenu {199
pub fn tile_menu(200
popup: PopupMenu,201
app: &Entity<AppState>,202
model: &CallModel,203
mri: &str,204
name: &str,205
own: bool,206
) -> PopupMenu {152
let pinned = model.is_pinned(mri);207
let pinned = model.is_pinned(mri);153
let spotlighted = model.is_spotlighted(mri);208
let spotlighted = model.is_spotlighted(mri);154
let organizes = model.organizes_meeting();209
let organizes = model.organizes_meeting();155
let raised = !own && model.tiles.iter().any(|tile| tile.mri == mri && tile.hand.is_some());210
let raised = !own211
&& model212
.tiles213
.iter()214
.any(|tile| tile.mri == mri && tile.hand.is_some());156
let muted = model.tiles.iter().any(|tile| tile.mri == mri && tile.muted);215
let muted = model.tiles.iter().any(|tile| tile.mri == mri && tile.muted);157
let mut popup = popup.min_w(px(MENU_WIDTH));216
let mut popup = popup.min_w(px(MENU_WIDTH));158
let pin_app = app.clone();217
let pin_app = app.clone();@@ -160,14 +219,24 @@ pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mr160
popup = popup.item(219
popup = popup.item(161
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin for me" })220
PopupMenuItem::new(if pinned { "Unpin" } else { "Pin for me" })162
.icon(IconName::Frame)221
.icon(IconName::Frame)163
.on_click(move |_, _, cx| pin_app.update(cx, |state, cx| state.toggle_call_pin(&pin_mri, cx))),222
.on_click(move |_, _, cx| {223
pin_app.update(cx, |state, cx| state.toggle_call_pin(&pin_mri, cx))224
}),164
);225
);165
if organizes {226
if organizes {166
let (spotlight_app, spotlight_mri) = (app.clone(), mri.to_owned());227
let (spotlight_app, spotlight_mri) = (app.clone(), mri.to_owned());167
popup = popup.item(228
popup = popup.item(168
PopupMenuItem::new(if spotlighted { "Stop spotlight" } else { "Spotlight for everyone" })229
PopupMenuItem::new(if spotlighted {169
.icon(IconName::Star)230
"Stop spotlight"170
.on_click(move |_, _, cx| spotlight_app.update(cx, |state, cx| state.toggle_call_spotlight(spotlight_mri.clone(), cx))),231
} else {232
"Spotlight for everyone"233
})234
.icon(IconName::Star)235
.on_click(move |_, _, cx| {236
spotlight_app.update(cx, |state, cx| {237
state.toggle_call_spotlight(spotlight_mri.clone(), cx)238
})239
}),171
);240
);172
}241
}173
if organizes && !own {242
if organizes && !own {@@ -176,55 +245,104 @@ pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mr176
PopupMenuItem::new("Mute")245
PopupMenuItem::new("Mute")177
.icon(IconName::MicOff)246
.icon(IconName::MicOff)178
.disabled(muted)247
.disabled(muted)179
.on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_call_participant(mute_mri.clone(), cx))),248
.on_click(move |_, _, cx| {249
mute_app.update(cx, |state, cx| {250
state.mute_call_participant(mute_mri.clone(), cx)251
})252
}),180
);253
);181
}254
}182
if organizes && raised {255
if organizes && raised {183
let (hand_app, hand_mri) = (app.clone(), mri.to_owned());256
let (hand_app, hand_mri) = (app.clone(), mri.to_owned());184
popup = popup.item(257
popup = popup.item(PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| {185
PopupMenuItem::new("Lower hand").on_click(move |_, _, cx| hand_app.update(cx, |state, cx| state.lower_call_hand(hand_mri.clone(), cx))),258
hand_app.update(cx, |state, cx| state.lower_call_hand(hand_mri.clone(), cx))186
);259
}));187
}260
}188
if organizes && !own {261
if organizes && !own {189
let (remove_app, remove_mri, remove_name) = (app.clone(), mri.to_owned(), name.to_owned());262
let (remove_app, remove_mri, remove_name) = (app.clone(), mri.to_owned(), name.to_owned());190
popup = popup.separator().item(263
popup = popup.separator().item(191
PopupMenuItem::new("Remove from meeting...")264
PopupMenuItem::new("Remove from meeting...")192
.icon(IconName::Close)265
.icon(IconName::Close)193
.on_click(move |_, window, cx| confirm_remove(&remove_app, &remove_mri, &remove_name, window, cx)),266
.on_click(move |_, window, cx| {267
confirm_remove(&remove_app, &remove_mri, &remove_name, window, cx)268
}),194
);269
);195
}270
}196
popup271
popup197
}272
}198
273
199
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {274
fn more_overlay(200
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());275
app: &Entity<AppState>,201
div().absolute().top(px(6.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(276
model: &CallModel,202
Button::new(SharedString::from(format!("call-tile-more-{mri}")))277
mri: &str,203
.icon(IconName::Ellipsis)278
name: &str,204
.ghost()279
own: bool,205
.xsmall()280
group: SharedString,206
.size(px(MORE_SIZE))281
) -> Div {207
.rounded_full()282
let (app, model, mri_owned, name) =208
.bg(black().opacity(0.55))283
(app.clone(), model.clone(), mri.to_owned(), name.to_owned());209
.text_color(theme::white())284
div()210
.tooltip("More")285
.absolute()211
.dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| tile_menu(popup, &app, &model, &mri_owned, &name, own)),286
.top(px(6.))212
)287
.right(px(38.))288
.opacity(0.)289
.group_hover(group, |more| more.opacity(1.))290
.child(291
Button::new(SharedString::from(format!("call-tile-more-{mri}")))292
.icon(IconName::Ellipsis)293
.ghost()294
.xsmall()295
.size(px(MORE_SIZE))296
.rounded_full()297
.bg(black().opacity(0.55))298
.text_color(theme::white())299
.tooltip("More")300
.dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {301
tile_menu(popup, &app, &model, &mri_owned, &name, own)302
}),303
)213
}304
}214
305
215
/// Adds the right-click menu and a "..." button that shows while the pointer is over the tile.306
/// Adds the right-click menu and a "..." button that shows while the pointer is over the tile.216
pub fn attach_tile_menu(tile: Stateful<Div>, app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool) -> AnyElement {307
pub fn attach_tile_menu(308
tile: Stateful<Div>,309
app: &Entity<AppState>,310
model: &CallModel,311
mri: &str,312
name: &str,313
own: bool,314
) -> AnyElement {217
let group = SharedString::from(format!("call-tile-group-{mri}"));315
let group = SharedString::from(format!("call-tile-group-{mri}"));218
let (context_app, context_model, context_mri, context_name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());316
let (context_app, context_model, context_mri, context_name) =317
(app.clone(), model.clone(), mri.to_owned(), name.to_owned());219
tile.group(group.clone())318
tile.group(group.clone())220
.relative()319
.relative()221
.child(more_overlay(app, model, mri, name, own, group))320
.child(more_overlay(app, model, mri, name, own, group))222
.context_menu(move |popup, _, _| tile_menu(popup, &context_app, &context_model, &context_mri, &context_name, own))321
.context_menu(move |popup, _, _| {322
tile_menu(323
popup,324
&context_app,325
&context_model,326
&context_mri,327
&context_name,328
own,329
)330
})223
.into_any_element()331
.into_any_element()224
}332
}225
333
226
pub fn with_tile_menu(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, tile: AnyElement) -> AnyElement {334
pub fn with_tile_menu(227
let wrapper = div().id(SharedString::from(format!("call-tile-{mri}"))).flex_none().child(tile);335
app: &Entity<AppState>,336
model: &CallModel,337
mri: &str,338
name: &str,339
own: bool,340
tile: AnyElement,341
) -> AnyElement {342
let wrapper = div()343
.id(SharedString::from(format!("call-tile-{mri}")))344
.flex_none()345
.child(tile);228
attach_tile_menu(wrapper, app, model, mri, name, own)346
attach_tile_menu(wrapper, app, model, mri, name, own)229
}347
}230
348
@@ -241,8 +359,15 @@ pub fn more_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme241
.p_0()359
.p_0()242
.size(px(CONTROL_SIZE))360
.size(px(CONTROL_SIZE))243
.rounded_full()361
.rounded_full()244
.child(round_control("call-more-face", IconName::Ellipsis, theme::surface_raised(), theme::text()))362
.child(round_control(245
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| more_menu(popup, &app, &model))363
"call-more-face",364
IconName::Ellipsis,365
theme::surface_raised(),366
theme::text(),367
))368
.dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {369
more_menu(popup, &app, &model)370
})246
.into_any_element(),371
.into_any_element(),247
)372
)248
}373
}@@ -274,7 +399,8 @@ fn one_to_one_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallMo274
}399
}275
400
276
fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {401
fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {277
let (mute_app, captions_app, record_app, board_app) = (app.clone(), app.clone(), app.clone(), app.clone());402
let (mute_app, captions_app, record_app, board_app) =403
(app.clone(), app.clone(), app.clone(), app.clone());278
let captions_on = model.captions_on();404
let captions_on = model.captions_on();279
if model.organizes_meeting() {405
if model.organizes_meeting() {280
popup = popup.item(406
popup = popup.item(@@ -286,32 +412,52 @@ fn meeting_items(mut popup: PopupMenu, app: &Entity<AppState>, model: &CallModel286
if model.can_record() {412
if model.can_record() {287
let recording = model.recording;413
let recording = model.recording;288
popup = popup.item(414
popup = popup.item(289
PopupMenuItem::new(if recording { "Stop recording" } else { "Start recording" })415
PopupMenuItem::new(if recording {290
.icon(IconName::Video)416
"Stop recording"291
.on_click(move |_, window, cx| {417
} else {292
if recording {418
"Start recording"293
confirm_stop_recording(&record_app, window, cx);419
})294
} else {420
.icon(IconName::Video)295
record_app.update(cx, |state, cx| state.set_call_recording(true, cx));421
.on_click(move |_, window, cx| {296
}422
if recording {297
}),423
confirm_stop_recording(&record_app, window, cx);424
} else {425
record_app.update(cx, |state, cx| state.set_call_recording(true, cx));426
}427
}),298
);428
);299
}429
}300
if model.can_open_whiteboard() {430
if model.can_open_whiteboard() {301
popup = popup.item(431
popup = popup.item(302
PopupMenuItem::new("Whiteboard")432
PopupMenuItem::new("Whiteboard")303
.icon(IconName::Frame)433
.icon(IconName::Frame)304
.on_click(move |_, _, cx| board_app.update(cx, |state, cx| state.open_call_whiteboard(cx))),434
.on_click(move |_, _, cx| {435
board_app.update(cx, |state, cx| state.open_call_whiteboard(cx))436
}),305
);437
);306
}438
}307
popup.item(439
popup.item(308
PopupMenuItem::new(if captions_on { "Turn off live captions" } else { "Turn on live captions" })440
PopupMenuItem::new(if captions_on {309
.icon(if captions_on { IconName::CaptionsOff } else { IconName::Captions })441
"Turn off live captions"310
.on_click(move |_, _, cx| captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))),442
} else {443
"Turn on live captions"444
})445
.icon(if captions_on {446
IconName::CaptionsOff447
} else {448
IconName::Captions449
})450
.on_click(move |_, _, cx| {451
captions_app.update(cx, |state, cx| state.toggle_call_captions(cx))452
}),311
)453
)312
}454
}313
455
314
pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds: BackgroundMenu) -> Option<AnyElement> {456
pub fn camera_menu_button(457
app: &Entity<AppState>,458
model: &CallModel,459
backgrounds: BackgroundMenu,460
) -> Option<AnyElement> {315
if !model.can_use_camera() {461
if !model.can_use_camera() {316
return None;462
return None;317
}463
}@@ -334,17 +480,30 @@ pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds334
.justify_center()480
.justify_center()335
.child(icon(IconName::ChevronUp, 16., theme::text())),481
.child(icon(IconName::ChevronUp, 16., theme::text())),336
)482
)337
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))483
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {484
camera_menu(popup, &app, &model, &backgrounds)485
})338
.into_any_element(),486
.into_any_element(),339
)487
)340
}488
}341
489
342
fn camera_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, backgrounds: &BackgroundMenu) -> PopupMenu {490
fn camera_menu(491
popup: PopupMenu,492
app: &Entity<AppState>,493
model: &CallModel,494
backgrounds: &BackgroundMenu,495
) -> PopupMenu {343
let camera_app = app.clone();496
let camera_app = app.clone();344
let cameras = super::call_view::device_items(calling::camera_entries(&model.cameras), &model.camera, move |choice, cx| {497
let cameras = super::call_view::device_items(345
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));498
calling::camera_entries(&model.cameras),346
});499
&model.camera,347
let mut popup = popup.min_w(px(MENU_WIDTH)).item(PopupMenuItem::label("Camera"));500
move |choice, cx| {501
camera_app.update(cx, |state, cx| state.select_call_camera(choice, cx));502
},503
);504
let mut popup = popup505
.min_w(px(MENU_WIDTH))506
.item(PopupMenuItem::label("Camera"));348
for item in cameras {507
for item in cameras {349
popup = popup.item(item);508
popup = popup.item(item);350
}509
}@@ -385,7 +544,12 @@ pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {385
.opacity(fade)544
.opacity(fade)386
.gap(px(8.))545
.gap(px(8.))387
.items_start()546
.items_start()388
.child(div().flex_none().font_weight(FontWeight::BOLD).child(format!("{}:", line.speaker)))547
.child(548
div()549
.flex_none()550
.font_weight(FontWeight::BOLD)551
.child(format!("{}:", line.speaker)),552
)389
.child(div().flex_1().min_w_0().child(line.text.clone()))553
.child(div().flex_1().min_w_0().child(line.text.clone()))390
})),554
})),391
)555
)@@ -413,28 +577,58 @@ pub fn spotlight_chip() -> Div {413
}577
}414
578
415
pub fn pin_chip() -> Div {579
pub fn pin_chip() -> Div {416
focus_chip("Pinned", IconName::Frame, hsla(0., 0., 0., 0.6), theme::white())580
focus_chip(581
"Pinned",582
IconName::Frame,583
hsla(0., 0., 0., 0.6),584
theme::white(),585
)417
}586
}418
587
419
pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focus, now: Instant) -> Option<AnyElement> {588
pub fn render_focus_stage(589
app: &Entity<AppState>,590
state: &AppState,591
focus: &Focus,592
now: Instant,593
) -> Option<AnyElement> {420
let call = state.call.as_ref()?;594
let call = state.call.as_ref()?;421
let model = &call.model;595
let model = &call.model;422
let me = state.directory.me.as_ref();596
let me = state.directory.me.as_ref();423
let (name, user_id, speaking, muted, key) = if focus.own {597
let (name, user_id, speaking, muted, key) = if focus.own {424
("You".to_owned(), me.map(|person| person.user_id.clone()), model.local_speaking, model.muted, VideoKey::LocalCamera)598
(599
"You".to_owned(),600
me.map(|person| person.user_id.clone()),601
model.local_speaking,602
model.muted,603
VideoKey::LocalCamera,604
)425
} else {605
} else {426
let tile = model.tiles.iter().find(|tile| tile.mri == focus.mri)?;606
let tile = model.tiles.iter().find(|tile| tile.mri == focus.mri)?;427
(tile.name.clone(), tile.user_id.clone(), model.tile_speaking(tile), tile.muted, VideoKey::Person(tile.mri.clone()))607
(608
tile.name.clone(),609
tile.user_id.clone(),610
model.tile_speaking(tile),611
tile.muted,612
VideoKey::Person(tile.mri.clone()),613
)428
};614
};429
let image: Option<Arc<RenderImage>> = call.pictures.live(&key, now);615
let image: Option<Arc<RenderImage>> = call.pictures.live(&key, now);430
let picture = match image {616
let picture = match image {431
Some(image) => img(ImageSource::Render(image)).size_full().object_fit(ObjectFit::Contain).into_any_element(),617
Some(image) => img(ImageSource::Render(image))618
.size_full()619
.object_fit(ObjectFit::Contain)620
.into_any_element(),432
None => div()621
None => div()433
.size_full()622
.size_full()434
.flex()623
.flex()435
.items_center()624
.items_center()436
.justify_center()625
.justify_center()437
.child(person_avatar(&state.directory, user_id.as_deref(), &name, FOCUS_AVATAR))626
.child(person_avatar(627
&state.directory,628
user_id.as_deref(),629
&name,630
FOCUS_AVATAR,631
))438
.into_any_element(),632
.into_any_element(),439
};633
};440
let stage = div()634
let stage = div()@@ -447,7 +641,11 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu447
.rounded(px(FOCUS_RADIUS))641
.rounded(px(FOCUS_RADIUS))448
.bg(hsla(0., 0., 0.04, 1.))642
.bg(hsla(0., 0., 0.04, 1.))449
.border_2()643
.border_2()450
.border_color(if speaking { theme::green() } else { transparent_black() })644
.border_color(if speaking {645
theme::green()646
} else {647
transparent_black()648
})451
.child(picture)649
.child(picture)452
.child(650
.child(453
h_flex()651
h_flex()@@ -472,9 +670,13 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu472
.text_size(px(13.))670
.text_size(px(13.))473
.font_weight(FontWeight::SEMIBOLD)671
.font_weight(FontWeight::SEMIBOLD)474
.child(name.clone())672
.child(name.clone())475
.when(muted, |plate| plate.child(icon(IconName::MicOff, 14., theme::red()))),673
.when(muted, |plate| {674
plate.child(icon(IconName::MicOff, 14., theme::red()))675
}),476
);676
);477
Some(attach_tile_menu(stage, app, model, &focus.mri, &name, focus.own))677
Some(attach_tile_menu(678
stage, app, model, &focus.mri, &name, focus.own,679
))478
}680
}479
681
480
pub fn captions_state_hint(model: &CallModel) -> Option<&'static str> {682
pub fn captions_state_hint(model: &CallModel) -> Option<&'static str> {@@ -58,14 +58,22 @@ fn picture(image: Option<Arc<RenderImage>>) -> AnyElement {
58
58
}
59
59
}
60
60
61
pub fn render_stage(app: &Entity<AppState>, state: &AppState, fullscreen: bool) -> Option<AnyElement> {
61
pub fn render_stage(
62
app: &Entity<AppState>,
63
state: &AppState,
64
fullscreen: bool,
65
) -> Option<AnyElement> {
62
66
let call = state.call.as_ref()?;
63
67
let label = call.model.sharing_label()?;
64
68
let image = call.pictures.live(&VideoKey::Screen, Instant::now());
65
69
let toggle_app = app.clone();
66
70
Some(
67
71
div()
68
.id(if fullscreen { "call-stage-full" } else { "call-stage" })
72
.id(if fullscreen {
73
"call-stage-full"
74
} else {
75
"call-stage"
76
})
69
77
.relative()
70
78
.flex_1()
71
79
.min_w_0()
@@ -58,14 +58,22 @@ fn picture(image: Option<Arc<RenderImage>>) -> AnyElement {58
}58
}59
}59
}60
60
61
pub fn render_stage(app: &Entity<AppState>, state: &AppState, fullscreen: bool) -> Option<AnyElement> {61
pub fn render_stage(62
app: &Entity<AppState>,63
state: &AppState,64
fullscreen: bool,65
) -> Option<AnyElement> {62
let call = state.call.as_ref()?;66
let call = state.call.as_ref()?;63
let label = call.model.sharing_label()?;67
let label = call.model.sharing_label()?;64
let image = call.pictures.live(&VideoKey::Screen, Instant::now());68
let image = call.pictures.live(&VideoKey::Screen, Instant::now());65
let toggle_app = app.clone();69
let toggle_app = app.clone();66
Some(70
Some(67
div()71
div()68
.id(if fullscreen { "call-stage-full" } else { "call-stage" })72
.id(if fullscreen {73
"call-stage-full"74
} else {75
"call-stage"76
})69
.relative()77
.relative()70
.flex_1()78
.flex_1()71
.min_w_0()79
.min_w_0()@@ -16,16 +16,25 @@ use gpui_kit::prelude::FluentBuilder as _;
16
16
use gpui_kit::*;
17
17
18
18
use super::avatar::person_avatar;
19
use super::call_extras::{BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button, room_chip, whiteboard_stage};
20
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};
19
use super::call_extras::{
20
BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
21
room_chip, whiteboard_stage,
22
};
23
use super::call_organizer::{
24
camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip,
25
render_focus_stage, spotlight_chip, with_tile_menu,
26
};
21
27
use super::call_stage::render_stage;
22
28
use super::conversation::ConversationView;
23
29
use super::shell::ISLAND_GAP;
24
30
use super::widgets::{count_badge, icon};
25
31
use crate::app_state::AppState;
26
use crate::call::TileSize;
27
use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};
28
32
use crate::call::REACTION_SHOWN;
33
use crate::call::TileSize;
34
use crate::call::{
35
CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout,
36
tile_size,
37
};
29
38
use crate::rows::reaction_glyph as chat_reaction_glyph;
30
39
use crate::theme;
31
40
@@ -91,7 +100,11 @@ fn hand_badge(position: usize, own: bool) -> Div {
91
100
.text_color(hsla(0., 0., 0.08, 1.))
92
101
.text_size(px(12.))
93
102
.font_weight(FontWeight::SEMIBOLD)
94
.child(if own { "Hand raised".to_owned() } else { format!("Hand {position}") })
103
.child(if own {
104
"Hand raised".to_owned()
105
} else {
106
format!("Hand {position}")
107
})
95
108
}
96
109
97
110
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
@@ -112,7 +125,8 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
112
125
Animation::new(REACTION_SHOWN),
113
126
|chip, delta| {
114
127
let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);
115
chip.bottom(px(32. + REACTION_RISE * delta)).opacity(1. - fade)
128
chip.bottom(px(32. + REACTION_RISE * delta))
129
.opacity(1. - fade)
116
130
},
117
131
)
118
132
.into_any_element()
@@ -130,7 +144,9 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
130
144
.when(extras.pinned, |row| row.child(pin_chip()))
131
145
.into_any_element()
132
146
});
133
let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));
147
let reaction = extras
148
.reaction
149
.map(|(reaction, serial)| reaction_chip(reaction, serial));
134
150
badges.into_iter().chain(reaction).collect()
135
151
}
136
152
@@ -161,8 +177,13 @@ pub fn pulsing(element: impl IntoElement + 'static, id: &'static str) -> AnyElem
161
177
}
162
178
163
179
fn blinking(element: impl IntoElement + 'static) -> AnyElement {
164
let dimmed = SystemTime::now().duration_since(UNIX_EPOCH).is_ok_and(|elapsed| (elapsed.as_millis() / BLINK_HALF_PERIOD.as_millis()) % 2 == 1);
165
div().child(element).opacity(if dimmed { BLINK_DIMMED_OPACITY } else { 1. }).into_any_element()
180
let dimmed = SystemTime::now()
181
.duration_since(UNIX_EPOCH)
182
.is_ok_and(|elapsed| (elapsed.as_millis() / BLINK_HALF_PERIOD.as_millis()) % 2 == 1);
183
div()
184
.child(element)
185
.opacity(if dimmed { BLINK_DIMMED_OPACITY } else { 1. })
186
.into_any_element()
166
187
}
167
188
168
189
fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
@@ -192,7 +213,14 @@ fn mute_badge() -> Div {
192
213
.child(icon(IconName::MicOff, 13., theme::white()))
193
214
}
194
215
195
fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: bool, muted: bool, extras: &TileExtras) -> Div {
216
fn video_tile(
217
size: TileSize,
218
image: Arc<RenderImage>,
219
name: &str,
220
speaking: bool,
221
muted: bool,
222
extras: &TileExtras,
223
) -> Div {
196
224
div()
197
225
.relative()
198
226
.w(px(size.width))
@@ -202,7 +230,11 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo
202
230
.rounded(px(TILE_RADIUS))
203
231
.bg(theme::row_hover())
204
232
.border_2()
205
.border_color(if speaking { theme::green() } else { transparent_black() })
233
.border_color(if speaking {
234
theme::green()
235
} else {
236
transparent_black()
237
})
206
238
.child(
207
239
img(ImageSource::Render(image))
208
240
.size_full()
@@ -309,11 +341,21 @@ fn control_shell(id: &'static str, background: Hsla) -> Stateful<Div> {
309
341
.hover(|button| button.opacity(0.85))
310
342
}
311
343
312
pub(super) fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {
344
pub(super) fn round_control(
345
id: &'static str,
346
glyph: IconName,
347
background: Hsla,
348
foreground: Hsla,
349
) -> Stateful<Div> {
313
350
control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))
314
351
}
315
352
316
pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, size: f32) -> Stateful<Div> {
353
pub fn mute_button(
354
app: &Entity<AppState>,
355
model: &CallModel,
356
id: &'static str,
357
size: f32,
358
) -> Stateful<Div> {
317
359
let (glyph, background, foreground) = if model.muted {
318
360
(IconName::MicOff, theme::red(), theme::white())
319
361
} else {
@@ -333,8 +375,17 @@ pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str,
333
375
})
334
376
}
335
377
336
pub fn leave_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, compact: bool) -> Stateful<Div> {
337
let label = if model.is_connecting() { "Cancel" } else { "Leave" };
378
pub fn leave_button(
379
app: &Entity<AppState>,
380
model: &CallModel,
381
id: &'static str,
382
compact: bool,
383
) -> Stateful<Div> {
384
let label = if model.is_connecting() {
385
"Cancel"
386
} else {
387
"Leave"
388
};
338
389
let app = app.clone();
339
390
h_flex()
340
391
.id(id)
@@ -351,7 +402,11 @@ pub fn leave_button(app: &Entity<AppState>, model: &CallModel, id: &'static str,
351
402
.font_weight(FontWeight::SEMIBOLD)
352
403
.cursor_pointer()
353
404
.hover(|button| button.opacity(0.85))
354
.child(icon(IconName::PhoneOff, if compact { 14. } else { 18. }, theme::white()))
405
.child(icon(
406
IconName::PhoneOff,
407
if compact { 14. } else { 18. },
408
theme::white(),
409
))
355
410
.child(label)
356
411
.on_click(move |_, _, cx| {
357
412
cx.stop_propagation();
@@ -394,21 +449,33 @@ fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
394
449
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
395
450
}
396
451
397
fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, sound: bool) -> PopupMenu {
452
fn share_items(
453
popup: PopupMenu,
454
app: &Entity<AppState>,
455
model: &CallModel,
456
sound: bool,
457
) -> PopupMenu {
398
458
let screens = model.screens();
399
459
let single_screen = screens.len() == 1;
400
let mut popup = popup.min_w(px(MENU_WIDTH)).item(sound_switch_item(app, sound)).separator();
460
let mut popup = popup
461
.min_w(px(MENU_WIDTH))
462
.item(sound_switch_item(app, sound))
463
.separator();
401
464
for (index, source) in screens.into_iter().enumerate() {
402
let label = if single_screen { "Share entire screen".to_owned() } else { format!("Share screen {}", index + 1) };
465
let label = if single_screen {
466
"Share entire screen".to_owned()
467
} else {
468
format!("Share screen {}", index + 1)
469
};
403
470
let source = source.clone();
404
471
let app = app.clone();
405
popup = popup.item(
406
PopupMenuItem::new(label)
407
.icon(IconName::Monitor)
408
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))),
409
);
472
popup = popup.item(PopupMenuItem::new(label).icon(IconName::Monitor).on_click(
473
move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
474
));
410
475
}
411
popup = popup.separator().item(PopupMenuItem::label("Share a window..."));
476
popup = popup
477
.separator()
478
.item(PopupMenuItem::label("Share a window..."));
412
479
let windows = model.windows();
413
480
if windows.is_empty() {
414
481
return popup.item(PopupMenuItem::new(NO_WINDOWS_HINT).disabled(true));
@@ -420,7 +487,9 @@ fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, soun
420
487
popup = popup.item(
421
488
PopupMenuItem::new(label)
422
489
.icon(IconName::AppWindow)
423
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))),
490
.on_click(move |_, _, cx| {
491
app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
492
}),
424
493
);
425
494
}
426
495
popup
@@ -429,15 +498,25 @@ fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, soun
429
498
fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyElement {
430
499
if model.local_share.is_some() {
431
500
let app = app.clone();
432
return round_control("call-share-stop", IconName::ScreenShareOff, theme::accent(), theme::on_accent())
433
.tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
434
.on_click(move |_, _, cx| {
435
cx.stop_propagation();
436
app.update(cx, |state, cx| state.stop_call_share(cx));
437
})
438
.into_any_element();
501
return round_control(
502
"call-share-stop",
503
IconName::ScreenShareOff,
504
theme::accent(),
505
theme::on_accent(),
506
)
507
.tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
508
.on_click(move |_, _, cx| {
509
cx.stop_propagation();
510
app.update(cx, |state, cx| state.stop_call_share(cx));
511
})
512
.into_any_element();
439
513
}
440
let face = round_control("call-share-face", IconName::ScreenShare, theme::surface_raised(), theme::text());
514
let face = round_control(
515
"call-share-face",
516
IconName::ScreenShare,
517
theme::surface_raised(),
518
theme::text(),
519
);
441
520
if !model.can_share() {
442
521
return face
443
522
.opacity(DISABLED_OPACITY)
@@ -453,7 +532,9 @@ fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyEl
453
532
.size(px(CONTROL_SIZE))
454
533
.rounded_full()
455
534
.child(face)
456
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| share_items(popup, &app, &model, sound))
535
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
536
share_items(popup, &app, &model, sound)
537
})
457
538
.into_any_element()
458
539
}
459
540
@@ -488,8 +569,14 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
488
569
.bg(theme::on_accent().opacity(0.2))
489
570
.cursor_pointer()
490
571
.hover(|button| button.opacity(0.9))
491
.child(if sound { "Computer sound on" } else { "Computer sound off" })
492
.on_click(move |_, _, cx| sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))),
572
.child(if sound {
573
"Computer sound on"
574
} else {
575
"Computer sound off"
576
})
577
.on_click(move |_, _, cx| {
578
sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))
579
}),
493
580
)
494
581
.child(
495
582
div()
@@ -504,7 +591,9 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
504
591
.cursor_pointer()
505
592
.hover(|button| button.opacity(0.9))
506
593
.child("Stop sharing")
507
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.stop_call_share(cx))),
594
.on_click(move |_, _, cx| {
595
app.update(cx, |state, cx| state.stop_call_share(cx))
596
}),
508
597
)
509
598
.into_any_element(),
510
599
)
@@ -519,18 +608,43 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>
519
608
};
520
609
round_control("call-chat", IconName::MessageCircle, background, foreground)
521
610
.relative()
522
.tooltip(move |window, cx| Tooltip::new(if open { "Close the chat" } else { "Open the chat" }).build(window, cx))
611
.tooltip(move |window, cx| {
612
Tooltip::new(if open {
613
"Close the chat"
614
} else {
615
"Open the chat"
616
})
617
.build(window, cx)
618
})
523
619
.when(unread > 0, |button| {
524
button.child(div().absolute().top(px(-4.)).right(px(-4.)).child(count_badge(unread, false)))
620
button.child(
621
div()
622
.absolute()
623
.top(px(-4.))
624
.right(px(-4.))
625
.child(count_badge(unread, false)),
626
)
525
627
})
526
628
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
527
629
}
528
630
529
631
fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
530
632
let raised = model.own_hand.is_some();
531
let background = if raised { theme::accent() } else { theme::surface_raised() };
532
let foreground = if raised { theme::on_accent() } else { theme::text() };
533
let button = control_shell("call-hand", background).child(icon(IconName::Hand, CONTROL_ICON, foreground));
633
let background = if raised {
634
theme::accent()
635
} else {
636
theme::surface_raised()
637
};
638
let foreground = if raised {
639
theme::on_accent()
640
} else {
641
theme::text()
642
};
643
let button = control_shell("call-hand", background).child(icon(
644
IconName::Hand,
645
CONTROL_ICON,
646
foreground,
647
));
534
648
let tooltip = if raised { "Lower hand" } else { "Raise hand" };
535
649
let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));
536
650
if !model.can_react() {
@@ -544,37 +658,55 @@ fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
544
658
}
545
659
546
660
fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
547
let face = control_shell("call-reactions-face", theme::surface_raised())
548
.child(icon(IconName::FaceSlightlySmiling, CONTROL_ICON, theme::text()));
661
let face = control_shell("call-reactions-face", theme::surface_raised()).child(icon(
662
IconName::FaceSlightlySmiling,
663
CONTROL_ICON,
664
theme::text(),
665
));
549
666
if !model.can_react() {
550
return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();
667
return face
668
.opacity(DISABLED_OPACITY)
669
.cursor_default()
670
.into_any_element();
551
671
}
552
672
let app = app.clone();
553
673
Popover::new("call-reactions-popover")
554
674
.anchor(Anchor::BottomLeft)
555
675
.offset(px(10.))
556
.trigger(Button::new("call-reactions").ghost().p_0().size(px(CONTROL_SIZE)).rounded_full().child(face))
676
.trigger(
677
Button::new("call-reactions")
678
.ghost()
679
.p_0()
680
.size(px(CONTROL_SIZE))
681
.rounded_full()
682
.child(face),
683
)
557
684
.content(move |_, _, cx| {
558
685
let popover = cx.entity().downgrade();
559
h_flex().id("call-reactions-row").gap(px(4.)).children(Reaction::ALL.into_iter().map(|reaction| {
560
let app = app.clone();
561
let popover = popover.clone();
562
div()
563
.id(reaction.name())
564
.size(px(REACTION_CELL))
565
.flex()
566
.items_center()
567
.justify_center()
568
.rounded(px(8.))
569
.text_size(px(24.))
570
.cursor_pointer()
571
.hover(|cell| cell.bg(theme::border_strong()))
572
.child(reaction_glyph(reaction))
573
.on_click(move |_, window, cx| {
574
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));
575
popover.update(cx, |state, cx| state.dismiss(window, cx)).ok();
576
})
577
}))
686
h_flex()
687
.id("call-reactions-row")
688
.gap(px(4.))
689
.children(Reaction::ALL.into_iter().map(|reaction| {
690
let app = app.clone();
691
let popover = popover.clone();
692
div()
693
.id(reaction.name())
694
.size(px(REACTION_CELL))
695
.flex()
696
.items_center()
697
.justify_center()
698
.rounded(px(8.))
699
.text_size(px(24.))
700
.cursor_pointer()
701
.hover(|cell| cell.bg(theme::border_strong()))
702
.child(reaction_glyph(reaction))
703
.on_click(move |_, window, cx| {
704
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));
705
popover
706
.update(cx, |state, cx| state.dismiss(window, cx))
707
.ok();
708
})
709
}))
578
710
})
579
711
.into_any_element()
580
712
}
@@ -603,12 +735,15 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
603
735
let popup = popup.min_w(px(MENU_WIDTH)).item(
604
736
PopupMenuItem::new("Leave")
605
737
.icon(IconName::PhoneOff)
606
.on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),
738
.on_click(move |_, _, cx| {
739
leave_app.update(cx, |state, cx| state.leave_call(cx))
740
}),
607
741
);
608
742
let popup = if can_lower_all {
609
743
popup.item(
610
PopupMenuItem::new("Lower all hands")
611
.on_click(move |_, _, cx| lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))),
744
PopupMenuItem::new("Lower all hands").on_click(move |_, _, cx| {
745
lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))
746
}),
612
747
)
613
748
} else {
614
749
popup
@@ -617,7 +752,9 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
617
752
popup.item(
618
753
PopupMenuItem::new("End meeting for everyone")
619
754
.icon(IconName::PhoneOff)
620
.on_click(move |_, _, cx| end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))),
755
.on_click(move |_, _, cx| {
756
end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))
757
}),
621
758
)
622
759
} else {
623
760
popup
@@ -645,12 +782,20 @@ pub(super) fn device_items(
645
782
fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
646
783
let input_app = app.clone();
647
784
let output_app = app.clone();
648
let inputs = device_items(model.devices.input_entries(), &model.input, move |choice, cx| {
649
input_app.update(cx, |state, cx| state.select_call_input(choice, cx));
650
});
651
let outputs = device_items(model.devices.output_entries(), &model.output, move |choice, cx| {
652
output_app.update(cx, |state, cx| state.select_call_output(choice, cx));
653
});
785
let inputs = device_items(
786
model.devices.input_entries(),
787
&model.input,
788
move |choice, cx| {
789
input_app.update(cx, |state, cx| state.select_call_input(choice, cx));
790
},
791
);
792
let outputs = device_items(
793
model.devices.output_entries(),
794
&model.output,
795
move |choice, cx| {
796
output_app.update(cx, |state, cx| state.select_call_output(choice, cx));
797
},
798
);
654
799
let mut popup = popup
655
800
.min_w(px(MENU_WIDTH))
656
801
.item(PopupMenuItem::label("Microphone"));
@@ -687,11 +832,20 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement
687
832
})
688
833
}
689
834
690
fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {
835
fn person_tile(
836
app: &Entity<AppState>,
837
state: &AppState,
838
model: &CallModel,
839
remote: &Tile,
840
size: TileSize,
841
now: Instant,
842
) -> AnyElement {
691
843
let extras = TileExtras {
692
844
hand: remote.hand.map(|rank| model.hand_position(rank)),
693
845
own: false,
694
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),
846
reaction: model
847
.chip_of(&remote.mri, now)
848
.map(|chip| (chip.reaction, chip.serial)),
695
849
spotlight: remote.spotlight.is_some(),
696
850
pinned: model.is_pinned(&remote.mri),
697
851
};
@@ -699,25 +853,70 @@ fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remo
699
853
with_tile_menu(app, model, &remote.mri, &remote.name, false, element)
700
854
}
701
855
702
fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {
856
fn person_tile_body(
857
state: &AppState,
858
model: &CallModel,
859
remote: &Tile,
860
size: TileSize,
861
now: Instant,
862
extras: &TileExtras,
863
) -> AnyElement {
703
864
let video = state
704
865
.call
705
866
.as_ref()
706
867
.filter(|_| remote.has_video || model.is_one_to_one())
707
.and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));
868
.and_then(|call| {
869
call.pictures
870
.live(&VideoKey::Person(remote.mri.clone()), now)
871
});
708
872
if let Some(image) = video {
709
return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();
873
return video_tile(
874
size,
875
image,
876
&remote.name,
877
model.tile_speaking(remote),
878
remote.muted,
879
extras,
880
)
881
.into_any_element();
710
882
}
711
883
let waiting = remote.state == TileState::Invited;
712
let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
884
let avatar = person_avatar(
885
&state.directory,
886
remote.user_id.as_deref(),
887
&remote.name,
888
size.avatar,
889
);
713
890
let caption = model.tile_caption(remote).map(|text| {
714
let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
715
if waiting { blinking(label) } else { label.into_any_element() }
891
let label = div()
892
.text_size(px(12.))
893
.text_color(theme::text_muted())
894
.child(text);
895
if waiting {
896
blinking(label)
897
} else {
898
label.into_any_element()
899
}
716
900
});
717
tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()
901
tile(
902
size,
903
avatar,
904
&remote.name,
905
model.tile_speaking(remote),
906
remote.muted,
907
caption,
908
extras,
909
)
910
.into_any_element()
718
911
}
719
912
720
fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {
913
fn own_tile(
914
app: &Entity<AppState>,
915
state: &AppState,
916
model: &CallModel,
917
size: TileSize,
918
now: Instant,
919
) -> AnyElement {
721
920
let own_mri = model.own_mri.clone().unwrap_or_default();
722
921
let extras = TileExtras {
723
922
hand: model.own_hand.map(|rank| model.hand_position(rank)),
@@ -733,14 +932,28 @@ fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: T
733
932
with_tile_menu(app, model, &own_mri, "You", true, element)
734
933
}
735
934
736
fn own_tile_body(state: &AppState, model: &CallModel, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {
935
fn own_tile_body(
936
state: &AppState,
937
model: &CallModel,
938
size: TileSize,
939
now: Instant,
940
extras: &TileExtras,
941
) -> AnyElement {
737
942
let me = state.directory.me.as_ref();
738
943
let self_view = state
739
944
.call
740
945
.as_ref()
741
946
.and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
742
947
if let Some(image) = self_view {
743
return video_tile(size, image, "You", model.local_speaking, model.muted, extras).into_any_element();
948
return video_tile(
949
size,
950
image,
951
"You",
952
model.local_speaking,
953
model.muted,
954
extras,
955
)
956
.into_any_element();
744
957
}
745
958
let avatar = person_avatar(
746
959
&state.directory,
@@ -748,10 +961,26 @@ fn own_tile_body(state: &AppState, model: &CallModel, size: TileSize, now: Insta
748
961
me.map_or("You", |person| person.display_name.as_str()),
749
962
size.avatar,
750
963
);
751
tile(size, avatar, "You", model.local_speaking, model.muted, None, extras).into_any_element()
964
tile(
965
size,
966
avatar,
967
"You",
968
model.local_speaking,
969
model.muted,
970
None,
971
extras,
972
)
973
.into_any_element()
752
974
}
753
975
754
fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {
976
fn remote_tiles(
977
app: &Entity<AppState>,
978
state: &AppState,
979
model: &CallModel,
980
size: TileSize,
981
hidden_cap: GridLayout,
982
now: Instant,
983
) -> Vec<AnyElement> {
755
984
let visible = model.visible_tiles();
756
985
let mut cells: Vec<AnyElement> = visible
757
986
.iter()
@@ -764,7 +993,13 @@ fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, siz
764
993
cells
765
994
}
766
995
767
fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant, focused: Option<&str>) -> Stateful<Div> {
996
fn people_strip(
997
app: &Entity<AppState>,
998
state: &AppState,
999
model: &CallModel,
1000
now: Instant,
1001
focused: Option<&str>,
1002
) -> Stateful<Div> {
768
1003
let mut cells: Vec<AnyElement> = model
769
1004
.strip_tiles()
770
1005
.into_iter()
@@ -779,13 +1014,19 @@ fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now
779
1014
.id("call-strip")
780
1015
.flex_none()
781
1016
.w(px(STRIP_TILE.width))
782
.max_h(px(STRIP_VISIBLE * (STRIP_TILE.height + STRIP_GAP) - STRIP_GAP))
1017
.max_h(px(
1018
STRIP_VISIBLE * (STRIP_TILE.height + STRIP_GAP) - STRIP_GAP
1019
))
783
1020
.gap(px(STRIP_GAP))
784
1021
.overflow_y_scroll()
785
1022
.children(cells)
786
1023
}
787
1024
788
pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<Entity<ConversationView>>) -> Option<AnyElement> {
1025
pub fn render_call_view(
1026
app: &Entity<AppState>,
1027
state: &AppState,
1028
chat: Option<Entity<ConversationView>>,
1029
) -> Option<AnyElement> {
789
1030
let call = state.call.as_ref()?;
790
1031
let model = &call.model;
791
1032
let now = Instant::now();
@@ -806,15 +1047,29 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
806
1047
.font_weight(FontWeight::SEMIBOLD)
807
1048
.child(model.title.clone()),
808
1049
)
809
.child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status))
1050
.child(
1051
div()
1052
.flex_none()
1053
.text_size(px(13.))
1054
.text_color(status_color)
1055
.child(status),
1056
)
810
1057
.children(recording_chip(model))
811
1058
.children(room_chip(model))
812
1059
.child(div().flex_1())
813
1060
.children(return_button(app, model));
814
1061
815
let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };
1062
let max_tiles = if chat.is_some() {
1063
CHAT_OPEN_TILES
1064
} else {
1065
MAX_TILES
1066
};
816
1067
let layout = grid_layout(model.visible_tiles().len(), max_tiles);
817
let cells_for_size = if chat.is_some() { MAX_TILES } else { layout.shown_others + usize::from(layout.hidden > 0) + 1 };
1068
let cells_for_size = if chat.is_some() {
1069
MAX_TILES
1070
} else {
1071
layout.shown_others + usize::from(layout.hidden > 0) + 1
1072
};
818
1073
let size = tile_size(cells_for_size);
819
1074
let mut cells = remote_tiles(app, state, model, size, layout, now);
820
1075
let own_index = model.own_cell_index(cells.len());
@@ -822,7 +1077,11 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
822
1077
let focus = model.focus().filter(|_| model.screen_sharer.is_none());
823
1078
let stage = render_stage(app, state, false)
824
1079
.or_else(|| whiteboard_stage(app, model))
825
.or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));
1080
.or_else(|| {
1081
focus
1082
.as_ref()
1083
.and_then(|focus| render_focus_stage(app, state, focus, now))
1084
});
826
1085
let hold = hold_panel(app, model);
827
1086
let focused = focus.as_ref().map(|focus| focus.mri.as_str());
828
1087
@@ -834,57 +1093,72 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
834
1093
.items_center()
835
1094
.justify_center()
836
1095
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))
837
.child(h_flex().h(px(CONTROL_SIZE)).items_center().rounded_full().bg(theme::surface_raised()).child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))
1096
.child(
1097
h_flex()
1098
.h(px(CONTROL_SIZE))
1099
.items_center()
1100
.rounded_full()
1101
.bg(theme::surface_raised())
1102
.child(camera_button(app, model))
1103
.children(camera_menu_button(app, model, BackgroundMenu::of(state))),
1104
)
838
1105
.child(share_button(app, model, state.call_share_sound))
839
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))
1106
.when(model.has_reaction_controls(), |row| {
1107
row.child(hand_button(app, model))
1108
.child(reactions_button(app, model))
1109
})
840
1110
.child(devices_button(app, model))
841
1111
.children(more_button(app, model))
842
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))
1112
.when(call.chat_thread().is_some(), |row| {
1113
row.child(chat_button(app, call.chat_open, state.call_chat_unread()))
1114
})
843
1115
.child(leave_button(app, model, "call-leave", false))
844
.when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));
1116
.when(model.kind == CallKind::Meeting, |row| {
1117
row.child(leave_menu(app, model))
1118
});
845
1119
846
1120
let column = v_flex()
847
.relative()
848
.flex_1()
849
.min_w_0()
850
.h_full()
851
.rounded(px(10.))
852
.overflow_hidden()
853
.bg(theme::surface())
854
.child(header)
855
.children(lobby_banner(app, model))
856
.children(sharing_banner(app, model, state.call_share_sound))
857
.children(consult_banner(app, state))
858
.child(match stage {
859
_ if hold.is_some() => hold.expect("checked above"),
860
Some(stage) => h_flex()
861
.flex_1()
862
.min_h_0()
863
.p(px(GRID_PADDING))
864
.gap(px(TILE_GAP))
865
.items_center()
866
.child(stage)
867
.child(people_strip(app, state, model, now, focused))
868
.into_any_element(),
869
None => h_flex()
870
.id("call-grid")
871
.flex_1()
872
.min_h_0()
873
.overflow_y_scroll()
874
.flex_wrap()
875
.content_center()
876
.p(px(GRID_PADDING))
877
.gap(px(TILE_GAP))
878
.items_center()
879
.justify_center()
880
.children(cells)
881
.into_any_element(),
882
})
883
.child(controls)
884
.children(captions_overlay(model, now))
885
.children(captions_hint_chip(model))
886
.children(state.transfer_picker.clone())
887
.children(consent_overlay(app, model));
1121
.relative()
1122
.flex_1()
1123
.min_w_0()
1124
.h_full()
1125
.rounded(px(10.))
1126
.overflow_hidden()
1127
.bg(theme::surface())
1128
.child(header)
1129
.children(lobby_banner(app, model))
1130
.children(sharing_banner(app, model, state.call_share_sound))
1131
.children(consult_banner(app, state))
1132
.child(match stage {
1133
_ if hold.is_some() => hold.expect("checked above"),
1134
Some(stage) => h_flex()
1135
.flex_1()
1136
.min_h_0()
1137
.p(px(GRID_PADDING))
1138
.gap(px(TILE_GAP))
1139
.items_center()
1140
.child(stage)
1141
.child(people_strip(app, state, model, now, focused))
1142
.into_any_element(),
1143
None => h_flex()
1144
.id("call-grid")
1145
.flex_1()
1146
.min_h_0()
1147
.overflow_y_scroll()
1148
.flex_wrap()
1149
.content_center()
1150
.p(px(GRID_PADDING))
1151
.gap(px(TILE_GAP))
1152
.items_center()
1153
.justify_center()
1154
.children(cells)
1155
.into_any_element(),
1156
})
1157
.child(controls)
1158
.children(captions_overlay(model, now))
1159
.children(captions_hint_chip(model))
1160
.children(state.transfer_picker.clone())
1161
.children(consent_overlay(app, model));
888
1162
Some(
889
1163
h_flex()
890
1164
.flex_1()
@@ -916,7 +1190,12 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem
916
1190
.pr(px(12.))
917
1191
.items_center()
918
1192
.justify_between()
919
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))
1193
.child(
1194
div()
1195
.text_size(px(15.))
1196
.font_weight(FontWeight::SEMIBOLD)
1197
.child("Chat"),
1198
)
920
1199
.child(
921
1200
div()
922
1201
.id("call-chat-close")
@@ -929,7 +1208,9 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem
929
1208
.hover(|button| button.bg(theme::row_hover()))
930
1209
.tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))
931
1210
.child(icon(IconName::Close, 14., theme::text_muted()))
932
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),
1211
.on_click(move |_, _, cx| {
1212
app.update(cx, |state, cx| state.toggle_call_chat(cx))
1213
}),
933
1214
),
934
1215
)
935
1216
.child(chat)
@@ -16,16 +16,25 @@ use gpui_kit::prelude::FluentBuilder as _;16
use gpui_kit::*;16
use gpui_kit::*;17
17
18
use super::avatar::person_avatar;18
use super::avatar::person_avatar;19
use super::call_extras::{BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button, room_chip, whiteboard_stage};19
use super::call_extras::{20
use super::call_organizer::{camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip, render_focus_stage, spotlight_chip, with_tile_menu};20
BackgroundMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,21
room_chip, whiteboard_stage,22
};23
use super::call_organizer::{24
camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner, more_button, pin_chip,25
render_focus_stage, spotlight_chip, with_tile_menu,26
};21
use super::call_stage::render_stage;27
use super::call_stage::render_stage;22
use super::conversation::ConversationView;28
use super::conversation::ConversationView;23
use super::shell::ISLAND_GAP;29
use super::shell::ISLAND_GAP;24
use super::widgets::{count_badge, icon};30
use super::widgets::{count_badge, icon};25
use crate::app_state::AppState;31
use crate::app_state::AppState;26
use crate::call::TileSize;27
use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};28
use crate::call::REACTION_SHOWN;32
use crate::call::REACTION_SHOWN;33
use crate::call::TileSize;34
use crate::call::{35
CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout,36
tile_size,37
};29
use crate::rows::reaction_glyph as chat_reaction_glyph;38
use crate::rows::reaction_glyph as chat_reaction_glyph;30
use crate::theme;39
use crate::theme;31
40
@@ -91,7 +100,11 @@ fn hand_badge(position: usize, own: bool) -> Div {91
.text_color(hsla(0., 0., 0.08, 1.))100
.text_color(hsla(0., 0., 0.08, 1.))92
.text_size(px(12.))101
.text_size(px(12.))93
.font_weight(FontWeight::SEMIBOLD)102
.font_weight(FontWeight::SEMIBOLD)94
.child(if own { "Hand raised".to_owned() } else { format!("Hand {position}") })103
.child(if own {104
"Hand raised".to_owned()105
} else {106
format!("Hand {position}")107
})95
}108
}96
109
97
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {110
fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {@@ -112,7 +125,8 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {112
Animation::new(REACTION_SHOWN),125
Animation::new(REACTION_SHOWN),113
|chip, delta| {126
|chip, delta| {114
let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);127
let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);115
chip.bottom(px(32. + REACTION_RISE * delta)).opacity(1. - fade)128
chip.bottom(px(32. + REACTION_RISE * delta))129
.opacity(1. - fade)116
},130
},117
)131
)118
.into_any_element()132
.into_any_element()@@ -130,7 +144,9 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {130
.when(extras.pinned, |row| row.child(pin_chip()))144
.when(extras.pinned, |row| row.child(pin_chip()))131
.into_any_element()145
.into_any_element()132
});146
});133
let reaction = extras.reaction.map(|(reaction, serial)| reaction_chip(reaction, serial));147
let reaction = extras148
.reaction149
.map(|(reaction, serial)| reaction_chip(reaction, serial));134
badges.into_iter().chain(reaction).collect()150
badges.into_iter().chain(reaction).collect()135
}151
}136
152
@@ -161,8 +177,13 @@ pub fn pulsing(element: impl IntoElement + 'static, id: &'static str) -> AnyElem161
}177
}162
178
163
fn blinking(element: impl IntoElement + 'static) -> AnyElement {179
fn blinking(element: impl IntoElement + 'static) -> AnyElement {164
let dimmed = SystemTime::now().duration_since(UNIX_EPOCH).is_ok_and(|elapsed| (elapsed.as_millis() / BLINK_HALF_PERIOD.as_millis()) % 2 == 1);180
let dimmed = SystemTime::now()165
div().child(element).opacity(if dimmed { BLINK_DIMMED_OPACITY } else { 1. }).into_any_element()181
.duration_since(UNIX_EPOCH)182
.is_ok_and(|elapsed| (elapsed.as_millis() / BLINK_HALF_PERIOD.as_millis()) % 2 == 1);183
div()184
.child(element)185
.opacity(if dimmed { BLINK_DIMMED_OPACITY } else { 1. })186
.into_any_element()166
}187
}167
188
168
fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {189
fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {@@ -192,7 +213,14 @@ fn mute_badge() -> Div {192
.child(icon(IconName::MicOff, 13., theme::white()))213
.child(icon(IconName::MicOff, 13., theme::white()))193
}214
}194
215
195
fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: bool, muted: bool, extras: &TileExtras) -> Div {216
fn video_tile(217
size: TileSize,218
image: Arc<RenderImage>,219
name: &str,220
speaking: bool,221
muted: bool,222
extras: &TileExtras,223
) -> Div {196
div()224
div()197
.relative()225
.relative()198
.w(px(size.width))226
.w(px(size.width))@@ -202,7 +230,11 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo202
.rounded(px(TILE_RADIUS))230
.rounded(px(TILE_RADIUS))203
.bg(theme::row_hover())231
.bg(theme::row_hover())204
.border_2()232
.border_2()205
.border_color(if speaking { theme::green() } else { transparent_black() })233
.border_color(if speaking {234
theme::green()235
} else {236
transparent_black()237
})206
.child(238
.child(207
img(ImageSource::Render(image))239
img(ImageSource::Render(image))208
.size_full()240
.size_full()@@ -309,11 +341,21 @@ fn control_shell(id: &'static str, background: Hsla) -> Stateful<Div> {309
.hover(|button| button.opacity(0.85))341
.hover(|button| button.opacity(0.85))310
}342
}311
343
312
pub(super) fn round_control(id: &'static str, glyph: IconName, background: Hsla, foreground: Hsla) -> Stateful<Div> {344
pub(super) fn round_control(345
id: &'static str,346
glyph: IconName,347
background: Hsla,348
foreground: Hsla,349
) -> Stateful<Div> {313
control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))350
control_shell(id, background).child(icon(glyph, CONTROL_ICON, foreground))314
}351
}315
352
316
pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, size: f32) -> Stateful<Div> {353
pub fn mute_button(354
app: &Entity<AppState>,355
model: &CallModel,356
id: &'static str,357
size: f32,358
) -> Stateful<Div> {317
let (glyph, background, foreground) = if model.muted {359
let (glyph, background, foreground) = if model.muted {318
(IconName::MicOff, theme::red(), theme::white())360
(IconName::MicOff, theme::red(), theme::white())319
} else {361
} else {@@ -333,8 +375,17 @@ pub fn mute_button(app: &Entity<AppState>, model: &CallModel, id: &'static str,333
})375
})334
}376
}335
377
336
pub fn leave_button(app: &Entity<AppState>, model: &CallModel, id: &'static str, compact: bool) -> Stateful<Div> {378
pub fn leave_button(337
let label = if model.is_connecting() { "Cancel" } else { "Leave" };379
app: &Entity<AppState>,380
model: &CallModel,381
id: &'static str,382
compact: bool,383
) -> Stateful<Div> {384
let label = if model.is_connecting() {385
"Cancel"386
} else {387
"Leave"388
};338
let app = app.clone();389
let app = app.clone();339
h_flex()390
h_flex()340
.id(id)391
.id(id)@@ -351,7 +402,11 @@ pub fn leave_button(app: &Entity<AppState>, model: &CallModel, id: &'static str,351
.font_weight(FontWeight::SEMIBOLD)402
.font_weight(FontWeight::SEMIBOLD)352
.cursor_pointer()403
.cursor_pointer()353
.hover(|button| button.opacity(0.85))404
.hover(|button| button.opacity(0.85))354
.child(icon(IconName::PhoneOff, if compact { 14. } else { 18. }, theme::white()))405
.child(icon(406
IconName::PhoneOff,407
if compact { 14. } else { 18. },408
theme::white(),409
))355
.child(label)410
.child(label)356
.on_click(move |_, _, cx| {411
.on_click(move |_, _, cx| {357
cx.stop_propagation();412
cx.stop_propagation();@@ -394,21 +449,33 @@ fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {394
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))449
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))395
}450
}396
451
397
fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, sound: bool) -> PopupMenu {452
fn share_items(453
popup: PopupMenu,454
app: &Entity<AppState>,455
model: &CallModel,456
sound: bool,457
) -> PopupMenu {398
let screens = model.screens();458
let screens = model.screens();399
let single_screen = screens.len() == 1;459
let single_screen = screens.len() == 1;400
let mut popup = popup.min_w(px(MENU_WIDTH)).item(sound_switch_item(app, sound)).separator();460
let mut popup = popup461
.min_w(px(MENU_WIDTH))462
.item(sound_switch_item(app, sound))463
.separator();401
for (index, source) in screens.into_iter().enumerate() {464
for (index, source) in screens.into_iter().enumerate() {402
let label = if single_screen { "Share entire screen".to_owned() } else { format!("Share screen {}", index + 1) };465
let label = if single_screen {466
"Share entire screen".to_owned()467
} else {468
format!("Share screen {}", index + 1)469
};403
let source = source.clone();470
let source = source.clone();404
let app = app.clone();471
let app = app.clone();405
popup = popup.item(472
popup = popup.item(PopupMenuItem::new(label).icon(IconName::Monitor).on_click(406
PopupMenuItem::new(label)473
move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),407
.icon(IconName::Monitor)474
));408
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))),409
);410
}475
}411
popup = popup.separator().item(PopupMenuItem::label("Share a window..."));476
popup = popup477
.separator()478
.item(PopupMenuItem::label("Share a window..."));412
let windows = model.windows();479
let windows = model.windows();413
if windows.is_empty() {480
if windows.is_empty() {414
return popup.item(PopupMenuItem::new(NO_WINDOWS_HINT).disabled(true));481
return popup.item(PopupMenuItem::new(NO_WINDOWS_HINT).disabled(true));@@ -420,7 +487,9 @@ fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, soun420
popup = popup.item(487
popup = popup.item(421
PopupMenuItem::new(label)488
PopupMenuItem::new(label)422
.icon(IconName::AppWindow)489
.icon(IconName::AppWindow)423
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))),490
.on_click(move |_, _, cx| {491
app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))492
}),424
);493
);425
}494
}426
popup495
popup@@ -429,15 +498,25 @@ fn share_items(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, soun429
fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyElement {498
fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyElement {430
if model.local_share.is_some() {499
if model.local_share.is_some() {431
let app = app.clone();500
let app = app.clone();432
return round_control("call-share-stop", IconName::ScreenShareOff, theme::accent(), theme::on_accent())501
return round_control(433
.tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))502
"call-share-stop",434
.on_click(move |_, _, cx| {503
IconName::ScreenShareOff,435
cx.stop_propagation();504
theme::accent(),436
app.update(cx, |state, cx| state.stop_call_share(cx));505
theme::on_accent(),437
})506
)438
.into_any_element();507
.tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))508
.on_click(move |_, _, cx| {509
cx.stop_propagation();510
app.update(cx, |state, cx| state.stop_call_share(cx));511
})512
.into_any_element();439
}513
}440
let face = round_control("call-share-face", IconName::ScreenShare, theme::surface_raised(), theme::text());514
let face = round_control(515
"call-share-face",516
IconName::ScreenShare,517
theme::surface_raised(),518
theme::text(),519
);441
if !model.can_share() {520
if !model.can_share() {442
return face521
return face443
.opacity(DISABLED_OPACITY)522
.opacity(DISABLED_OPACITY)@@ -453,7 +532,9 @@ fn share_button(app: &Entity<AppState>, model: &CallModel, sound: bool) -> AnyEl453
.size(px(CONTROL_SIZE))532
.size(px(CONTROL_SIZE))454
.rounded_full()533
.rounded_full()455
.child(face)534
.child(face)456
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| share_items(popup, &app, &model, sound))535
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {536
share_items(popup, &app, &model, sound)537
})457
.into_any_element()538
.into_any_element()458
}539
}459
540
@@ -488,8 +569,14 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt488
.bg(theme::on_accent().opacity(0.2))569
.bg(theme::on_accent().opacity(0.2))489
.cursor_pointer()570
.cursor_pointer()490
.hover(|button| button.opacity(0.9))571
.hover(|button| button.opacity(0.9))491
.child(if sound { "Computer sound on" } else { "Computer sound off" })572
.child(if sound {492
.on_click(move |_, _, cx| sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))),573
"Computer sound on"574
} else {575
"Computer sound off"576
})577
.on_click(move |_, _, cx| {578
sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))579
}),493
)580
)494
.child(581
.child(495
div()582
div()@@ -504,7 +591,9 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt504
.cursor_pointer()591
.cursor_pointer()505
.hover(|button| button.opacity(0.9))592
.hover(|button| button.opacity(0.9))506
.child("Stop sharing")593
.child("Stop sharing")507
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.stop_call_share(cx))),594
.on_click(move |_, _, cx| {595
app.update(cx, |state, cx| state.stop_call_share(cx))596
}),508
)597
)509
.into_any_element(),598
.into_any_element(),510
)599
)@@ -519,18 +608,43 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>519
};608
};520
round_control("call-chat", IconName::MessageCircle, background, foreground)609
round_control("call-chat", IconName::MessageCircle, background, foreground)521
.relative()610
.relative()522
.tooltip(move |window, cx| Tooltip::new(if open { "Close the chat" } else { "Open the chat" }).build(window, cx))611
.tooltip(move |window, cx| {612
Tooltip::new(if open {613
"Close the chat"614
} else {615
"Open the chat"616
})617
.build(window, cx)618
})523
.when(unread > 0, |button| {619
.when(unread > 0, |button| {524
button.child(div().absolute().top(px(-4.)).right(px(-4.)).child(count_badge(unread, false)))620
button.child(621
div()622
.absolute()623
.top(px(-4.))624
.right(px(-4.))625
.child(count_badge(unread, false)),626
)525
})627
})526
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))628
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))527
}629
}528
630
529
fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {631
fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {530
let raised = model.own_hand.is_some();632
let raised = model.own_hand.is_some();531
let background = if raised { theme::accent() } else { theme::surface_raised() };633
let background = if raised {532
let foreground = if raised { theme::on_accent() } else { theme::text() };634
theme::accent()533
let button = control_shell("call-hand", background).child(icon(IconName::Hand, CONTROL_ICON, foreground));635
} else {636
theme::surface_raised()637
};638
let foreground = if raised {639
theme::on_accent()640
} else {641
theme::text()642
};643
let button = control_shell("call-hand", background).child(icon(644
IconName::Hand,645
CONTROL_ICON,646
foreground,647
));534
let tooltip = if raised { "Lower hand" } else { "Raise hand" };648
let tooltip = if raised { "Lower hand" } else { "Raise hand" };535
let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));649
let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));536
if !model.can_react() {650
if !model.can_react() {@@ -544,37 +658,55 @@ fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {544
}658
}545
659
546
fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {660
fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {547
let face = control_shell("call-reactions-face", theme::surface_raised())661
let face = control_shell("call-reactions-face", theme::surface_raised()).child(icon(548
.child(icon(IconName::FaceSlightlySmiling, CONTROL_ICON, theme::text()));662
IconName::FaceSlightlySmiling,663
CONTROL_ICON,664
theme::text(),665
));549
if !model.can_react() {666
if !model.can_react() {550
return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();667
return face668
.opacity(DISABLED_OPACITY)669
.cursor_default()670
.into_any_element();551
}671
}552
let app = app.clone();672
let app = app.clone();553
Popover::new("call-reactions-popover")673
Popover::new("call-reactions-popover")554
.anchor(Anchor::BottomLeft)674
.anchor(Anchor::BottomLeft)555
.offset(px(10.))675
.offset(px(10.))556
.trigger(Button::new("call-reactions").ghost().p_0().size(px(CONTROL_SIZE)).rounded_full().child(face))676
.trigger(677
Button::new("call-reactions")678
.ghost()679
.p_0()680
.size(px(CONTROL_SIZE))681
.rounded_full()682
.child(face),683
)557
.content(move |_, _, cx| {684
.content(move |_, _, cx| {558
let popover = cx.entity().downgrade();685
let popover = cx.entity().downgrade();559
h_flex().id("call-reactions-row").gap(px(4.)).children(Reaction::ALL.into_iter().map(|reaction| {686
h_flex()560
let app = app.clone();687
.id("call-reactions-row")561
let popover = popover.clone();688
.gap(px(4.))562
div()689
.children(Reaction::ALL.into_iter().map(|reaction| {563
.id(reaction.name())690
let app = app.clone();564
.size(px(REACTION_CELL))691
let popover = popover.clone();565
.flex()692
div()566
.items_center()693
.id(reaction.name())567
.justify_center()694
.size(px(REACTION_CELL))568
.rounded(px(8.))695
.flex()569
.text_size(px(24.))696
.items_center()570
.cursor_pointer()697
.justify_center()571
.hover(|cell| cell.bg(theme::border_strong()))698
.rounded(px(8.))572
.child(reaction_glyph(reaction))699
.text_size(px(24.))573
.on_click(move |_, window, cx| {700
.cursor_pointer()574
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));701
.hover(|cell| cell.bg(theme::border_strong()))575
popover.update(cx, |state, cx| state.dismiss(window, cx)).ok();702
.child(reaction_glyph(reaction))576
})703
.on_click(move |_, window, cx| {577
}))704
app.update(cx, |state, cx| state.send_call_reaction(reaction, cx));705
popover706
.update(cx, |state, cx| state.dismiss(window, cx))707
.ok();708
})709
}))578
})710
})579
.into_any_element()711
.into_any_element()580
}712
}@@ -603,12 +735,15 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {603
let popup = popup.min_w(px(MENU_WIDTH)).item(735
let popup = popup.min_w(px(MENU_WIDTH)).item(604
PopupMenuItem::new("Leave")736
PopupMenuItem::new("Leave")605
.icon(IconName::PhoneOff)737
.icon(IconName::PhoneOff)606
.on_click(move |_, _, cx| leave_app.update(cx, |state, cx| state.leave_call(cx))),738
.on_click(move |_, _, cx| {739
leave_app.update(cx, |state, cx| state.leave_call(cx))740
}),607
);741
);608
let popup = if can_lower_all {742
let popup = if can_lower_all {609
popup.item(743
popup.item(610
PopupMenuItem::new("Lower all hands")744
PopupMenuItem::new("Lower all hands").on_click(move |_, _, cx| {611
.on_click(move |_, _, cx| lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))),745
lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))746
}),612
)747
)613
} else {748
} else {614
popup749
popup@@ -617,7 +752,9 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {617
popup.item(752
popup.item(618
PopupMenuItem::new("End meeting for everyone")753
PopupMenuItem::new("End meeting for everyone")619
.icon(IconName::PhoneOff)754
.icon(IconName::PhoneOff)620
.on_click(move |_, _, cx| end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))),755
.on_click(move |_, _, cx| {756
end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))757
}),621
)758
)622
} else {759
} else {623
popup760
popup@@ -645,12 +782,20 @@ pub(super) fn device_items(645
fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {782
fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {646
let input_app = app.clone();783
let input_app = app.clone();647
let output_app = app.clone();784
let output_app = app.clone();648
let inputs = device_items(model.devices.input_entries(), &model.input, move |choice, cx| {785
let inputs = device_items(649
input_app.update(cx, |state, cx| state.select_call_input(choice, cx));786
model.devices.input_entries(),650
});787
&model.input,651
let outputs = device_items(model.devices.output_entries(), &model.output, move |choice, cx| {788
move |choice, cx| {652
output_app.update(cx, |state, cx| state.select_call_output(choice, cx));789
input_app.update(cx, |state, cx| state.select_call_input(choice, cx));653
});790
},791
);792
let outputs = device_items(793
model.devices.output_entries(),794
&model.output,795
move |choice, cx| {796
output_app.update(cx, |state, cx| state.select_call_output(choice, cx));797
},798
);654
let mut popup = popup799
let mut popup = popup655
.min_w(px(MENU_WIDTH))800
.min_w(px(MENU_WIDTH))656
.item(PopupMenuItem::label("Microphone"));801
.item(PopupMenuItem::label("Microphone"));@@ -687,11 +832,20 @@ fn devices_button(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement687
})832
})688
}833
}689
834
690
fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant) -> AnyElement {835
fn person_tile(836
app: &Entity<AppState>,837
state: &AppState,838
model: &CallModel,839
remote: &Tile,840
size: TileSize,841
now: Instant,842
) -> AnyElement {691
let extras = TileExtras {843
let extras = TileExtras {692
hand: remote.hand.map(|rank| model.hand_position(rank)),844
hand: remote.hand.map(|rank| model.hand_position(rank)),693
own: false,845
own: false,694
reaction: model.chip_of(&remote.mri, now).map(|chip| (chip.reaction, chip.serial)),846
reaction: model847
.chip_of(&remote.mri, now)848
.map(|chip| (chip.reaction, chip.serial)),695
spotlight: remote.spotlight.is_some(),849
spotlight: remote.spotlight.is_some(),696
pinned: model.is_pinned(&remote.mri),850
pinned: model.is_pinned(&remote.mri),697
};851
};@@ -699,25 +853,70 @@ fn person_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, remo699
with_tile_menu(app, model, &remote.mri, &remote.name, false, element)853
with_tile_menu(app, model, &remote.mri, &remote.name, false, element)700
}854
}701
855
702
fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {856
fn person_tile_body(857
state: &AppState,858
model: &CallModel,859
remote: &Tile,860
size: TileSize,861
now: Instant,862
extras: &TileExtras,863
) -> AnyElement {703
let video = state864
let video = state704
.call865
.call705
.as_ref()866
.as_ref()706
.filter(|_| remote.has_video || model.is_one_to_one())867
.filter(|_| remote.has_video || model.is_one_to_one())707
.and_then(|call| call.pictures.live(&VideoKey::Person(remote.mri.clone()), now));868
.and_then(|call| {869
call.pictures870
.live(&VideoKey::Person(remote.mri.clone()), now)871
});708
if let Some(image) = video {872
if let Some(image) = video {709
return video_tile(size, image, &remote.name, model.tile_speaking(remote), remote.muted, extras).into_any_element();873
return video_tile(874
size,875
image,876
&remote.name,877
model.tile_speaking(remote),878
remote.muted,879
extras,880
)881
.into_any_element();710
}882
}711
let waiting = remote.state == TileState::Invited;883
let waiting = remote.state == TileState::Invited;712
let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);884
let avatar = person_avatar(885
&state.directory,886
remote.user_id.as_deref(),887
&remote.name,888
size.avatar,889
);713
let caption = model.tile_caption(remote).map(|text| {890
let caption = model.tile_caption(remote).map(|text| {714
let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);891
let label = div()715
if waiting { blinking(label) } else { label.into_any_element() }892
.text_size(px(12.))893
.text_color(theme::text_muted())894
.child(text);895
if waiting {896
blinking(label)897
} else {898
label.into_any_element()899
}716
});900
});717
tile(size, avatar, &remote.name, model.tile_speaking(remote), remote.muted, caption, extras).into_any_element()901
tile(902
size,903
avatar,904
&remote.name,905
model.tile_speaking(remote),906
remote.muted,907
caption,908
extras,909
)910
.into_any_element()718
}911
}719
912
720
fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, now: Instant) -> AnyElement {913
fn own_tile(914
app: &Entity<AppState>,915
state: &AppState,916
model: &CallModel,917
size: TileSize,918
now: Instant,919
) -> AnyElement {721
let own_mri = model.own_mri.clone().unwrap_or_default();920
let own_mri = model.own_mri.clone().unwrap_or_default();722
let extras = TileExtras {921
let extras = TileExtras {723
hand: model.own_hand.map(|rank| model.hand_position(rank)),922
hand: model.own_hand.map(|rank| model.hand_position(rank)),@@ -733,14 +932,28 @@ fn own_tile(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: T733
with_tile_menu(app, model, &own_mri, "You", true, element)932
with_tile_menu(app, model, &own_mri, "You", true, element)734
}933
}735
934
736
fn own_tile_body(state: &AppState, model: &CallModel, size: TileSize, now: Instant, extras: &TileExtras) -> AnyElement {935
fn own_tile_body(936
state: &AppState,937
model: &CallModel,938
size: TileSize,939
now: Instant,940
extras: &TileExtras,941
) -> AnyElement {737
let me = state.directory.me.as_ref();942
let me = state.directory.me.as_ref();738
let self_view = state943
let self_view = state739
.call944
.call740
.as_ref()945
.as_ref()741
.and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));946
.and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));742
if let Some(image) = self_view {947
if let Some(image) = self_view {743
return video_tile(size, image, "You", model.local_speaking, model.muted, extras).into_any_element();948
return video_tile(949
size,950
image,951
"You",952
model.local_speaking,953
model.muted,954
extras,955
)956
.into_any_element();744
}957
}745
let avatar = person_avatar(958
let avatar = person_avatar(746
&state.directory,959
&state.directory,@@ -748,10 +961,26 @@ fn own_tile_body(state: &AppState, model: &CallModel, size: TileSize, now: Insta748
me.map_or("You", |person| person.display_name.as_str()),961
me.map_or("You", |person| person.display_name.as_str()),749
size.avatar,962
size.avatar,750
);963
);751
tile(size, avatar, "You", model.local_speaking, model.muted, None, extras).into_any_element()964
tile(965
size,966
avatar,967
"You",968
model.local_speaking,969
model.muted,970
None,971
extras,972
)973
.into_any_element()752
}974
}753
975
754
fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, size: TileSize, hidden_cap: GridLayout, now: Instant) -> Vec<AnyElement> {976
fn remote_tiles(977
app: &Entity<AppState>,978
state: &AppState,979
model: &CallModel,980
size: TileSize,981
hidden_cap: GridLayout,982
now: Instant,983
) -> Vec<AnyElement> {755
let visible = model.visible_tiles();984
let visible = model.visible_tiles();756
let mut cells: Vec<AnyElement> = visible985
let mut cells: Vec<AnyElement> = visible757
.iter()986
.iter()@@ -764,7 +993,13 @@ fn remote_tiles(app: &Entity<AppState>, state: &AppState, model: &CallModel, siz764
cells993
cells765
}994
}766
995
767
fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now: Instant, focused: Option<&str>) -> Stateful<Div> {996
fn people_strip(997
app: &Entity<AppState>,998
state: &AppState,999
model: &CallModel,1000
now: Instant,1001
focused: Option<&str>,1002
) -> Stateful<Div> {768
let mut cells: Vec<AnyElement> = model1003
let mut cells: Vec<AnyElement> = model769
.strip_tiles()1004
.strip_tiles()770
.into_iter()1005
.into_iter()@@ -779,13 +1014,19 @@ fn people_strip(app: &Entity<AppState>, state: &AppState, model: &CallModel, now779
.id("call-strip")1014
.id("call-strip")780
.flex_none()1015
.flex_none()781
.w(px(STRIP_TILE.width))1016
.w(px(STRIP_TILE.width))782
.max_h(px(STRIP_VISIBLE * (STRIP_TILE.height + STRIP_GAP) - STRIP_GAP))1017
.max_h(px(1018
STRIP_VISIBLE * (STRIP_TILE.height + STRIP_GAP) - STRIP_GAP1019
))783
.gap(px(STRIP_GAP))1020
.gap(px(STRIP_GAP))784
.overflow_y_scroll()1021
.overflow_y_scroll()785
.children(cells)1022
.children(cells)786
}1023
}787
1024
788
pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<Entity<ConversationView>>) -> Option<AnyElement> {1025
pub fn render_call_view(1026
app: &Entity<AppState>,1027
state: &AppState,1028
chat: Option<Entity<ConversationView>>,1029
) -> Option<AnyElement> {789
let call = state.call.as_ref()?;1030
let call = state.call.as_ref()?;790
let model = &call.model;1031
let model = &call.model;791
let now = Instant::now();1032
let now = Instant::now();@@ -806,15 +1047,29 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E806
.font_weight(FontWeight::SEMIBOLD)1047
.font_weight(FontWeight::SEMIBOLD)807
.child(model.title.clone()),1048
.child(model.title.clone()),808
)1049
)809
.child(div().flex_none().text_size(px(13.)).text_color(status_color).child(status))1050
.child(1051
div()1052
.flex_none()1053
.text_size(px(13.))1054
.text_color(status_color)1055
.child(status),1056
)810
.children(recording_chip(model))1057
.children(recording_chip(model))811
.children(room_chip(model))1058
.children(room_chip(model))812
.child(div().flex_1())1059
.child(div().flex_1())813
.children(return_button(app, model));1060
.children(return_button(app, model));814
1061
815
let max_tiles = if chat.is_some() { CHAT_OPEN_TILES } else { MAX_TILES };1062
let max_tiles = if chat.is_some() {1063
CHAT_OPEN_TILES1064
} else {1065
MAX_TILES1066
};816
let layout = grid_layout(model.visible_tiles().len(), max_tiles);1067
let layout = grid_layout(model.visible_tiles().len(), max_tiles);817
let cells_for_size = if chat.is_some() { MAX_TILES } else { layout.shown_others + usize::from(layout.hidden > 0) + 1 };1068
let cells_for_size = if chat.is_some() {1069
MAX_TILES1070
} else {1071
layout.shown_others + usize::from(layout.hidden > 0) + 11072
};818
let size = tile_size(cells_for_size);1073
let size = tile_size(cells_for_size);819
let mut cells = remote_tiles(app, state, model, size, layout, now);1074
let mut cells = remote_tiles(app, state, model, size, layout, now);820
let own_index = model.own_cell_index(cells.len());1075
let own_index = model.own_cell_index(cells.len());@@ -822,7 +1077,11 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E822
let focus = model.focus().filter(|_| model.screen_sharer.is_none());1077
let focus = model.focus().filter(|_| model.screen_sharer.is_none());823
let stage = render_stage(app, state, false)1078
let stage = render_stage(app, state, false)824
.or_else(|| whiteboard_stage(app, model))1079
.or_else(|| whiteboard_stage(app, model))825
.or_else(|| focus.as_ref().and_then(|focus| render_focus_stage(app, state, focus, now)));1080
.or_else(|| {1081
focus1082
.as_ref()1083
.and_then(|focus| render_focus_stage(app, state, focus, now))1084
});826
let hold = hold_panel(app, model);1085
let hold = hold_panel(app, model);827
let focused = focus.as_ref().map(|focus| focus.mri.as_str());1086
let focused = focus.as_ref().map(|focus| focus.mri.as_str());828
1087
@@ -834,57 +1093,72 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E834
.items_center()1093
.items_center()835
.justify_center()1094
.justify_center()836
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))1095
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))837
.child(h_flex().h(px(CONTROL_SIZE)).items_center().rounded_full().bg(theme::surface_raised()).child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))1096
.child(1097
h_flex()1098
.h(px(CONTROL_SIZE))1099
.items_center()1100
.rounded_full()1101
.bg(theme::surface_raised())1102
.child(camera_button(app, model))1103
.children(camera_menu_button(app, model, BackgroundMenu::of(state))),1104
)838
.child(share_button(app, model, state.call_share_sound))1105
.child(share_button(app, model, state.call_share_sound))839
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))1106
.when(model.has_reaction_controls(), |row| {1107
row.child(hand_button(app, model))1108
.child(reactions_button(app, model))1109
})840
.child(devices_button(app, model))1110
.child(devices_button(app, model))841
.children(more_button(app, model))1111
.children(more_button(app, model))842
.when(call.chat_thread().is_some(), |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())))1112
.when(call.chat_thread().is_some(), |row| {1113
row.child(chat_button(app, call.chat_open, state.call_chat_unread()))1114
})843
.child(leave_button(app, model, "call-leave", false))1115
.child(leave_button(app, model, "call-leave", false))844
.when(model.kind == CallKind::Meeting, |row| row.child(leave_menu(app, model)));1116
.when(model.kind == CallKind::Meeting, |row| {1117
row.child(leave_menu(app, model))1118
});845
1119
846
let column = v_flex()1120
let column = v_flex()847
.relative()1121
.relative()848
.flex_1()1122
.flex_1()849
.min_w_0()1123
.min_w_0()850
.h_full()1124
.h_full()851
.rounded(px(10.))1125
.rounded(px(10.))852
.overflow_hidden()1126
.overflow_hidden()853
.bg(theme::surface())1127
.bg(theme::surface())854
.child(header)1128
.child(header)855
.children(lobby_banner(app, model))1129
.children(lobby_banner(app, model))856
.children(sharing_banner(app, model, state.call_share_sound))1130
.children(sharing_banner(app, model, state.call_share_sound))857
.children(consult_banner(app, state))1131
.children(consult_banner(app, state))858
.child(match stage {1132
.child(match stage {859
_ if hold.is_some() => hold.expect("checked above"),1133
_ if hold.is_some() => hold.expect("checked above"),860
Some(stage) => h_flex()1134
Some(stage) => h_flex()861
.flex_1()1135
.flex_1()862
.min_h_0()1136
.min_h_0()863
.p(px(GRID_PADDING))1137
.p(px(GRID_PADDING))864
.gap(px(TILE_GAP))1138
.gap(px(TILE_GAP))865
.items_center()1139
.items_center()866
.child(stage)1140
.child(stage)867
.child(people_strip(app, state, model, now, focused))1141
.child(people_strip(app, state, model, now, focused))868
.into_any_element(),1142
.into_any_element(),869
None => h_flex()1143
None => h_flex()870
.id("call-grid")1144
.id("call-grid")871
.flex_1()1145
.flex_1()872
.min_h_0()1146
.min_h_0()873
.overflow_y_scroll()1147
.overflow_y_scroll()874
.flex_wrap()1148
.flex_wrap()875
.content_center()1149
.content_center()876
.p(px(GRID_PADDING))1150
.p(px(GRID_PADDING))877
.gap(px(TILE_GAP))1151
.gap(px(TILE_GAP))878
.items_center()1152
.items_center()879
.justify_center()1153
.justify_center()880
.children(cells)1154
.children(cells)881
.into_any_element(),1155
.into_any_element(),882
})1156
})883
.child(controls)1157
.child(controls)884
.children(captions_overlay(model, now))1158
.children(captions_overlay(model, now))885
.children(captions_hint_chip(model))1159
.children(captions_hint_chip(model))886
.children(state.transfer_picker.clone())1160
.children(state.transfer_picker.clone())887
.children(consent_overlay(app, model));1161
.children(consent_overlay(app, model));888
Some(1162
Some(889
h_flex()1163
h_flex()890
.flex_1()1164
.flex_1()@@ -916,7 +1190,12 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem916
.pr(px(12.))1190
.pr(px(12.))917
.items_center()1191
.items_center()918
.justify_between()1192
.justify_between()919
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))1193
.child(1194
div()1195
.text_size(px(15.))1196
.font_weight(FontWeight::SEMIBOLD)1197
.child("Chat"),1198
)920
.child(1199
.child(921
div()1200
div()922
.id("call-chat-close")1201
.id("call-chat-close")@@ -929,7 +1208,9 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem929
.hover(|button| button.bg(theme::row_hover()))1208
.hover(|button| button.bg(theme::row_hover()))930
.tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))1209
.tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))931
.child(icon(IconName::Close, 14., theme::text_muted()))1210
.child(icon(IconName::Close, 14., theme::text_muted()))932
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),1211
.on_click(move |_, _, cx| {1212
app.update(cx, |state, cx| state.toggle_call_chat(cx))1213
}),933
),1214
),934
)1215
)935
.child(chat)1216
.child(chat)@@ -148,7 +148,11 @@ fn join_button(id: &'static str, label: &'static str, primary: bool) -> Stateful
148
148
let (fill, hover_fill, text_color) = if primary {
149
149
(theme::accent(), theme::accent_text(), theme::on_accent())
150
150
} else {
151
(theme::surface_raised(), theme::popup_hover(), theme::text_strong())
151
(
152
theme::surface_raised(),
153
theme::popup_hover(),
154
theme::text_strong(),
155
)
152
156
};
153
157
div()
154
158
.id(id)
@@ -332,9 +336,11 @@ pub fn calls_body(
332
336
ListEntry::Section(title) => section_header(title),
333
337
ListEntry::Day(label) => day_header(label),
334
338
ListEntry::Empty(text) => empty_row(text),
335
ListEntry::Agenda(row) => {
336
agenda_row(state, row, join_available(row.start, row.end, now) && row.join_url.is_some())
337
}
339
ListEntry::Agenda(row) => agenda_row(
340
state,
341
row,
342
join_available(row.start, row.end, now) && row.join_url.is_some(),
343
),
338
344
ListEntry::Call(row) => call_row(
339
345
state,
340
346
row,
@@ -148,7 +148,11 @@ fn join_button(id: &'static str, label: &'static str, primary: bool) -> Stateful148
let (fill, hover_fill, text_color) = if primary {148
let (fill, hover_fill, text_color) = if primary {149
(theme::accent(), theme::accent_text(), theme::on_accent())149
(theme::accent(), theme::accent_text(), theme::on_accent())150
} else {150
} else {151
(theme::surface_raised(), theme::popup_hover(), theme::text_strong())151
(152
theme::surface_raised(),153
theme::popup_hover(),154
theme::text_strong(),155
)152
};156
};153
div()157
div()154
.id(id)158
.id(id)@@ -332,9 +336,11 @@ pub fn calls_body(332
ListEntry::Section(title) => section_header(title),336
ListEntry::Section(title) => section_header(title),333
ListEntry::Day(label) => day_header(label),337
ListEntry::Day(label) => day_header(label),334
ListEntry::Empty(text) => empty_row(text),338
ListEntry::Empty(text) => empty_row(text),335
ListEntry::Agenda(row) => {339
ListEntry::Agenda(row) => agenda_row(336
agenda_row(state, row, join_available(row.start, row.end, now) && row.join_url.is_some())340
state,337
}341
row,342
join_available(row.start, row.end, now) && row.join_url.is_some(),343
),338
ListEntry::Call(row) => call_row(344
ListEntry::Call(row) => call_row(339
state,345
state,340
row,346
row,@@ -25,8 +25,8 @@ use gpui_kit::prelude::FluentBuilder as _;
25
25
use gpui_kit::*;
26
26
use serde::{Deserialize, Serialize};
27
27
use teams_core::{
28
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
29
LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
28
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, LinkPreview,
29
MarkKind, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
30
30
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
31
31
};
32
32
@@ -42,8 +42,8 @@ use super::avatar::{person_avatar, square_avatar};
42
42
use super::draft_style::draft_style;
43
43
use super::emoji_popup::{self, EmojiPopup};
44
44
use super::format_toolbar::{self, FormatButton};
45
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};
46
45
use super::fun_picker::{FunPicker, FunPickerEvent};
46
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};
47
47
use super::widgets::{icon, symbol};
48
48
use crate::app_state::AppState;
49
49
use crate::emoji;
@@ -137,7 +137,9 @@ impl Outgoing {
137
137
match objects.next() {
138
138
Some(OutgoingImage::Inline(_)) => {
139
139
uploaded += 1;
140
html.push_str(&format!("<img src=\"../hostedContents/{uploaded}/$value\">"));
140
html.push_str(&format!(
141
"<img src=\"../hostedContents/{uploaded}/$value\">"
142
));
141
143
}
142
144
Some(OutgoingImage::Remote(remote)) => html.push_str(&remote.html()),
143
145
None => {}
@@ -1332,12 +1334,9 @@ impl Composer {
1332
1334
return;
1333
1335
};
1334
1336
self.link.lookup = Some(cx.spawn(async move |this, cx| {
1335
cx.background_executor()
1336
.timer(LINK_PREVIEW_DEBOUNCE)
1337
.await;
1337
cx.background_executor().timer(LINK_PREVIEW_DEBOUNCE).await;
1338
1338
let task_url = url.clone();
1339
let receiver =
1340
runtime::spawn(async move { engine.link_preview_for(&task_url).await });
1339
let receiver = runtime::spawn(async move { engine.link_preview_for(&task_url).await });
1341
1340
if let Ok(Ok(preview)) = receiver.await {
1342
1341
this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))
1343
1342
.ok();
@@ -1345,7 +1344,12 @@ impl Composer {
1345
1344
}));
1346
1345
}
1347
1346
1348
fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {
1347
fn finish_link_preview(
1348
&mut self,
1349
url: &str,
1350
preview: Option<LinkPreview>,
1351
cx: &mut Context<Self>,
1352
) {
1349
1353
let image = preview.as_ref().and_then(LinkPreview::image);
1350
1354
if !self.link.apply(url, preview) {
1351
1355
return;
@@ -1385,15 +1389,13 @@ impl Composer {
1385
1389
})
1386
1390
.ok();
1387
1391
});
1388
Some(
1389
div().w_full().mb(px(6.)).child(link_preview_card(
1390
preview,
1391
"composer-link-preview".to_owned(),
1392
&self.app.read(cx).directory,
1393
true,
1394
Some(close),
1395
)),
1396
)
1392
Some(div().w_full().mb(px(6.)).child(link_preview_card(
1393
preview,
1394
"composer-link-preview".to_owned(),
1395
&self.app.read(cx).directory,
1396
true,
1397
Some(close),
1398
)))
1397
1399
}
1398
1400
1399
1401
fn popup_is_open(&self) -> bool {
@@ -2334,7 +2336,9 @@ impl Composer {
2334
2336
.rounded(px(10.))
2335
2337
.bg(theme::row_hover())
2336
2338
.child(match edit.scheduled {
2337
Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),
2339
Some(_) => {
2340
symbol("schedule_send", 14., theme::accent_text()).into_any_element()
2341
}
2338
2342
None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
2339
2343
})
2340
2344
.child(
@@ -2499,7 +2503,11 @@ impl Render for Composer {
2499
2503
.cursor_pointer()
2500
2504
.hover(|button| button.bg(theme::popup_hover()))
2501
2505
.tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))
2502
.child(symbol("attach_file", COMPOSER_ICON_SIZE, theme::text_muted()))
2506
.child(symbol(
2507
"attach_file",
2508
COMPOSER_ICON_SIZE,
2509
theme::text_muted(),
2510
))
2503
2511
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))
2504
2512
});
2505
2513
let composer = cx.weak_entity();
@@ -2992,14 +3000,22 @@ mod tests {
2992
3000
#[test]
2993
3001
fn a_gif_title_is_escaped_in_the_html() {
2994
3002
let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);
2995
assert!(outgoing.html().contains("alt=\"a "b" <c>\""));
3003
assert!(
3004
outgoing
3005
.html()
3006
.contains("alt=\"a "b" <c>\"")
3007
);
2996
3008
}
2997
3009
2998
3010
#[test]
2999
3011
fn a_sticker_carries_the_sticker_itemtype() {
3000
3012
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);
3001
3013
let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);
3002
assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));
3014
assert!(
3015
outgoing
3016
.html()
3017
.contains("itemtype=\"http://schema.skype.com/Sticker\"")
3018
);
3003
3019
assert!(outgoing.html().contains("width=\"250\" height=\"250\""));
3004
3020
}
3005
3021
@@ -3312,7 +3328,11 @@ mod tests {
3312
3328
assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));
3313
3329
assert_eq!(typist.value(), "\u{FFFC}");
3314
3330
let outgoing = typist.outgoing();
3315
assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));
3331
assert!(
3332
outgoing
3333
.html()
3334
.starts_with("<img src=\"https://media0.giphy.com/")
3335
);
3316
3336
assert!(outgoing.extras().images.is_empty());
3317
3337
typist.press("ctrl-z");
3318
3338
assert_eq!(typist.value(), "");
@@ -25,8 +25,8 @@ use gpui_kit::prelude::FluentBuilder as _;25
use gpui_kit::*;25
use gpui_kit::*;26
use serde::{Deserialize, Serialize};26
use serde::{Deserialize, Serialize};27
use teams_core::{27
use teams_core::{28
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,28
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, LinkPreview,29
LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,29
MarkKind, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,30
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,30
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,31
};31
};32
32
@@ -42,8 +42,8 @@ use super::avatar::{person_avatar, square_avatar};42
use super::draft_style::draft_style;42
use super::draft_style::draft_style;43
use super::emoji_popup::{self, EmojiPopup};43
use super::emoji_popup::{self, EmojiPopup};44
use super::format_toolbar::{self, FormatButton};44
use super::format_toolbar::{self, FormatButton};45
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};46
use super::fun_picker::{FunPicker, FunPickerEvent};45
use super::fun_picker::{FunPicker, FunPickerEvent};46
use super::link_preview::{ComposeLink, draft_link, link_preview_card, meeting_join_chip};47
use super::widgets::{icon, symbol};47
use super::widgets::{icon, symbol};48
use crate::app_state::AppState;48
use crate::app_state::AppState;49
use crate::emoji;49
use crate::emoji;@@ -137,7 +137,9 @@ impl Outgoing {137
match objects.next() {137
match objects.next() {138
Some(OutgoingImage::Inline(_)) => {138
Some(OutgoingImage::Inline(_)) => {139
uploaded += 1;139
uploaded += 1;140
html.push_str(&format!("<img src=\"../hostedContents/{uploaded}/$value\">"));140
html.push_str(&format!(141
"<img src=\"../hostedContents/{uploaded}/$value\">"142
));141
}143
}142
Some(OutgoingImage::Remote(remote)) => html.push_str(&remote.html()),144
Some(OutgoingImage::Remote(remote)) => html.push_str(&remote.html()),143
None => {}145
None => {}@@ -1332,12 +1334,9 @@ impl Composer {1332
return;1334
return;1333
};1335
};1334
self.link.lookup = Some(cx.spawn(async move |this, cx| {1336
self.link.lookup = Some(cx.spawn(async move |this, cx| {1335
cx.background_executor()1337
cx.background_executor().timer(LINK_PREVIEW_DEBOUNCE).await;1336
.timer(LINK_PREVIEW_DEBOUNCE)1337
.await;1338
let task_url = url.clone();1338
let task_url = url.clone();1339
let receiver =1339
let receiver = runtime::spawn(async move { engine.link_preview_for(&task_url).await });1340
runtime::spawn(async move { engine.link_preview_for(&task_url).await });1341
if let Ok(Ok(preview)) = receiver.await {1340
if let Ok(Ok(preview)) = receiver.await {1342
this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))1341
this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))1343
.ok();1342
.ok();@@ -1345,7 +1344,12 @@ impl Composer {1345
}));1344
}));1346
}1345
}1347
1346
1348
fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {1347
fn finish_link_preview(1348
&mut self,1349
url: &str,1350
preview: Option<LinkPreview>,1351
cx: &mut Context<Self>,1352
) {1349
let image = preview.as_ref().and_then(LinkPreview::image);1353
let image = preview.as_ref().and_then(LinkPreview::image);1350
if !self.link.apply(url, preview) {1354
if !self.link.apply(url, preview) {1351
return;1355
return;@@ -1385,15 +1389,13 @@ impl Composer {1385
})1389
})1386
.ok();1390
.ok();1387
});1391
});1388
Some(1392
Some(div().w_full().mb(px(6.)).child(link_preview_card(1389
div().w_full().mb(px(6.)).child(link_preview_card(1393
preview,1390
preview,1394
"composer-link-preview".to_owned(),1391
"composer-link-preview".to_owned(),1395
&self.app.read(cx).directory,1392
&self.app.read(cx).directory,1396
true,1393
true,1397
Some(close),1394
Some(close),1398
)))1395
)),1396
)1397
}1399
}1398
1400
1399
fn popup_is_open(&self) -> bool {1401
fn popup_is_open(&self) -> bool {@@ -2334,7 +2336,9 @@ impl Composer {2334
.rounded(px(10.))2336
.rounded(px(10.))2335
.bg(theme::row_hover())2337
.bg(theme::row_hover())2336
.child(match edit.scheduled {2338
.child(match edit.scheduled {2337
Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),2339
Some(_) => {2340
symbol("schedule_send", 14., theme::accent_text()).into_any_element()2341
}2338
None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),2342
None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),2339
})2343
})2340
.child(2344
.child(@@ -2499,7 +2503,11 @@ impl Render for Composer {2499
.cursor_pointer()2503
.cursor_pointer()2500
.hover(|button| button.bg(theme::popup_hover()))2504
.hover(|button| button.bg(theme::popup_hover()))2501
.tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))2505
.tooltip(|window, cx| Tooltip::new("Attach file").build(window, cx))2502
.child(symbol("attach_file", COMPOSER_ICON_SIZE, theme::text_muted()))2506
.child(symbol(2507
"attach_file",2508
COMPOSER_ICON_SIZE,2509
theme::text_muted(),2510
))2503
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2511
.on_click(cx.listener(|this, _, window, cx| this.open_picker(window, cx)))2504
});2512
});2505
let composer = cx.weak_entity();2513
let composer = cx.weak_entity();@@ -2992,14 +3000,22 @@ mod tests {2992
#[test]3000
#[test]2993
fn a_gif_title_is_escaped_in_the_html() {3001
fn a_gif_title_is_escaped_in_the_html() {2994
let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);3002
let outgoing = outgoing_with("\u{FFFC}", vec![remote_gif("a \"b\" <c>")]);2995
assert!(outgoing.html().contains("alt=\"a "b" <c>\""));3003
assert!(3004
outgoing3005
.html()3006
.contains("alt=\"a "b" <c>\"")3007
);2996
}3008
}2997
3009
2998
#[test]3010
#[test]2999
fn a_sticker_carries_the_sticker_itemtype() {3011
fn a_sticker_carries_the_sticker_itemtype() {3000
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);3012
let sticker = super::RemoteImage::sticker(crate::stickers::popular()[0]);3001
let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);3013
let outgoing = outgoing_with("\u{FFFC}", vec![super::OutgoingImage::Remote(sticker)]);3002
assert!(outgoing.html().contains("itemtype=\"http://schema.skype.com/Sticker\""));3014
assert!(3015
outgoing3016
.html()3017
.contains("itemtype=\"http://schema.skype.com/Sticker\"")3018
);3003
assert!(outgoing.html().contains("width=\"250\" height=\"250\""));3019
assert!(outgoing.html().contains("width=\"250\" height=\"250\""));3004
}3020
}3005
3021
@@ -3312,7 +3328,11 @@ mod tests {3312
assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));3328
assert!(typist.cx.update(|cx| composer.read(cx).can_send(cx)));3313
assert_eq!(typist.value(), "\u{FFFC}");3329
assert_eq!(typist.value(), "\u{FFFC}");3314
let outgoing = typist.outgoing();3330
let outgoing = typist.outgoing();3315
assert!(outgoing.html().starts_with("<img src=\"https://media0.giphy.com/"));3331
assert!(3332
outgoing3333
.html()3334
.starts_with("<img src=\"https://media0.giphy.com/")3335
);3316
assert!(outgoing.extras().images.is_empty());3336
assert!(outgoing.extras().images.is_empty());3317
typist.press("ctrl-z");3337
typist.press("ctrl-z");3318
assert_eq!(typist.value(), "");3338
assert_eq!(typist.value(), "");@@ -35,10 +35,10 @@ use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_
35
35
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
36
36
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
37
37
use super::post_card::render_post;
38
use super::toolbar_placement::{TimelineBounds, record_bounds};
39
38
use super::profile_card::opens_profile;
40
39
use super::reaction_picker::{PickHandler, ReactionPicker};
41
40
use super::reaction_pills::{ReactionControls, ReactionPopover};
41
use super::toolbar_placement::{TimelineBounds, record_bounds};
42
42
use super::widgets::{icon, symbol};
43
43
use crate::agents::{AgentRun, StartRequest};
44
44
use crate::app_state::{AppEvent, AppState, Selection, selection_title};
@@ -53,7 +53,6 @@ use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
53
53
use crate::notice::short_error;
54
54
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
55
55
use crate::pending_rows::pending_row;
56
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
57
56
use crate::people::{local_names, resolve_names};
58
57
use crate::reaction_model::UNKNOWN_REACTOR;
59
58
use crate::read_state::{ReadTrigger, plan_read};
@@ -64,9 +63,10 @@ use crate::rows::{
64
63
reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,
65
64
};
66
65
use crate::runtime;
67
use crate::translation::TranslationLine;
66
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
68
67
use crate::sidebar_model::{AvatarSpec, Face};
69
68
use crate::theme;
69
use crate::translation::TranslationLine;
70
70
use crate::typing::typing_tooltip;
71
71
use feed::{FeedStash, subject_input};
72
72
use render_env::RenderEnv;
@@ -416,11 +416,21 @@ impl ConversationView {
416
416
Self::build(app, None, window, cx)
417
417
}
418
418
419
pub fn pinned_to(app: Entity<AppState>, selection: Selection, window: &mut Window, cx: &mut Context<Self>) -> Self {
419
pub fn pinned_to(
420
app: Entity<AppState>,
421
selection: Selection,
422
window: &mut Window,
423
cx: &mut Context<Self>,
424
) -> Self {
420
425
Self::build(app, Some(selection), window, cx)
421
426
}
422
427
423
fn build(app: Entity<AppState>, pinned: Option<Selection>, window: &mut Window, cx: &mut Context<Self>) -> Self {
428
fn build(
429
app: Entity<AppState>,
430
pinned: Option<Selection>,
431
window: &mut Window,
432
cx: &mut Context<Self>,
433
) -> Self {
424
434
let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));
425
435
let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));
426
436
let subject = subject_input(window, cx);
@@ -744,7 +754,11 @@ impl ConversationView {
744
754
_ => member_stack(&app.directory, &faces, faces.len()).into_any_element(),
745
755
};
746
756
h_flex()
747
.h(px(if flat { AVATAR_SIZE + 4. } else { TYPING_LINE_HEIGHT }))
757
.h(px(if flat {
758
AVATAR_SIZE + 4.
759
} else {
760
TYPING_LINE_HEIGHT
761
}))
748
762
.flex_none()
749
763
.px(px(20.))
750
764
.gap(px(if flat { AVATAR_GAP } else { 6. }))
@@ -2709,8 +2723,9 @@ impl ConversationView {
2709
2723
}
2710
2724
})
2711
2725
.collect();
2712
let manage_agents = (!entries.is_empty())
2713
.then(|| Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action);
2726
let manage_agents = (!entries.is_empty()).then(|| {
2727
Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action
2728
});
2714
2729
(entries, manage_agents)
2715
2730
}
2716
2731
@@ -35,10 +35,10 @@ use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_35
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};35
use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};36
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};36
use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};37
use super::post_card::render_post;37
use super::post_card::render_post;38
use super::toolbar_placement::{TimelineBounds, record_bounds};39
use super::profile_card::opens_profile;38
use super::profile_card::opens_profile;40
use super::reaction_picker::{PickHandler, ReactionPicker};39
use super::reaction_picker::{PickHandler, ReactionPicker};41
use super::reaction_pills::{ReactionControls, ReactionPopover};40
use super::reaction_pills::{ReactionControls, ReactionPopover};41
use super::toolbar_placement::{TimelineBounds, record_bounds};42
use super::widgets::{icon, symbol};42
use super::widgets::{icon, symbol};43
use crate::agents::{AgentRun, StartRequest};43
use crate::agents::{AgentRun, StartRequest};44
use crate::app_state::{AppEvent, AppState, Selection, selection_title};44
use crate::app_state::{AppEvent, AppState, Selection, selection_title};@@ -53,7 +53,6 @@ use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};53
use crate::notice::short_error;53
use crate::notice::short_error;54
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};54
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};55
use crate::pending_rows::pending_row;55
use crate::pending_rows::pending_row;56
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;57
use crate::people::{local_names, resolve_names};56
use crate::people::{local_names, resolve_names};58
use crate::reaction_model::UNKNOWN_REACTOR;57
use crate::reaction_model::UNKNOWN_REACTOR;59
use crate::read_state::{ReadTrigger, plan_read};58
use crate::read_state::{ReadTrigger, plan_read};@@ -64,9 +63,10 @@ use crate::rows::{64
reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,63
reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,65
};64
};66
use crate::runtime;65
use crate::runtime;67
use crate::translation::TranslationLine;66
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;68
use crate::sidebar_model::{AvatarSpec, Face};67
use crate::sidebar_model::{AvatarSpec, Face};69
use crate::theme;68
use crate::theme;69
use crate::translation::TranslationLine;70
use crate::typing::typing_tooltip;70
use crate::typing::typing_tooltip;71
use feed::{FeedStash, subject_input};71
use feed::{FeedStash, subject_input};72
use render_env::RenderEnv;72
use render_env::RenderEnv;@@ -416,11 +416,21 @@ impl ConversationView {416
Self::build(app, None, window, cx)416
Self::build(app, None, window, cx)417
}417
}418
418
419
pub fn pinned_to(app: Entity<AppState>, selection: Selection, window: &mut Window, cx: &mut Context<Self>) -> Self {419
pub fn pinned_to(420
app: Entity<AppState>,421
selection: Selection,422
window: &mut Window,423
cx: &mut Context<Self>,424
) -> Self {420
Self::build(app, Some(selection), window, cx)425
Self::build(app, Some(selection), window, cx)421
}426
}422
427
423
fn build(app: Entity<AppState>, pinned: Option<Selection>, window: &mut Window, cx: &mut Context<Self>) -> Self {428
fn build(429
app: Entity<AppState>,430
pinned: Option<Selection>,431
window: &mut Window,432
cx: &mut Context<Self>,433
) -> Self {424
let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));434
let scroller = cx.new(|cx| MessageScrollerState::new(0, cx));425
let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));435
let composer = cx.new(|cx| Composer::new(app.clone(), window, cx));426
let subject = subject_input(window, cx);436
let subject = subject_input(window, cx);@@ -744,7 +754,11 @@ impl ConversationView {744
_ => member_stack(&app.directory, &faces, faces.len()).into_any_element(),754
_ => member_stack(&app.directory, &faces, faces.len()).into_any_element(),745
};755
};746
h_flex()756
h_flex()747
.h(px(if flat { AVATAR_SIZE + 4. } else { TYPING_LINE_HEIGHT }))757
.h(px(if flat {758
AVATAR_SIZE + 4.759
} else {760
TYPING_LINE_HEIGHT761
}))748
.flex_none()762
.flex_none()749
.px(px(20.))763
.px(px(20.))750
.gap(px(if flat { AVATAR_GAP } else { 6. }))764
.gap(px(if flat { AVATAR_GAP } else { 6. }))@@ -2709,8 +2723,9 @@ impl ConversationView {2709
}2723
}2710
})2724
})2711
.collect();2725
.collect();2712
let manage_agents = (!entries.is_empty())2726
let manage_agents = (!entries.is_empty()).then(|| {2713
.then(|| Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action);2727
Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action2728
});2714
(entries, manage_agents)2729
(entries, manage_agents)2715
}2730
}2716
2731
@@ -247,12 +247,12 @@ impl ConversationView {
247
247
.font_weight(FontWeight::SEMIBOLD)
248
248
.cursor_pointer()
249
249
.hover(|button| button.bg(theme::accent_text()))
250
.on_click(
251
cx.listener(|this, _, window, cx| this.open_new_post(window, cx)),
252
)
250
.on_click(cx.listener(|this, _, window, cx| {
251
this.open_new_post(window, cx)
252
}))
253
253
.child(icon(IconName::Plus, 14., theme::on_accent()))
254
254
.child("New post"),
255
)
255
),
256
256
)
257
257
.into_any_element(),
258
258
);
@@ -247,12 +247,12 @@ impl ConversationView {247
.font_weight(FontWeight::SEMIBOLD)247
.font_weight(FontWeight::SEMIBOLD)248
.cursor_pointer()248
.cursor_pointer()249
.hover(|button| button.bg(theme::accent_text()))249
.hover(|button| button.bg(theme::accent_text()))250
.on_click(250
.on_click(cx.listener(|this, _, window, cx| {251
cx.listener(|this, _, window, cx| this.open_new_post(window, cx)),251
this.open_new_post(window, cx)252
)252
}))253
.child(icon(IconName::Plus, 14., theme::on_accent()))253
.child(icon(IconName::Plus, 14., theme::on_accent()))254
.child("New post"),254
.child("New post"),255
)255
),256
)256
)257
.into_any_element(),257
.into_any_element(),258
);258
);@@ -15,8 +15,8 @@ use crate::app_state::AppState;
15
15
use crate::rows::{Delivery, MessageRow, PostRow};
16
16
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
17
17
use crate::translation::TranslationLine;
18
use crate::views::attachments::ImageOpen;
19
18
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
19
use crate::views::attachments::ImageOpen;
20
20
use crate::views::composer::Composer;
21
21
use crate::views::message_row::{DeliveryActions, RowActions};
22
22
use crate::views::post_card::{PostAction, PostActions};
@@ -15,8 +15,8 @@ use crate::app_state::AppState;15
use crate::rows::{Delivery, MessageRow, PostRow};15
use crate::rows::{Delivery, MessageRow, PostRow};16
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;16
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;17
use crate::translation::TranslationLine;17
use crate::translation::TranslationLine;18
use crate::views::attachments::ImageOpen;19
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};18
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};19
use crate::views::attachments::ImageOpen;20
use crate::views::composer::Composer;20
use crate::views::composer::Composer;21
use crate::views::message_row::{DeliveryActions, RowActions};21
use crate::views::message_row::{DeliveryActions, RowActions};22
use crate::views::post_card::{PostAction, PostActions};22
use crate::views::post_card::{PostAction, PostActions};@@ -299,8 +299,14 @@ fn arrow(offset: Pixels) -> impl IntoElement {
299
299
move |bounds, _, window, _| {
300
300
let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));
301
301
let mut builder = PathBuilder::fill();
302
builder.move_to(point(tip.x - px(ARROW_WIDTH / 2.), bounds.origin.y - px(1.)));
303
builder.line_to(point(tip.x + px(ARROW_WIDTH / 2.), bounds.origin.y - px(1.)));
302
builder.move_to(point(
303
tip.x - px(ARROW_WIDTH / 2.),
304
bounds.origin.y - px(1.),
305
));
306
builder.line_to(point(
307
tip.x + px(ARROW_WIDTH / 2.),
308
bounds.origin.y - px(1.),
309
));
304
310
builder.line_to(point(tip.x, tip.y));
305
311
builder.close();
306
312
if let Ok(path) = builder.build() {
@@ -299,8 +299,14 @@ fn arrow(offset: Pixels) -> impl IntoElement {299
move |bounds, _, window, _| {299
move |bounds, _, window, _| {300
let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));300
let tip = point(bounds.origin.x + offset, bounds.origin.y + px(ARROW_HEIGHT));301
let mut builder = PathBuilder::fill();301
let mut builder = PathBuilder::fill();302
builder.move_to(point(tip.x - px(ARROW_WIDTH / 2.), bounds.origin.y - px(1.)));302
builder.move_to(point(303
builder.line_to(point(tip.x + px(ARROW_WIDTH / 2.), bounds.origin.y - px(1.)));303
tip.x - px(ARROW_WIDTH / 2.),304
bounds.origin.y - px(1.),305
));306
builder.line_to(point(307
tip.x + px(ARROW_WIDTH / 2.),308
bounds.origin.y - px(1.),309
));304
builder.line_to(point(tip.x, tip.y));310
builder.line_to(point(tip.x, tip.y));305
builder.close();311
builder.close();306
if let Ok(path) = builder.build() {312
if let Ok(path) = builder.build() {@@ -14,12 +14,12 @@ use super::widgets::symbol;
14
14
use crate::app_state::AppState;
15
15
use crate::downloads;
16
16
use crate::image_view_gallery::{GalleryItem, ViewerRequest};
17
use crate::theme;
18
17
use crate::image_view_math::{
19
MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size,
20
fit_scale, image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,
18
MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale,
19
image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,
21
20
thumbnail_window, toggle_target, wheel_scale, zoom_at,
22
21
};
22
use crate::theme;
23
23
24
24
const HEADER_HEIGHT: f32 = 52.;
25
25
const FOOTER_HEIGHT: f32 = 120.;
@@ -133,7 +133,10 @@ fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
133
133
fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {
134
134
if quarter_turns != 0 {
135
135
let bytes = rotated_png(path, quarter_turns)?;
136
return Some(ClipboardItem::new_image(&Image::from_bytes(ImageFormat::Png, bytes)));
136
return Some(ClipboardItem::new_image(&Image::from_bytes(
137
ImageFormat::Png,
138
bytes,
139
)));
137
140
}
138
141
let bytes = std::fs::read(path).ok()?;
139
142
let format = clipboard_format(&bytes)?;
@@ -146,7 +149,10 @@ fn suggested_name(path: &Path, rotated: bool) -> String {
146
149
.map(|name| name.to_string_lossy().into_owned())
147
150
.unwrap_or_else(|| "image".to_owned());
148
151
if rotated {
149
return Path::new(&name).with_extension("png").to_string_lossy().into_owned();
152
return Path::new(&name)
153
.with_extension("png")
154
.to_string_lossy()
155
.into_owned();
150
156
}
151
157
if path.extension().is_some() {
152
158
return name;
@@ -250,7 +256,10 @@ impl ImageViewer {
250
256
Self::thumbnail_capacity(window),
251
257
);
252
258
let first = visible.start.min(self.index.saturating_sub(1));
253
let last = visible.end.saturating_sub(1).max((self.index + 1).min(last_index));
259
let last = visible
260
.end
261
.saturating_sub(1)
262
.max((self.index + 1).min(last_index));
254
263
let directory = &self.app.read(cx).directory;
255
264
let missing: Vec<_> = self
256
265
.items
@@ -411,7 +420,11 @@ impl ImageViewer {
411
420
layout.pan.0 + f32::from(event.position.x - last.x),
412
421
layout.pan.1 + f32::from(event.position.y - last.y),
413
422
);
414
self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);
423
self.pan = clamp_pan(
424
moved,
425
display_size(layout.source, layout.scale),
426
layout.stage,
427
);
415
428
self.drag_from = Some(event.position);
416
429
cx.notify();
417
430
}
@@ -534,7 +547,9 @@ impl ImageViewer {
534
547
this.show_notice("Image copied", cx);
535
548
}
536
549
None => {
537
cx.write_to_clipboard(ClipboardItem::new_string(fallback.display().to_string()));
550
cx.write_to_clipboard(ClipboardItem::new_string(
551
fallback.display().to_string(),
552
));
538
553
this.show_notice("Copied file path", cx);
539
554
}
540
555
})
@@ -633,7 +648,9 @@ impl ImageViewer {
633
648
let sender_id = item.and_then(|item| item.sender_id.clone());
634
649
let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);
635
650
let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);
636
let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();
651
let zoom_label = layout
652
.map(|layout| percent_label(layout.scale))
653
.unwrap_or_default();
637
654
let loaded = layout.is_some();
638
655
h_flex()
639
656
.id("viewer-header")
@@ -651,17 +668,12 @@ impl ImageViewer {
651
668
.min_w_0()
652
669
.gap(px(10.))
653
670
.items_center()
654
.child(
655
div()
656
.size(px(AVATAR_SIZE))
657
.flex_none()
658
.child(person_avatar(
659
&self.app.read(cx).directory,
660
sender_id.as_deref(),
661
&author,
662
AVATAR_SIZE,
663
)),
664
)
671
.child(div().size(px(AVATAR_SIZE)).flex_none().child(person_avatar(
672
&self.app.read(cx).directory,
673
sender_id.as_deref(),
674
&author,
675
AVATAR_SIZE,
676
)))
665
677
.child(
666
678
v_flex()
667
679
.flex_1()
@@ -808,7 +820,8 @@ impl ImageViewer {
808
820
.image(&item.image.url)
809
821
.map(|entry| entry.path.clone().into())
810
822
} else {
811
self.rotated_render().map(|render| ImageSource::Render(render.clone()))
823
self.rotated_render()
824
.map(|render| ImageSource::Render(render.clone()))
812
825
};
813
826
let Some(source) = source else {
814
827
return loading_placeholder();
@@ -873,11 +886,9 @@ impl ImageViewer {
873
886
.bg(white().opacity(0.08))
874
887
.when(!current, |frame| frame.opacity(0.7))
875
888
.map(|frame| match path {
876
Some(path) => frame.child(
877
img(path)
878
.size_full()
879
.object_fit(ObjectFit::Cover),
880
),
889
Some(path) => {
890
frame.child(img(path).size_full().object_fit(ObjectFit::Cover))
891
}
881
892
None => frame.child(symbol("image", 18., white().opacity(0.5))),
882
893
}),
883
894
)
@@ -14,12 +14,12 @@ use super::widgets::symbol;14
use crate::app_state::AppState;14
use crate::app_state::AppState;15
use crate::downloads;15
use crate::downloads;16
use crate::image_view_gallery::{GalleryItem, ViewerRequest};16
use crate::image_view_gallery::{GalleryItem, ViewerRequest};17
use crate::theme;18
use crate::image_view_math::{17
use crate::image_view_math::{19
MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size,18
MAX_ZOOM, Pair, View, clamp_pan, clamp_scale, counter_label, display_size, fit_scale,20
fit_scale, image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,19
image_origin, next_rotation, percent_label, rotated_size, step_index, step_scale,21
thumbnail_window, toggle_target, wheel_scale, zoom_at,20
thumbnail_window, toggle_target, wheel_scale, zoom_at,22
};21
};22
use crate::theme;23
23
24
const HEADER_HEIGHT: f32 = 52.;24
const HEADER_HEIGHT: f32 = 52.;25
const FOOTER_HEIGHT: f32 = 120.;25
const FOOTER_HEIGHT: f32 = 120.;@@ -133,7 +133,10 @@ fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {133
fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {133
fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {134
if quarter_turns != 0 {134
if quarter_turns != 0 {135
let bytes = rotated_png(path, quarter_turns)?;135
let bytes = rotated_png(path, quarter_turns)?;136
return Some(ClipboardItem::new_image(&Image::from_bytes(ImageFormat::Png, bytes)));136
return Some(ClipboardItem::new_image(&Image::from_bytes(137
ImageFormat::Png,138
bytes,139
)));137
}140
}138
let bytes = std::fs::read(path).ok()?;141
let bytes = std::fs::read(path).ok()?;139
let format = clipboard_format(&bytes)?;142
let format = clipboard_format(&bytes)?;@@ -146,7 +149,10 @@ fn suggested_name(path: &Path, rotated: bool) -> String {146
.map(|name| name.to_string_lossy().into_owned())149
.map(|name| name.to_string_lossy().into_owned())147
.unwrap_or_else(|| "image".to_owned());150
.unwrap_or_else(|| "image".to_owned());148
if rotated {151
if rotated {149
return Path::new(&name).with_extension("png").to_string_lossy().into_owned();152
return Path::new(&name)153
.with_extension("png")154
.to_string_lossy()155
.into_owned();150
}156
}151
if path.extension().is_some() {157
if path.extension().is_some() {152
return name;158
return name;@@ -250,7 +256,10 @@ impl ImageViewer {250
Self::thumbnail_capacity(window),256
Self::thumbnail_capacity(window),251
);257
);252
let first = visible.start.min(self.index.saturating_sub(1));258
let first = visible.start.min(self.index.saturating_sub(1));253
let last = visible.end.saturating_sub(1).max((self.index + 1).min(last_index));259
let last = visible260
.end261
.saturating_sub(1)262
.max((self.index + 1).min(last_index));254
let directory = &self.app.read(cx).directory;263
let directory = &self.app.read(cx).directory;255
let missing: Vec<_> = self264
let missing: Vec<_> = self256
.items265
.items@@ -411,7 +420,11 @@ impl ImageViewer {411
layout.pan.0 + f32::from(event.position.x - last.x),420
layout.pan.0 + f32::from(event.position.x - last.x),412
layout.pan.1 + f32::from(event.position.y - last.y),421
layout.pan.1 + f32::from(event.position.y - last.y),413
);422
);414
self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);423
self.pan = clamp_pan(424
moved,425
display_size(layout.source, layout.scale),426
layout.stage,427
);415
self.drag_from = Some(event.position);428
self.drag_from = Some(event.position);416
cx.notify();429
cx.notify();417
}430
}@@ -534,7 +547,9 @@ impl ImageViewer {534
this.show_notice("Image copied", cx);547
this.show_notice("Image copied", cx);535
}548
}536
None => {549
None => {537
cx.write_to_clipboard(ClipboardItem::new_string(fallback.display().to_string()));550
cx.write_to_clipboard(ClipboardItem::new_string(551
fallback.display().to_string(),552
));538
this.show_notice("Copied file path", cx);553
this.show_notice("Copied file path", cx);539
}554
}540
})555
})@@ -633,7 +648,9 @@ impl ImageViewer {633
let sender_id = item.and_then(|item| item.sender_id.clone());648
let sender_id = item.and_then(|item| item.sender_id.clone());634
let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);649
let can_zoom_out = layout.is_some_and(|layout| layout.scale > layout.fit);635
let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);650
let can_zoom_in = layout.is_some_and(|layout| layout.scale < MAX_ZOOM);636
let zoom_label = layout.map(|layout| percent_label(layout.scale)).unwrap_or_default();651
let zoom_label = layout652
.map(|layout| percent_label(layout.scale))653
.unwrap_or_default();637
let loaded = layout.is_some();654
let loaded = layout.is_some();638
h_flex()655
h_flex()639
.id("viewer-header")656
.id("viewer-header")@@ -651,17 +668,12 @@ impl ImageViewer {651
.min_w_0()668
.min_w_0()652
.gap(px(10.))669
.gap(px(10.))653
.items_center()670
.items_center()654
.child(671
.child(div().size(px(AVATAR_SIZE)).flex_none().child(person_avatar(655
div()672
&self.app.read(cx).directory,656
.size(px(AVATAR_SIZE))673
sender_id.as_deref(),657
.flex_none()674
&author,658
.child(person_avatar(675
AVATAR_SIZE,659
&self.app.read(cx).directory,676
)))660
sender_id.as_deref(),661
&author,662
AVATAR_SIZE,663
)),664
)665
.child(677
.child(666
v_flex()678
v_flex()667
.flex_1()679
.flex_1()@@ -808,7 +820,8 @@ impl ImageViewer {808
.image(&item.image.url)820
.image(&item.image.url)809
.map(|entry| entry.path.clone().into())821
.map(|entry| entry.path.clone().into())810
} else {822
} else {811
self.rotated_render().map(|render| ImageSource::Render(render.clone()))823
self.rotated_render()824
.map(|render| ImageSource::Render(render.clone()))812
};825
};813
let Some(source) = source else {826
let Some(source) = source else {814
return loading_placeholder();827
return loading_placeholder();@@ -873,11 +886,9 @@ impl ImageViewer {873
.bg(white().opacity(0.08))886
.bg(white().opacity(0.08))874
.when(!current, |frame| frame.opacity(0.7))887
.when(!current, |frame| frame.opacity(0.7))875
.map(|frame| match path {888
.map(|frame| match path {876
Some(path) => frame.child(889
Some(path) => {877
img(path)890
frame.child(img(path).size_full().object_fit(ObjectFit::Cover))878
.size_full()891
}879
.object_fit(ObjectFit::Cover),880
),881
None => frame.child(symbol("image", 18., white().opacity(0.5))),892
None => frame.child(symbol("image", 18., white().opacity(0.5))),882
}),893
}),883
)894
)@@ -67,18 +67,23 @@ pub struct RowActions {
67
67
const TOOLBAR_RIGHT_INSET: f32 = 0.;
68
68
69
69
fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {
70
h_flex().w_full().justify_center().mt(px(12.)).mb(px(6.)).child(
71
div()
72
.h(px(24.))
73
.px(px(8.))
74
.flex()
75
.items_center()
76
.rounded(px(12.))
77
.bg(fill)
78
.text_size(px(11.))
79
.text_color(text_color)
80
.child(label.to_owned()),
81
)
70
h_flex()
71
.w_full()
72
.justify_center()
73
.mt(px(12.))
74
.mb(px(6.))
75
.child(
76
div()
77
.h(px(24.))
78
.px(px(8.))
79
.flex()
80
.items_center()
81
.rounded(px(12.))
82
.bg(fill)
83
.text_size(px(11.))
84
.text_color(text_color)
85
.child(label.to_owned()),
86
)
82
87
}
83
88
84
89
fn day_separator(label: &str) -> Div {
@@ -86,7 +91,11 @@ fn day_separator(label: &str) -> Div {
86
91
}
87
92
88
93
fn new_marker() -> Div {
89
separator_pill("New", theme::mention_background(false), theme::accent_text())
94
separator_pill(
95
"New",
96
theme::mention_background(false),
97
theme::accent_text(),
98
)
90
99
}
91
100
92
101
fn bubble(
@@ -137,14 +146,13 @@ fn bubble(
137
146
bubble.border_1().border_color(theme::red())
138
147
})
139
148
.when(scheduled, |bubble| {
140
bubble
141
.border_1()
142
.border_dashed()
143
.border_color(if row.delivery == Delivery::Scheduled(ScheduledState::DeliveryFailed) {
149
bubble.border_1().border_dashed().border_color(
150
if row.delivery == Delivery::Scheduled(ScheduledState::DeliveryFailed) {
144
151
theme::red()
145
152
} else {
146
153
theme::accent()
147
})
154
},
155
)
148
156
});
149
157
let has_reactions = !row.reactions.is_empty();
150
158
let saved = extras.saved;
@@ -414,7 +422,12 @@ pub(super) fn has_text(row: &MessageRow) -> bool {
414
422
&& row.adaptive_cards.is_empty())
415
423
}
416
424
417
fn delivery_link(index: usize, name: &str, label: &'static str, action: RowAction) -> Stateful<Div> {
425
fn delivery_link(
426
index: usize,
427
name: &str,
428
label: &'static str,
429
action: RowAction,
430
) -> Stateful<Div> {
418
431
div()
419
432
.id(ElementId::Name(format!("{name}-{index}").into()))
420
433
.cursor_pointer()
@@ -492,10 +505,10 @@ fn others_row(
492
505
div().id(ElementId::Name(format!("author-{index}").into())),
493
506
profile_user,
494
507
)
495
.text_size(px(12.))
496
.font_weight(FontWeight::SEMIBOLD)
497
.text_color(theme::text_soft())
498
.child(author.clone()),
508
.text_size(px(12.))
509
.font_weight(FontWeight::SEMIBOLD)
510
.text_color(theme::text_soft())
511
.child(author.clone()),
499
512
),
500
513
);
501
514
}
@@ -67,18 +67,23 @@ pub struct RowActions {67
const TOOLBAR_RIGHT_INSET: f32 = 0.;67
const TOOLBAR_RIGHT_INSET: f32 = 0.;68
68
69
fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {69
fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {70
h_flex().w_full().justify_center().mt(px(12.)).mb(px(6.)).child(70
h_flex()71
div()71
.w_full()72
.h(px(24.))72
.justify_center()73
.px(px(8.))73
.mt(px(12.))74
.flex()74
.mb(px(6.))75
.items_center()75
.child(76
.rounded(px(12.))76
div()77
.bg(fill)77
.h(px(24.))78
.text_size(px(11.))78
.px(px(8.))79
.text_color(text_color)79
.flex()80
.child(label.to_owned()),80
.items_center()81
)81
.rounded(px(12.))82
.bg(fill)83
.text_size(px(11.))84
.text_color(text_color)85
.child(label.to_owned()),86
)82
}87
}83
88
84
fn day_separator(label: &str) -> Div {89
fn day_separator(label: &str) -> Div {@@ -86,7 +91,11 @@ fn day_separator(label: &str) -> Div {86
}91
}87
92
88
fn new_marker() -> Div {93
fn new_marker() -> Div {89
separator_pill("New", theme::mention_background(false), theme::accent_text())94
separator_pill(95
"New",96
theme::mention_background(false),97
theme::accent_text(),98
)90
}99
}91
100
92
fn bubble(101
fn bubble(@@ -137,14 +146,13 @@ fn bubble(137
bubble.border_1().border_color(theme::red())146
bubble.border_1().border_color(theme::red())138
})147
})139
.when(scheduled, |bubble| {148
.when(scheduled, |bubble| {140
bubble149
bubble.border_1().border_dashed().border_color(141
.border_1()150
if row.delivery == Delivery::Scheduled(ScheduledState::DeliveryFailed) {142
.border_dashed()143
.border_color(if row.delivery == Delivery::Scheduled(ScheduledState::DeliveryFailed) {144
theme::red()151
theme::red()145
} else {152
} else {146
theme::accent()153
theme::accent()147
})154
},155
)148
});156
});149
let has_reactions = !row.reactions.is_empty();157
let has_reactions = !row.reactions.is_empty();150
let saved = extras.saved;158
let saved = extras.saved;@@ -414,7 +422,12 @@ pub(super) fn has_text(row: &MessageRow) -> bool {414
&& row.adaptive_cards.is_empty())422
&& row.adaptive_cards.is_empty())415
}423
}416
424
417
fn delivery_link(index: usize, name: &str, label: &'static str, action: RowAction) -> Stateful<Div> {425
fn delivery_link(426
index: usize,427
name: &str,428
label: &'static str,429
action: RowAction,430
) -> Stateful<Div> {418
div()431
div()419
.id(ElementId::Name(format!("{name}-{index}").into()))432
.id(ElementId::Name(format!("{name}-{index}").into()))420
.cursor_pointer()433
.cursor_pointer()@@ -492,10 +505,10 @@ fn others_row(492
div().id(ElementId::Name(format!("author-{index}").into())),505
div().id(ElementId::Name(format!("author-{index}").into())),493
profile_user,506
profile_user,494
)507
)495
.text_size(px(12.))508
.text_size(px(12.))496
.font_weight(FontWeight::SEMIBOLD)509
.font_weight(FontWeight::SEMIBOLD)497
.text_color(theme::text_soft())510
.text_color(theme::text_soft())498
.child(author.clone()),511
.child(author.clone()),499
),512
),500
);513
);501
}514
}@@ -5,12 +5,12 @@ pub mod attachments;
5
5
pub mod avatar;
6
6
pub mod call_controls;
7
7
pub mod call_extras;
8
pub mod calls_tab;
9
8
pub mod call_mini;
10
9
pub mod call_mini_window;
11
10
pub mod call_organizer;
12
11
pub mod call_stage;
13
12
pub mod call_view;
13
pub mod calls_tab;
14
14
pub mod card_carousel;
15
15
pub mod card_chart;
16
16
pub mod card_code_block;
@@ -27,10 +27,10 @@ pub mod draft_style;
27
27
pub mod emoji_popup;
28
28
pub mod format_toolbar;
29
29
pub mod forward_dialog;
30
pub mod fun_picker;
30
31
pub mod image_viewer;
31
32
pub mod join_dialog;
32
33
pub mod link_preview;
33
pub mod fun_picker;
34
34
pub mod message_actions;
35
35
pub mod message_row;
36
36
pub mod new_chat;
@@ -43,7 +43,6 @@ pub mod reaction_picker;
43
43
pub mod reaction_pills;
44
44
pub mod saved_panel;
45
45
pub mod scheduled_toolbar;
46
pub mod toolbar_placement;
47
46
pub mod section_dialog;
48
47
pub mod share_bar;
49
48
pub mod shared_tab;
@@ -56,6 +55,7 @@ pub mod status_menu;
56
55
pub mod status_message_dialog;
57
56
pub mod switcher;
58
57
pub mod title_bar;
58
pub mod toolbar_placement;
59
59
pub mod transfer_picker;
60
60
pub mod translation_line;
61
61
pub mod widgets;
@@ -77,12 +77,14 @@ mod tests {
77
77
78
78
#[test]
79
79
fn hover_styles_never_toggle_display() {
80
let toggle = regex::Regex::new(
81
r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)",
82
)
83
.unwrap();
80
let toggle =
81
regex::Regex::new(r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)")
82
.unwrap();
84
83
let mut files = Vec::new();
85
rust_files(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);
84
rust_files(
85
&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"),
86
&mut files,
87
);
86
88
let offenders: Vec<String> = files
87
89
.iter()
88
90
.flat_map(|path| {
@@ -5,12 +5,12 @@ pub mod attachments;5
pub mod avatar;5
pub mod avatar;6
pub mod call_controls;6
pub mod call_controls;7
pub mod call_extras;7
pub mod call_extras;8
pub mod calls_tab;9
pub mod call_mini;8
pub mod call_mini;10
pub mod call_mini_window;9
pub mod call_mini_window;11
pub mod call_organizer;10
pub mod call_organizer;12
pub mod call_stage;11
pub mod call_stage;13
pub mod call_view;12
pub mod call_view;13
pub mod calls_tab;14
pub mod card_carousel;14
pub mod card_carousel;15
pub mod card_chart;15
pub mod card_chart;16
pub mod card_code_block;16
pub mod card_code_block;@@ -27,10 +27,10 @@ pub mod draft_style;27
pub mod emoji_popup;27
pub mod emoji_popup;28
pub mod format_toolbar;28
pub mod format_toolbar;29
pub mod forward_dialog;29
pub mod forward_dialog;30
pub mod fun_picker;30
pub mod image_viewer;31
pub mod image_viewer;31
pub mod join_dialog;32
pub mod join_dialog;32
pub mod link_preview;33
pub mod link_preview;33
pub mod fun_picker;34
pub mod message_actions;34
pub mod message_actions;35
pub mod message_row;35
pub mod message_row;36
pub mod new_chat;36
pub mod new_chat;@@ -43,7 +43,6 @@ pub mod reaction_picker;43
pub mod reaction_pills;43
pub mod reaction_pills;44
pub mod saved_panel;44
pub mod saved_panel;45
pub mod scheduled_toolbar;45
pub mod scheduled_toolbar;46
pub mod toolbar_placement;47
pub mod section_dialog;46
pub mod section_dialog;48
pub mod share_bar;47
pub mod share_bar;49
pub mod shared_tab;48
pub mod shared_tab;@@ -56,6 +55,7 @@ pub mod status_menu;56
pub mod status_message_dialog;55
pub mod status_message_dialog;57
pub mod switcher;56
pub mod switcher;58
pub mod title_bar;57
pub mod title_bar;58
pub mod toolbar_placement;59
pub mod transfer_picker;59
pub mod transfer_picker;60
pub mod translation_line;60
pub mod translation_line;61
pub mod widgets;61
pub mod widgets;@@ -77,12 +77,14 @@ mod tests {77
77
78
#[test]78
#[test]79
fn hover_styles_never_toggle_display() {79
fn hover_styles_never_toggle_display() {80
let toggle = regex::Regex::new(80
let toggle =81
r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)",81
regex::Regex::new(r"hover\([^|]*\|\w+\|\s*\w+\s*\.\s*(hidden|flex|block|grid)\(\)")82
)82
.unwrap();83
.unwrap();84
let mut files = Vec::new();83
let mut files = Vec::new();85
rust_files(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut files);84
rust_files(85
&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"),86
&mut files,87
);86
let offenders: Vec<String> = files88
let offenders: Vec<String> = files87
.iter()89
.iter()88
.flat_map(|path| {90
.flat_map(|path| {@@ -6,10 +6,10 @@ use gpui_kit::*;
6
6
use super::adaptive_card::cards_view;
7
7
use super::attachments::{attachments_view, message_body};
8
8
use super::avatar::{bot_avatar, person_avatar};
9
use super::profile_card::opens_profile;
10
9
use super::link_preview::{link_preview_card, meeting_join_chip};
11
10
use super::message_actions::message_toolbar;
12
11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};
12
use super::profile_card::opens_profile;
13
13
use super::reaction_pills::reaction_pills;
14
14
use super::scheduled_toolbar::scheduled_toolbar;
15
15
use super::toolbar_placement::placed_toolbar;
@@ -156,10 +156,10 @@ fn message_header(
156
156
div().id(ElementId::Name(format!("post-author-{index}").into())),
157
157
profile_user,
158
158
)
159
.text_size(px(13.))
160
.font_weight(FontWeight::SEMIBOLD)
161
.text_color(theme::text())
162
.child(author),
159
.text_size(px(13.))
160
.font_weight(FontWeight::SEMIBOLD)
161
.text_color(theme::text())
162
.child(author),
163
163
)
164
164
.child(
165
165
div()
@@ -6,10 +6,10 @@ use gpui_kit::*;6
use super::adaptive_card::cards_view;6
use super::adaptive_card::cards_view;7
use super::attachments::{attachments_view, message_body};7
use super::attachments::{attachments_view, message_body};8
use super::avatar::{bot_avatar, person_avatar};8
use super::avatar::{bot_avatar, person_avatar};9
use super::profile_card::opens_profile;10
use super::link_preview::{link_preview_card, meeting_join_chip};9
use super::link_preview::{link_preview_card, meeting_join_chip};11
use super::message_actions::message_toolbar;10
use super::message_actions::message_toolbar;12
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};11
use super::message_row::{BODY_SIZE, RowActions, delivery_note, forwarded_header, has_text};12
use super::profile_card::opens_profile;13
use super::reaction_pills::reaction_pills;13
use super::reaction_pills::reaction_pills;14
use super::scheduled_toolbar::scheduled_toolbar;14
use super::scheduled_toolbar::scheduled_toolbar;15
use super::toolbar_placement::placed_toolbar;15
use super::toolbar_placement::placed_toolbar;@@ -156,10 +156,10 @@ fn message_header(156
div().id(ElementId::Name(format!("post-author-{index}").into())),156
div().id(ElementId::Name(format!("post-author-{index}").into())),157
profile_user,157
profile_user,158
)158
)159
.text_size(px(13.))159
.text_size(px(13.))160
.font_weight(FontWeight::SEMIBOLD)160
.font_weight(FontWeight::SEMIBOLD)161
.text_color(theme::text())161
.text_color(theme::text())162
.child(author),162
.child(author),163
)163
)164
.child(164
.child(165
div()165
div()@@ -145,7 +145,9 @@ fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
145
145
.rounded(px(10.))
146
146
.cursor_pointer()
147
147
.when(active, |button| button.bg(theme::surface_raised()))
148
.when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))
148
.when(!active, |button| {
149
button.hover(|button| button.bg(theme::row_hover()))
150
})
149
151
.child(icon(item.icon, ICON_SIZE, color))
150
152
.child(
151
153
div()
@@ -145,7 +145,9 @@ fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {145
.rounded(px(10.))145
.rounded(px(10.))146
.cursor_pointer()146
.cursor_pointer()147
.when(active, |button| button.bg(theme::surface_raised()))147
.when(active, |button| button.bg(theme::surface_raised()))148
.when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))148
.when(!active, |button| {149
button.hover(|button| button.bg(theme::row_hover()))150
})149
.child(icon(item.icon, ICON_SIZE, color))151
.child(icon(item.icon, ICON_SIZE, color))150
.child(152
.child(151
div()153
div()@@ -15,9 +15,9 @@ use super::profile_card::{ProfileCard, ProfileCardEvent};
15
15
use super::rail::RailView;
16
16
use super::saved_panel::{SavedPanel, SavedPanelEvent};
17
17
use super::shortcuts::{
18
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenChannelsTab,
19
OpenCallsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts, ToggleCallCamera,
20
ToggleCallShare,
18
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenCallsTab,
19
OpenChannelsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts,
20
ToggleCallCamera, ToggleCallShare,
21
21
};
22
22
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
23
23
use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
@@ -31,17 +31,24 @@ use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest}
31
31
use crate::app_state::{AppEvent, AppState, Selection};
32
32
use crate::call::{CallMedia, CallWindows};
33
33
use crate::notice::NoticeAction;
34
use crate::user_activity::{self, UserInput};
35
34
use crate::notify::{NotificationCenter, selection_for};
36
35
use crate::sidebar_model::Step;
37
36
use crate::theme;
38
37
use crate::updater::{self, IdleInputs, UpdateStatus};
38
use crate::user_activity::{self, UserInput};
39
39
40
40
actions!(teams, [OpenSwitcher, NewChat, ToggleCallMute]);
41
41
42
42
pub fn bind_keys(cx: &mut App) {
43
43
super::composer::bind_keys(cx);
44
super::shortcuts::bind_scopes(cx, &[Scope::Global, Scope::OutsideComposer, Scope::GlobalOverTextFields]);
44
super::shortcuts::bind_scopes(
45
cx,
46
&[
47
Scope::Global,
48
Scope::OutsideComposer,
49
Scope::GlobalOverTextFields,
50
],
51
);
45
52
}
46
53
47
54
#[derive(Debug, Clone, Copy)]
@@ -91,7 +98,12 @@ pub struct AppShell {
91
98
}
92
99
93
100
impl AppShell {
94
fn sync_call_chat(&mut self, thread: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
101
fn sync_call_chat(
102
&mut self,
103
thread: Option<String>,
104
window: &mut Window,
105
cx: &mut Context<Self>,
106
) {
95
107
match (thread, &self.call_chat) {
96
108
(Some(wanted), Some((open, _))) if &wanted == open => {}
97
109
(Some(wanted), _) => {
@@ -118,15 +130,18 @@ impl AppShell {
118
130
let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));
119
131
let saved_panel = cx.new(|cx| SavedPanel::new(state.clone(), cx));
120
132
let panel_subscriptions = [
121
cx.subscribe(&activity_panel, |this, _, event: &ActivityPanelEvent, cx| match event {
122
ActivityPanelEvent::OpenSettings => this
123
.notifications
124
.update(cx, |center, cx| center.open_settings(cx)),
125
ActivityPanelEvent::Open {
126
conversation_id,
127
message_id,
128
} => this.open_message(conversation_id, message_id, cx),
129
}),
133
cx.subscribe(
134
&activity_panel,
135
|this, _, event: &ActivityPanelEvent, cx| match event {
136
ActivityPanelEvent::OpenSettings => this
137
.notifications
138
.update(cx, |center, cx| center.open_settings(cx)),
139
ActivityPanelEvent::Open {
140
conversation_id,
141
message_id,
142
} => this.open_message(conversation_id, message_id, cx),
143
},
144
),
130
145
cx.subscribe(&saved_panel, |this, _, event: &SavedPanelEvent, cx| {
131
146
let SavedPanelEvent::Open {
132
147
conversation_id,
@@ -136,8 +151,10 @@ impl AppShell {
136
151
}),
137
152
];
138
153
let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
139
cx.subscribe_in(&runs, window, |this, _, event: &AgentRunsEvent, window, cx| {
140
match event {
154
cx.subscribe_in(
155
&runs,
156
window,
157
|this, _, event: &AgentRunsEvent, window, cx| match event {
141
158
AgentRunsEvent::StartRequested(request) => {
142
159
this.open_agent_dialog(request.clone(), window, cx)
143
160
}
@@ -145,8 +162,8 @@ impl AppShell {
145
162
.notifications
146
163
.update(cx, |center, cx| center.open_agent_settings(cx)),
147
164
AgentRunsEvent::Finished(_) => {}
148
}
149
})
165
},
166
)
150
167
});
151
168
let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, cx));
152
169
let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
@@ -182,12 +199,14 @@ impl AppShell {
182
199
let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
183
200
this.user_input.touch();
184
201
if event.keystroke.key == "escape" {
185
this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
202
this.state
203
.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
186
204
}
187
205
});
188
206
let activation_observation = cx.observe_window_activation(window, |this, window, cx| {
189
207
if window.is_window_active() {
190
this.state.update(cx, |state, cx| state.refresh_calendar(cx));
208
this.state
209
.update(cx, |state, cx| state.refresh_calendar(cx));
191
210
}
192
211
});
193
212
let closing = notifications.clone();
@@ -257,7 +276,10 @@ impl AppShell {
257
276
258
277
#[cfg_attr(not(windows), allow(dead_code))]
259
278
fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {
260
if matches!(self.update, UpdateStatus::Failed(_) | UpdateStatus::Installing) {
279
if matches!(
280
self.update,
281
UpdateStatus::Failed(_) | UpdateStatus::Installing
282
) {
261
283
return;
262
284
}
263
285
let Some(paths) = updater::current_paths() else {
@@ -444,11 +466,15 @@ impl AppShell {
444
466
self.switcher = None;
445
467
let app = self.state.clone();
446
468
let dialog = cx.new(|cx| StartDialog::new(app, request, action, &agent_name, window, cx));
447
cx.subscribe_in(&dialog, window, |this, _, _: &StartDialogEvent, window, cx| {
448
this.agent_dialog = None;
449
window.focus(&this.focus_handle, cx);
450
cx.notify();
451
})
469
cx.subscribe_in(
470
&dialog,
471
window,
472
|this, _, _: &StartDialogEvent, window, cx| {
473
this.agent_dialog = None;
474
window.focus(&this.focus_handle, cx);
475
cx.notify();
476
},
477
)
452
478
.detach();
453
479
self.agent_dialog = Some(dialog);
454
480
cx.notify();
@@ -598,9 +624,12 @@ impl AppShell {
598
624
.flex_none()
599
625
.child(self.rail.clone())
600
626
.child(
601
self.sidebar
602
.clone()
603
.cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()),
627
self.sidebar.clone().cached(
628
StyleRefinement::default()
629
.w(px(SIDEBAR_WIDTH))
630
.h_full()
631
.flex_none(),
632
),
604
633
),
605
634
)
606
635
.child(match call_view {
@@ -648,7 +677,8 @@ impl Render for AppShell {
648
677
self.sync_call_chat(chat_thread, window, cx);
649
678
let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
650
679
let state = self.state.read(cx);
651
let call_view = render_call_view(&self.state, state, chat_panel).filter(|_| state.viewing_call());
680
let call_view =
681
render_call_view(&self.state, state, chat_panel).filter(|_| state.viewing_call());
652
682
let call_mini = render_call_mini(&self.state, state);
653
683
let stage_overlay = render_stage_overlay(&self.state, state);
654
684
let status = render_status_bar(
@@ -676,35 +706,42 @@ impl Render for AppShell {
676
706
this.state.update(cx, |state, cx| state.start_new_chat(cx));
677
707
}))
678
708
.on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {
679
this.state.update(cx, |state, cx| state.toggle_call_mute(cx));
709
this.state
710
.update(cx, |state, cx| state.toggle_call_mute(cx));
680
711
}))
681
712
.on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {
682
713
this.toggle_shortcuts_dialog(window, cx);
683
714
}))
684
715
.on_action(cx.listener(|this, _: &OpenActivity, window, cx| {
685
716
this.close_image_viewer(window, cx);
686
this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));
717
this.sidebar
718
.update(cx, |sidebar, cx| sidebar.show_activity(cx));
687
719
}))
688
720
.on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
689
721
this.close_image_viewer(window, cx);
690
this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));
722
this.sidebar
723
.update(cx, |sidebar, cx| sidebar.show_saved(cx));
691
724
}))
692
725
.on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {
693
726
this.close_image_viewer(window, cx);
694
this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
727
this.sidebar
728
.update(cx, |sidebar, cx| sidebar.show_chats(cx));
695
729
}))
696
730
.on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
697
731
this.close_image_viewer(window, cx);
698
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));
732
this.sidebar
733
.update(cx, |sidebar, cx| sidebar.show_channels(cx));
699
734
}))
700
735
.on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {
701
736
this.close_image_viewer(window, cx);
702
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));
737
this.sidebar
738
.update(cx, |sidebar, cx| sidebar.show_calls(cx));
703
739
}))
704
740
.on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {
705
741
this.close_image_viewer(window, cx);
706
this.sidebar
707
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));
742
this.sidebar.update(cx, |sidebar, cx| {
743
sidebar.select_adjacent(Step::Previous, cx)
744
});
708
745
}))
709
746
.on_action(cx.listener(|this, _: &NextConversation, window, cx| {
710
747
this.close_image_viewer(window, cx);
@@ -712,19 +749,23 @@ impl Render for AppShell {
712
749
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));
713
750
}))
714
751
.on_action(cx.listener(|this, _: &AcceptCall, _, cx| {
715
this.state.update(cx, |state, cx| state.accept_ringing_call(cx));
752
this.state
753
.update(cx, |state, cx| state.accept_ringing_call(cx));
716
754
}))
717
755
.on_action(cx.listener(|this, _: &DeclineCall, _, cx| {
718
this.state.update(cx, |state, cx| state.decline_ringing_call(cx));
756
this.state
757
.update(cx, |state, cx| state.decline_ringing_call(cx));
719
758
}))
720
759
.on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
721
760
this.state.update(cx, |state, cx| state.leave_call(cx));
722
761
}))
723
762
.on_action(cx.listener(|this, _: &ToggleCallCamera, _, cx| {
724
this.state.update(cx, |state, cx| state.toggle_call_camera(cx));
763
this.state
764
.update(cx, |state, cx| state.toggle_call_camera(cx));
725
765
}))
726
766
.on_action(cx.listener(|this, _: &ToggleCallShare, _, cx| {
727
this.state.update(cx, |state, cx| state.toggle_call_share(cx));
767
this.state
768
.update(cx, |state, cx| state.toggle_call_share(cx));
728
769
}))
729
770
.on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
730
771
this.close_image_viewer(window, cx);
@@ -15,9 +15,9 @@ use super::profile_card::{ProfileCard, ProfileCardEvent};15
use super::rail::RailView;15
use super::rail::RailView;16
use super::saved_panel::{SavedPanel, SavedPanelEvent};16
use super::saved_panel::{SavedPanel, SavedPanelEvent};17
use super::shortcuts::{17
use super::shortcuts::{18
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenChannelsTab,18
AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenCallsTab,19
OpenCallsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts, ToggleCallCamera,19
OpenChannelsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope, ShowShortcuts,20
ToggleCallShare,20
ToggleCallCamera, ToggleCallShare,21
};21
};22
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};22
use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};23
use super::sidebar::{SIDEBAR_WIDTH, SidebarView};23
use super::sidebar::{SIDEBAR_WIDTH, SidebarView};@@ -31,17 +31,24 @@ use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest}31
use crate::app_state::{AppEvent, AppState, Selection};31
use crate::app_state::{AppEvent, AppState, Selection};32
use crate::call::{CallMedia, CallWindows};32
use crate::call::{CallMedia, CallWindows};33
use crate::notice::NoticeAction;33
use crate::notice::NoticeAction;34
use crate::user_activity::{self, UserInput};35
use crate::notify::{NotificationCenter, selection_for};34
use crate::notify::{NotificationCenter, selection_for};36
use crate::sidebar_model::Step;35
use crate::sidebar_model::Step;37
use crate::theme;36
use crate::theme;38
use crate::updater::{self, IdleInputs, UpdateStatus};37
use crate::updater::{self, IdleInputs, UpdateStatus};38
use crate::user_activity::{self, UserInput};39
39
40
actions!(teams, [OpenSwitcher, NewChat, ToggleCallMute]);40
actions!(teams, [OpenSwitcher, NewChat, ToggleCallMute]);41
41
42
pub fn bind_keys(cx: &mut App) {42
pub fn bind_keys(cx: &mut App) {43
super::composer::bind_keys(cx);43
super::composer::bind_keys(cx);44
super::shortcuts::bind_scopes(cx, &[Scope::Global, Scope::OutsideComposer, Scope::GlobalOverTextFields]);44
super::shortcuts::bind_scopes(45
cx,46
&[47
Scope::Global,48
Scope::OutsideComposer,49
Scope::GlobalOverTextFields,50
],51
);45
}52
}46
53
47
#[derive(Debug, Clone, Copy)]54
#[derive(Debug, Clone, Copy)]@@ -91,7 +98,12 @@ pub struct AppShell {91
}98
}92
99
93
impl AppShell {100
impl AppShell {94
fn sync_call_chat(&mut self, thread: Option<String>, window: &mut Window, cx: &mut Context<Self>) {101
fn sync_call_chat(102
&mut self,103
thread: Option<String>,104
window: &mut Window,105
cx: &mut Context<Self>,106
) {95
match (thread, &self.call_chat) {107
match (thread, &self.call_chat) {96
(Some(wanted), Some((open, _))) if &wanted == open => {}108
(Some(wanted), Some((open, _))) if &wanted == open => {}97
(Some(wanted), _) => {109
(Some(wanted), _) => {@@ -118,15 +130,18 @@ impl AppShell {118
let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));130
let activity_panel = cx.new(|cx| ActivityPanel::new(state.clone(), activity.clone(), cx));119
let saved_panel = cx.new(|cx| SavedPanel::new(state.clone(), cx));131
let saved_panel = cx.new(|cx| SavedPanel::new(state.clone(), cx));120
let panel_subscriptions = [132
let panel_subscriptions = [121
cx.subscribe(&activity_panel, |this, _, event: &ActivityPanelEvent, cx| match event {133
cx.subscribe(122
ActivityPanelEvent::OpenSettings => this134
&activity_panel,123
.notifications135
|this, _, event: &ActivityPanelEvent, cx| match event {124
.update(cx, |center, cx| center.open_settings(cx)),136
ActivityPanelEvent::OpenSettings => this125
ActivityPanelEvent::Open {137
.notifications126
conversation_id,138
.update(cx, |center, cx| center.open_settings(cx)),127
message_id,139
ActivityPanelEvent::Open {128
} => this.open_message(conversation_id, message_id, cx),140
conversation_id,129
}),141
message_id,142
} => this.open_message(conversation_id, message_id, cx),143
},144
),130
cx.subscribe(&saved_panel, |this, _, event: &SavedPanelEvent, cx| {145
cx.subscribe(&saved_panel, |this, _, event: &SavedPanelEvent, cx| {131
let SavedPanelEvent::Open {146
let SavedPanelEvent::Open {132
conversation_id,147
conversation_id,@@ -136,8 +151,10 @@ impl AppShell {136
}),151
}),137
];152
];138
let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {153
let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {139
cx.subscribe_in(&runs, window, |this, _, event: &AgentRunsEvent, window, cx| {154
cx.subscribe_in(140
match event {155
&runs,156
window,157
|this, _, event: &AgentRunsEvent, window, cx| match event {141
AgentRunsEvent::StartRequested(request) => {158
AgentRunsEvent::StartRequested(request) => {142
this.open_agent_dialog(request.clone(), window, cx)159
this.open_agent_dialog(request.clone(), window, cx)143
}160
}@@ -145,8 +162,8 @@ impl AppShell {145
.notifications162
.notifications146
.update(cx, |center, cx| center.open_agent_settings(cx)),163
.update(cx, |center, cx| center.open_agent_settings(cx)),147
AgentRunsEvent::Finished(_) => {}164
AgentRunsEvent::Finished(_) => {}148
}165
},149
})166
)150
});167
});151
let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, cx));168
let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, cx));152
let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));169
let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));@@ -182,12 +199,14 @@ impl AppShell {182
let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {199
let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {183
this.user_input.touch();200
this.user_input.touch();184
if event.keystroke.key == "escape" {201
if event.keystroke.key == "escape" {185
this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));202
this.state203
.update(cx, |state, cx| state.leave_stage_fullscreen(cx));186
}204
}187
});205
});188
let activation_observation = cx.observe_window_activation(window, |this, window, cx| {206
let activation_observation = cx.observe_window_activation(window, |this, window, cx| {189
if window.is_window_active() {207
if window.is_window_active() {190
this.state.update(cx, |state, cx| state.refresh_calendar(cx));208
this.state209
.update(cx, |state, cx| state.refresh_calendar(cx));191
}210
}192
});211
});193
let closing = notifications.clone();212
let closing = notifications.clone();@@ -257,7 +276,10 @@ impl AppShell {257
276
258
#[cfg_attr(not(windows), allow(dead_code))]277
#[cfg_attr(not(windows), allow(dead_code))]259
fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {278
fn poll_update(&mut self, window: &mut Window, cx: &mut Context<Self>) {260
if matches!(self.update, UpdateStatus::Failed(_) | UpdateStatus::Installing) {279
if matches!(280
self.update,281
UpdateStatus::Failed(_) | UpdateStatus::Installing282
) {261
return;283
return;262
}284
}263
let Some(paths) = updater::current_paths() else {285
let Some(paths) = updater::current_paths() else {@@ -444,11 +466,15 @@ impl AppShell {444
self.switcher = None;466
self.switcher = None;445
let app = self.state.clone();467
let app = self.state.clone();446
let dialog = cx.new(|cx| StartDialog::new(app, request, action, &agent_name, window, cx));468
let dialog = cx.new(|cx| StartDialog::new(app, request, action, &agent_name, window, cx));447
cx.subscribe_in(&dialog, window, |this, _, _: &StartDialogEvent, window, cx| {469
cx.subscribe_in(448
this.agent_dialog = None;470
&dialog,449
window.focus(&this.focus_handle, cx);471
window,450
cx.notify();472
|this, _, _: &StartDialogEvent, window, cx| {451
})473
this.agent_dialog = None;474
window.focus(&this.focus_handle, cx);475
cx.notify();476
},477
)452
.detach();478
.detach();453
self.agent_dialog = Some(dialog);479
self.agent_dialog = Some(dialog);454
cx.notify();480
cx.notify();@@ -598,9 +624,12 @@ impl AppShell {598
.flex_none()624
.flex_none()599
.child(self.rail.clone())625
.child(self.rail.clone())600
.child(626
.child(601
self.sidebar627
self.sidebar.clone().cached(602
.clone()628
StyleRefinement::default()603
.cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()),629
.w(px(SIDEBAR_WIDTH))630
.h_full()631
.flex_none(),632
),604
),633
),605
)634
)606
.child(match call_view {635
.child(match call_view {@@ -648,7 +677,8 @@ impl Render for AppShell {648
self.sync_call_chat(chat_thread, window, cx);677
self.sync_call_chat(chat_thread, window, cx);649
let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());678
let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());650
let state = self.state.read(cx);679
let state = self.state.read(cx);651
let call_view = render_call_view(&self.state, state, chat_panel).filter(|_| state.viewing_call());680
let call_view =681
render_call_view(&self.state, state, chat_panel).filter(|_| state.viewing_call());652
let call_mini = render_call_mini(&self.state, state);682
let call_mini = render_call_mini(&self.state, state);653
let stage_overlay = render_stage_overlay(&self.state, state);683
let stage_overlay = render_stage_overlay(&self.state, state);654
let status = render_status_bar(684
let status = render_status_bar(@@ -676,35 +706,42 @@ impl Render for AppShell {676
this.state.update(cx, |state, cx| state.start_new_chat(cx));706
this.state.update(cx, |state, cx| state.start_new_chat(cx));677
}))707
}))678
.on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {708
.on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {679
this.state.update(cx, |state, cx| state.toggle_call_mute(cx));709
this.state710
.update(cx, |state, cx| state.toggle_call_mute(cx));680
}))711
}))681
.on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {712
.on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {682
this.toggle_shortcuts_dialog(window, cx);713
this.toggle_shortcuts_dialog(window, cx);683
}))714
}))684
.on_action(cx.listener(|this, _: &OpenActivity, window, cx| {715
.on_action(cx.listener(|this, _: &OpenActivity, window, cx| {685
this.close_image_viewer(window, cx);716
this.close_image_viewer(window, cx);686
this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));717
this.sidebar718
.update(cx, |sidebar, cx| sidebar.show_activity(cx));687
}))719
}))688
.on_action(cx.listener(|this, _: &OpenSaved, window, cx| {720
.on_action(cx.listener(|this, _: &OpenSaved, window, cx| {689
this.close_image_viewer(window, cx);721
this.close_image_viewer(window, cx);690
this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));722
this.sidebar723
.update(cx, |sidebar, cx| sidebar.show_saved(cx));691
}))724
}))692
.on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {725
.on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {693
this.close_image_viewer(window, cx);726
this.close_image_viewer(window, cx);694
this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));727
this.sidebar728
.update(cx, |sidebar, cx| sidebar.show_chats(cx));695
}))729
}))696
.on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {730
.on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {697
this.close_image_viewer(window, cx);731
this.close_image_viewer(window, cx);698
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));732
this.sidebar733
.update(cx, |sidebar, cx| sidebar.show_channels(cx));699
}))734
}))700
.on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {735
.on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {701
this.close_image_viewer(window, cx);736
this.close_image_viewer(window, cx);702
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));737
this.sidebar738
.update(cx, |sidebar, cx| sidebar.show_calls(cx));703
}))739
}))704
.on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {740
.on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {705
this.close_image_viewer(window, cx);741
this.close_image_viewer(window, cx);706
this.sidebar742
this.sidebar.update(cx, |sidebar, cx| {707
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));743
sidebar.select_adjacent(Step::Previous, cx)744
});708
}))745
}))709
.on_action(cx.listener(|this, _: &NextConversation, window, cx| {746
.on_action(cx.listener(|this, _: &NextConversation, window, cx| {710
this.close_image_viewer(window, cx);747
this.close_image_viewer(window, cx);@@ -712,19 +749,23 @@ impl Render for AppShell {712
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));749
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));713
}))750
}))714
.on_action(cx.listener(|this, _: &AcceptCall, _, cx| {751
.on_action(cx.listener(|this, _: &AcceptCall, _, cx| {715
this.state.update(cx, |state, cx| state.accept_ringing_call(cx));752
this.state753
.update(cx, |state, cx| state.accept_ringing_call(cx));716
}))754
}))717
.on_action(cx.listener(|this, _: &DeclineCall, _, cx| {755
.on_action(cx.listener(|this, _: &DeclineCall, _, cx| {718
this.state.update(cx, |state, cx| state.decline_ringing_call(cx));756
this.state757
.update(cx, |state, cx| state.decline_ringing_call(cx));719
}))758
}))720
.on_action(cx.listener(|this, _: &HangUpCall, _, cx| {759
.on_action(cx.listener(|this, _: &HangUpCall, _, cx| {721
this.state.update(cx, |state, cx| state.leave_call(cx));760
this.state.update(cx, |state, cx| state.leave_call(cx));722
}))761
}))723
.on_action(cx.listener(|this, _: &ToggleCallCamera, _, cx| {762
.on_action(cx.listener(|this, _: &ToggleCallCamera, _, cx| {724
this.state.update(cx, |state, cx| state.toggle_call_camera(cx));763
this.state764
.update(cx, |state, cx| state.toggle_call_camera(cx));725
}))765
}))726
.on_action(cx.listener(|this, _: &ToggleCallShare, _, cx| {766
.on_action(cx.listener(|this, _: &ToggleCallShare, _, cx| {727
this.state.update(cx, |state, cx| state.toggle_call_share(cx));767
this.state768
.update(cx, |state, cx| state.toggle_call_share(cx));728
}))769
}))729
.on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {770
.on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {730
this.close_image_viewer(window, cx);771
this.close_image_viewer(window, cx);@@ -14,8 +14,8 @@ use store::{
14
14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,
15
15
};
16
16
17
use super::avatar::{spec_avatar, square_avatar, with_presence};
18
17
use super::activity_panel::ActivityPanel;
18
use super::avatar::{spec_avatar, square_avatar, with_presence};
19
19
use super::calls_tab::calls_body;
20
20
use super::saved_panel::SavedPanel;
21
21
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
@@ -28,8 +28,8 @@ use crate::local_previews::LocalPreview;
28
28
use crate::notice::truncated;
29
29
use crate::sidebar_model::{
30
30
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,
31
SectionInput, SectionKind, Step, build_sections, step_id,
32
older_chats_trigger_resets, visible_channel_ids, wants_older_chats,
31
SectionInput, SectionKind, Step, build_sections, older_chats_trigger_resets, step_id,
32
visible_channel_ids, wants_older_chats,
33
33
};
34
34
use crate::theme;
35
35
@@ -649,7 +649,8 @@ impl SidebarView {
649
649
SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved => None,
650
650
};
651
651
if let Some(selection) = selection {
652
self.state.update(cx, |state, cx| state.select(selection, cx));
652
self.state
653
.update(cx, |state, cx| state.select(selection, cx));
653
654
}
654
655
}
655
656
@@ -14,8 +14,8 @@ use store::{14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,14
ChannelNotificationLevel, ChannelNotifications, ChannelRecord, SidebarTeam, Store, TeamRecord,15
};15
};16
16
17
use super::avatar::{spec_avatar, square_avatar, with_presence};18
use super::activity_panel::ActivityPanel;17
use super::activity_panel::ActivityPanel;18
use super::avatar::{spec_avatar, square_avatar, with_presence};19
use super::calls_tab::calls_body;19
use super::calls_tab::calls_body;20
use super::saved_panel::SavedPanel;20
use super::saved_panel::SavedPanel;21
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};21
use super::section_dialog::{SectionNameTarget, open_section_name_dialog};@@ -28,8 +28,8 @@ use crate::local_previews::LocalPreview;28
use crate::notice::truncated;28
use crate::notice::truncated;29
use crate::sidebar_model::{29
use crate::sidebar_model::{30
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,30
AvatarSpec, ChannelOrderInput, ChatItem, DELETED_PREVIEW, EMPTY_FOLDER_HINT, Preview, Section,31
SectionInput, SectionKind, Step, build_sections, step_id,31
SectionInput, SectionKind, Step, build_sections, older_chats_trigger_resets, step_id,32
older_chats_trigger_resets, visible_channel_ids, wants_older_chats,32
visible_channel_ids, wants_older_chats,33
};33
};34
use crate::theme;34
use crate::theme;35
35
@@ -649,7 +649,8 @@ impl SidebarView {649
SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved => None,649
SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Saved => None,650
};650
};651
if let Some(selection) = selection {651
if let Some(selection) = selection {652
self.state.update(cx, |state, cx| state.select(selection, cx));652
self.state653
.update(cx, |state, cx| state.select(selection, cx));653
}654
}654
}655
}655
656
@@ -109,7 +109,11 @@ pub fn render_status_bar(
109
109
)
110
110
}
111
111
UpdateStatus::Installing => {
112
bar = bar.child(div().text_color(theme::accent_text()).child("Restarting..."))
112
bar = bar.child(
113
div()
114
.text_color(theme::accent_text())
115
.child("Restarting..."),
116
)
113
117
}
114
118
UpdateStatus::Failed(message) => {
115
119
bar = bar.child(
@@ -109,7 +109,11 @@ pub fn render_status_bar(109
)109
)110
}110
}111
UpdateStatus::Installing => {111
UpdateStatus::Installing => {112
bar = bar.child(div().text_color(theme::accent_text()).child("Restarting..."))112
bar = bar.child(113
div()114
.text_color(theme::accent_text())115
.child("Restarting..."),116
)113
}117
}114
UpdateStatus::Failed(message) => {118
UpdateStatus::Failed(message) => {115
bar = bar.child(119
bar = bar.child(@@ -28,7 +28,10 @@ const FIELD_HEIGHT: f32 = 36.;
28
28
const CLOSE_SIZE: f32 = 28.;
29
29
const DISABLED_OPACITY: f32 = 0.4;
30
30
31
pub fn visible_candidates(candidates: &[(String, TransferCandidate)], query: &str) -> Vec<TransferCandidate> {
31
pub fn visible_candidates(
32
candidates: &[(String, TransferCandidate)],
33
query: &str,
34
) -> Vec<TransferCandidate> {
32
35
fuzzy::rank(query, candidates, MAX_RESULTS)
33
36
}
34
37
@@ -43,20 +46,42 @@ pub struct TransferPicker {
43
46
}
44
47
45
48
impl TransferPicker {
46
pub fn new(app: Entity<AppState>, candidates: Vec<TransferCandidate>, window: &mut Window, cx: &mut Context<Self>) -> Self {
47
let candidates: Vec<(String, TransferCandidate)> = candidates.into_iter().map(|candidate| (candidate.name.clone(), candidate)).collect();
49
pub fn new(
50
app: Entity<AppState>,
51
candidates: Vec<TransferCandidate>,
52
window: &mut Window,
53
cx: &mut Context<Self>,
54
) -> Self {
55
let candidates: Vec<(String, TransferCandidate)> = candidates
56
.into_iter()
57
.map(|candidate| (candidate.name.clone(), candidate))
58
.collect();
48
59
let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search people"));
49
60
let subscription = cx.subscribe_in(&search, window, Self::on_search_event);
50
61
search.update(cx, |input, cx| input.focus(window, cx));
51
62
let results = visible_candidates(&candidates, "");
52
TransferPicker { app, candidates, search, results, highlighted: 0, target: None, _subscription: subscription }
63
TransferPicker {
64
app,
65
candidates,
66
search,
67
results,
68
highlighted: 0,
69
target: None,
70
_subscription: subscription,
71
}
53
72
}
54
73
55
74
pub fn choose(&mut self, candidate: TransferCandidate) {
56
75
self.target = Some(candidate);
57
76
}
58
77
59
fn on_search_event(&mut self, input: &Entity<InputState>, event: &InputEvent, _: &mut Window, cx: &mut Context<Self>) {
78
fn on_search_event(
79
&mut self,
80
input: &Entity<InputState>,
81
event: &InputEvent,
82
_: &mut Window,
83
cx: &mut Context<Self>,
84
) {
60
85
match event {
61
86
InputEvent::Change => {
62
87
let query = input.read(cx).value().to_string();
@@ -90,7 +115,8 @@ impl TransferPicker {
90
115
}
91
116
92
117
fn close(&self, cx: &mut Context<Self>) {
93
self.app.update(cx, |state, cx| state.close_transfer_picker(cx));
118
self.app
119
.update(cx, |state, cx| state.close_transfer_picker(cx));
94
120
}
95
121
96
122
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {
@@ -111,11 +137,28 @@ impl TransferPicker {
111
137
.items_center()
112
138
.rounded(px(6.))
113
139
.cursor_pointer()
114
.when(chosen || (self.target.is_none() && index == self.highlighted), |row| row.bg(theme::surface_raised()))
140
.when(
141
chosen || (self.target.is_none() && index == self.highlighted),
142
|row| row.bg(theme::surface_raised()),
143
)
115
144
.hover(|row| row.bg(theme::row_hover()))
116
.child(person_avatar(directory, candidate.user_id.as_deref(), &candidate.name, AVATAR_SIZE))
117
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(candidate.name.clone()))
118
.when(chosen, |row| row.child(icon(IconName::Check, 16., theme::accent_text())))
145
.child(person_avatar(
146
directory,
147
candidate.user_id.as_deref(),
148
&candidate.name,
149
AVATAR_SIZE,
150
))
151
.child(
152
div()
153
.flex_1()
154
.min_w_0()
155
.truncate()
156
.text_size(px(14.))
157
.child(candidate.name.clone()),
158
)
159
.when(chosen, |row| {
160
row.child(icon(IconName::Check, 16., theme::accent_text()))
161
})
119
162
.on_click(cx.listener(move |this, _, _, cx| {
120
163
this.choose(picked.clone());
121
164
cx.notify();
@@ -123,17 +166,30 @@ impl TransferPicker {
123
166
.into_any_element()
124
167
})
125
168
.collect();
126
v_flex().id("transfer-targets").w_full().max_h(px(ROW_HEIGHT * MAX_RESULTS as f32)).overflow_y_scroll().children(rows)
169
v_flex()
170
.id("transfer-targets")
171
.w_full()
172
.max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))
173
.overflow_y_scroll()
174
.children(rows)
127
175
}
128
176
129
fn action(&self, id: &'static str, label: &'static str, primary: bool, run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>)) -> AnyElement {
177
fn action(
178
&self,
179
id: &'static str,
180
label: &'static str,
181
primary: bool,
182
run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>),
183
) -> AnyElement {
130
184
let button = Button::new(id).label(label);
131
185
let button = if primary { button } else { button.ghost() };
132
186
let Some(target) = self.target.clone() else {
133
187
return button.opacity(DISABLED_OPACITY).into_any_element();
134
188
};
135
189
let app = self.app.clone();
136
button.on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx))).into_any_element()
190
button
191
.on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx)))
192
.into_any_element()
137
193
}
138
194
}
139
195
@@ -150,14 +206,33 @@ impl Render for TransferPicker {
150
206
.border_1()
151
207
.border_color(theme::border())
152
208
.child(icon(IconName::Search, 14., theme::text_muted()))
153
.child(div().flex_1().child(Input::new(&self.search).appearance(false).bordered(false)));
209
.child(
210
div()
211
.flex_1()
212
.child(Input::new(&self.search).appearance(false).bordered(false)),
213
);
154
214
let actions = h_flex()
155
215
.w_full()
156
216
.justify_end()
157
217
.gap(px(8.))
158
.child(Button::new("transfer-cancel").ghost().label("Cancel").on_click(cx.listener(|this, _, _, cx| this.close(cx))))
159
.child(self.action("transfer-consult", "Consult first", false, AppState::start_consult))
160
.child(self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind));
218
.child(
219
Button::new("transfer-cancel")
220
.ghost()
221
.label("Cancel")
222
.on_click(cx.listener(|this, _, _, cx| this.close(cx))),
223
)
224
.child(self.action(
225
"transfer-consult",
226
"Consult first",
227
false,
228
AppState::start_consult,
229
))
230
.child(self.action(
231
"transfer-now",
232
"Transfer now",
233
true,
234
AppState::transfer_call_blind,
235
));
161
236
div()
162
237
.id("transfer-layer")
163
238
.absolute()
@@ -198,7 +273,13 @@ impl Render for TransferPicker {
198
273
.w_full()
199
274
.items_center()
200
275
.gap(px(SECTION_GAP))
201
.child(div().flex_1().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Transfer call"))
276
.child(
277
div()
278
.flex_1()
279
.text_size(px(15.))
280
.font_weight(FontWeight::SEMIBOLD)
281
.child("Transfer call"),
282
)
202
283
.child(
203
284
div()
204
285
.id("transfer-close")
@@ -227,13 +308,28 @@ mod tests {
227
308
use crate::call::TransferCandidate;
228
309
229
310
fn candidate(name: &str) -> (String, TransferCandidate) {
230
(name.to_owned(), TransferCandidate { mri: format!("8:orgid:{name}"), name: name.to_owned(), user_id: Some(name.to_owned()), chat_id: format!("19:{name}") })
311
(
312
name.to_owned(),
313
TransferCandidate {
314
mri: format!("8:orgid:{name}"),
315
name: name.to_owned(),
316
user_id: Some(name.to_owned()),
317
chat_id: format!("19:{name}"),
318
},
319
)
231
320
}
232
321
233
322
#[test]
234
323
fn the_search_ranks_people_by_name() {
235
let people = vec![candidate("Ana Weiss"), candidate("Bo Brandt"), candidate("Anja Vogel")];
236
let found: Vec<String> = visible_candidates(&people, "anj").into_iter().map(|person| person.name).collect();
324
let people = vec![
325
candidate("Ana Weiss"),
326
candidate("Bo Brandt"),
327
candidate("Anja Vogel"),
328
];
329
let found: Vec<String> = visible_candidates(&people, "anj")
330
.into_iter()
331
.map(|person| person.name)
332
.collect();
237
333
assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));
238
334
assert_eq!(visible_candidates(&people, "").len(), 3);
239
335
assert!(visible_candidates(&people, "zzz").is_empty());
@@ -241,7 +337,9 @@ mod tests {
241
337
242
338
#[test]
243
339
fn the_list_is_capped() {
244
let people: Vec<(String, TransferCandidate)> = (0..20).map(|index| candidate(&format!("Person {index}"))).collect();
340
let people: Vec<(String, TransferCandidate)> = (0..20)
341
.map(|index| candidate(&format!("Person {index}")))
342
.collect();
245
343
assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);
246
344
}
247
345
}
@@ -28,7 +28,10 @@ const FIELD_HEIGHT: f32 = 36.;28
const CLOSE_SIZE: f32 = 28.;28
const CLOSE_SIZE: f32 = 28.;29
const DISABLED_OPACITY: f32 = 0.4;29
const DISABLED_OPACITY: f32 = 0.4;30
30
31
pub fn visible_candidates(candidates: &[(String, TransferCandidate)], query: &str) -> Vec<TransferCandidate> {31
pub fn visible_candidates(32
candidates: &[(String, TransferCandidate)],33
query: &str,34
) -> Vec<TransferCandidate> {32
fuzzy::rank(query, candidates, MAX_RESULTS)35
fuzzy::rank(query, candidates, MAX_RESULTS)33
}36
}34
37
@@ -43,20 +46,42 @@ pub struct TransferPicker {43
}46
}44
47
45
impl TransferPicker {48
impl TransferPicker {46
pub fn new(app: Entity<AppState>, candidates: Vec<TransferCandidate>, window: &mut Window, cx: &mut Context<Self>) -> Self {49
pub fn new(47
let candidates: Vec<(String, TransferCandidate)> = candidates.into_iter().map(|candidate| (candidate.name.clone(), candidate)).collect();50
app: Entity<AppState>,51
candidates: Vec<TransferCandidate>,52
window: &mut Window,53
cx: &mut Context<Self>,54
) -> Self {55
let candidates: Vec<(String, TransferCandidate)> = candidates56
.into_iter()57
.map(|candidate| (candidate.name.clone(), candidate))58
.collect();48
let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search people"));59
let search = cx.new(|cx| InputState::new(window, cx).placeholder("Search people"));49
let subscription = cx.subscribe_in(&search, window, Self::on_search_event);60
let subscription = cx.subscribe_in(&search, window, Self::on_search_event);50
search.update(cx, |input, cx| input.focus(window, cx));61
search.update(cx, |input, cx| input.focus(window, cx));51
let results = visible_candidates(&candidates, "");62
let results = visible_candidates(&candidates, "");52
TransferPicker { app, candidates, search, results, highlighted: 0, target: None, _subscription: subscription }63
TransferPicker {64
app,65
candidates,66
search,67
results,68
highlighted: 0,69
target: None,70
_subscription: subscription,71
}53
}72
}54
73
55
pub fn choose(&mut self, candidate: TransferCandidate) {74
pub fn choose(&mut self, candidate: TransferCandidate) {56
self.target = Some(candidate);75
self.target = Some(candidate);57
}76
}58
77
59
fn on_search_event(&mut self, input: &Entity<InputState>, event: &InputEvent, _: &mut Window, cx: &mut Context<Self>) {78
fn on_search_event(79
&mut self,80
input: &Entity<InputState>,81
event: &InputEvent,82
_: &mut Window,83
cx: &mut Context<Self>,84
) {60
match event {85
match event {61
InputEvent::Change => {86
InputEvent::Change => {62
let query = input.read(cx).value().to_string();87
let query = input.read(cx).value().to_string();@@ -90,7 +115,8 @@ impl TransferPicker {90
}115
}91
116
92
fn close(&self, cx: &mut Context<Self>) {117
fn close(&self, cx: &mut Context<Self>) {93
self.app.update(cx, |state, cx| state.close_transfer_picker(cx));118
self.app119
.update(cx, |state, cx| state.close_transfer_picker(cx));94
}120
}95
121
96
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {122
fn list(&self, cx: &mut Context<Self>) -> Stateful<Div> {@@ -111,11 +137,28 @@ impl TransferPicker {111
.items_center()137
.items_center()112
.rounded(px(6.))138
.rounded(px(6.))113
.cursor_pointer()139
.cursor_pointer()114
.when(chosen || (self.target.is_none() && index == self.highlighted), |row| row.bg(theme::surface_raised()))140
.when(141
chosen || (self.target.is_none() && index == self.highlighted),142
|row| row.bg(theme::surface_raised()),143
)115
.hover(|row| row.bg(theme::row_hover()))144
.hover(|row| row.bg(theme::row_hover()))116
.child(person_avatar(directory, candidate.user_id.as_deref(), &candidate.name, AVATAR_SIZE))145
.child(person_avatar(117
.child(div().flex_1().min_w_0().truncate().text_size(px(14.)).child(candidate.name.clone()))146
directory,118
.when(chosen, |row| row.child(icon(IconName::Check, 16., theme::accent_text())))147
candidate.user_id.as_deref(),148
&candidate.name,149
AVATAR_SIZE,150
))151
.child(152
div()153
.flex_1()154
.min_w_0()155
.truncate()156
.text_size(px(14.))157
.child(candidate.name.clone()),158
)159
.when(chosen, |row| {160
row.child(icon(IconName::Check, 16., theme::accent_text()))161
})119
.on_click(cx.listener(move |this, _, _, cx| {162
.on_click(cx.listener(move |this, _, _, cx| {120
this.choose(picked.clone());163
this.choose(picked.clone());121
cx.notify();164
cx.notify();@@ -123,17 +166,30 @@ impl TransferPicker {123
.into_any_element()166
.into_any_element()124
})167
})125
.collect();168
.collect();126
v_flex().id("transfer-targets").w_full().max_h(px(ROW_HEIGHT * MAX_RESULTS as f32)).overflow_y_scroll().children(rows)169
v_flex()170
.id("transfer-targets")171
.w_full()172
.max_h(px(ROW_HEIGHT * MAX_RESULTS as f32))173
.overflow_y_scroll()174
.children(rows)127
}175
}128
176
129
fn action(&self, id: &'static str, label: &'static str, primary: bool, run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>)) -> AnyElement {177
fn action(178
&self,179
id: &'static str,180
label: &'static str,181
primary: bool,182
run: fn(&mut AppState, TransferCandidate, &mut Context<AppState>),183
) -> AnyElement {130
let button = Button::new(id).label(label);184
let button = Button::new(id).label(label);131
let button = if primary { button } else { button.ghost() };185
let button = if primary { button } else { button.ghost() };132
let Some(target) = self.target.clone() else {186
let Some(target) = self.target.clone() else {133
return button.opacity(DISABLED_OPACITY).into_any_element();187
return button.opacity(DISABLED_OPACITY).into_any_element();134
};188
};135
let app = self.app.clone();189
let app = self.app.clone();136
button.on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx))).into_any_element()190
button191
.on_click(move |_, _, cx| app.update(cx, |state, cx| run(state, target.clone(), cx)))192
.into_any_element()137
}193
}138
}194
}139
195
@@ -150,14 +206,33 @@ impl Render for TransferPicker {150
.border_1()206
.border_1()151
.border_color(theme::border())207
.border_color(theme::border())152
.child(icon(IconName::Search, 14., theme::text_muted()))208
.child(icon(IconName::Search, 14., theme::text_muted()))153
.child(div().flex_1().child(Input::new(&self.search).appearance(false).bordered(false)));209
.child(210
div()211
.flex_1()212
.child(Input::new(&self.search).appearance(false).bordered(false)),213
);154
let actions = h_flex()214
let actions = h_flex()155
.w_full()215
.w_full()156
.justify_end()216
.justify_end()157
.gap(px(8.))217
.gap(px(8.))158
.child(Button::new("transfer-cancel").ghost().label("Cancel").on_click(cx.listener(|this, _, _, cx| this.close(cx))))218
.child(159
.child(self.action("transfer-consult", "Consult first", false, AppState::start_consult))219
Button::new("transfer-cancel")160
.child(self.action("transfer-now", "Transfer now", true, AppState::transfer_call_blind));220
.ghost()221
.label("Cancel")222
.on_click(cx.listener(|this, _, _, cx| this.close(cx))),223
)224
.child(self.action(225
"transfer-consult",226
"Consult first",227
false,228
AppState::start_consult,229
))230
.child(self.action(231
"transfer-now",232
"Transfer now",233
true,234
AppState::transfer_call_blind,235
));161
div()236
div()162
.id("transfer-layer")237
.id("transfer-layer")163
.absolute()238
.absolute()@@ -198,7 +273,13 @@ impl Render for TransferPicker {198
.w_full()273
.w_full()199
.items_center()274
.items_center()200
.gap(px(SECTION_GAP))275
.gap(px(SECTION_GAP))201
.child(div().flex_1().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Transfer call"))276
.child(277
div()278
.flex_1()279
.text_size(px(15.))280
.font_weight(FontWeight::SEMIBOLD)281
.child("Transfer call"),282
)202
.child(283
.child(203
div()284
div()204
.id("transfer-close")285
.id("transfer-close")@@ -227,13 +308,28 @@ mod tests {227
use crate::call::TransferCandidate;308
use crate::call::TransferCandidate;228
309
229
fn candidate(name: &str) -> (String, TransferCandidate) {310
fn candidate(name: &str) -> (String, TransferCandidate) {230
(name.to_owned(), TransferCandidate { mri: format!("8:orgid:{name}"), name: name.to_owned(), user_id: Some(name.to_owned()), chat_id: format!("19:{name}") })311
(312
name.to_owned(),313
TransferCandidate {314
mri: format!("8:orgid:{name}"),315
name: name.to_owned(),316
user_id: Some(name.to_owned()),317
chat_id: format!("19:{name}"),318
},319
)231
}320
}232
321
233
#[test]322
#[test]234
fn the_search_ranks_people_by_name() {323
fn the_search_ranks_people_by_name() {235
let people = vec![candidate("Ana Weiss"), candidate("Bo Brandt"), candidate("Anja Vogel")];324
let people = vec![236
let found: Vec<String> = visible_candidates(&people, "anj").into_iter().map(|person| person.name).collect();325
candidate("Ana Weiss"),326
candidate("Bo Brandt"),327
candidate("Anja Vogel"),328
];329
let found: Vec<String> = visible_candidates(&people, "anj")330
.into_iter()331
.map(|person| person.name)332
.collect();237
assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));333
assert_eq!(found.first().map(String::as_str), Some("Anja Vogel"));238
assert_eq!(visible_candidates(&people, "").len(), 3);334
assert_eq!(visible_candidates(&people, "").len(), 3);239
assert!(visible_candidates(&people, "zzz").is_empty());335
assert!(visible_candidates(&people, "zzz").is_empty());@@ -241,7 +337,9 @@ mod tests {241
337
242
#[test]338
#[test]243
fn the_list_is_capped() {339
fn the_list_is_capped() {244
let people: Vec<(String, TransferCandidate)> = (0..20).map(|index| candidate(&format!("Person {index}"))).collect();340
let people: Vec<(String, TransferCandidate)> = (0..20)341
.map(|index| candidate(&format!("Person {index}")))342
.collect();245
assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);343
assert_eq!(visible_candidates(&people, "").len(), MAX_RESULTS);246
}344
}247
}345
}