Merge branch 'main' into feat/mcp-server
# Conflicts: # crates/app/src/main.rs # crates/app/src/views/conversation/feed.rs
@@ -49,8 +49,10 @@ windows = { version = "0.62", features = [
49
49
"Win32_Storage_FileSystem",
50
50
"Win32_System_Com",
51
51
"Win32_System_Pipes",
52
"Win32_System_SystemInformation",
52
53
"Win32_System_Threading",
53
54
"Win32_UI_HiDpi",
55
"Win32_UI_Input_KeyboardAndMouse",
54
56
"Win32_UI_Shell",
55
57
"Win32_UI_WindowsAndMessaging",
56
58
] }
@@ -49,8 +49,10 @@ windows = { version = "0.62", features = [49
"Win32_Storage_FileSystem",49
"Win32_Storage_FileSystem",50
"Win32_System_Com",50
"Win32_System_Com",51
"Win32_System_Pipes",51
"Win32_System_Pipes",52
"Win32_System_SystemInformation",52
"Win32_System_Threading",53
"Win32_System_Threading",53
"Win32_UI_HiDpi",54
"Win32_UI_HiDpi",55
"Win32_UI_Input_KeyboardAndMouse",54
"Win32_UI_Shell",56
"Win32_UI_Shell",55
"Win32_UI_WindowsAndMessaging",57
"Win32_UI_WindowsAndMessaging",56
] }58
] }@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M560-240 320-480l240-240 56 56-184 184 184 184-56 56Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M560-240 320-480l240-240 56 56-184 184 184 184-56 56Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M504-480 320-664l56-56 240 240-240 240-56-56 184-184Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M504-480 320-664l56-56 240 240-240 240-56-56 184-184Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="m640-280-57-56 184-184-184-184 57-56 240 240-240 240ZM80-200v-160q0-83 58.5-141.5T280-560h247L383-704l57-56 240 240-240 240-57-56 144-144H280q-50 0-85 35t-35 85v160H80Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="m640-280-57-56 184-184-184-184 57-56 240 240-240 240ZM80-200v-160q0-83 58.5-141.5T280-560h247L383-704l57-56 240 240-240 240-57-56 144-144H280q-50 0-85 35t-35 85v160H80Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M120-120v-200h80v120h120v80H120Zm520 0v-80h120v-120h80v200H640ZM120-640v-200h200v80H200v120h-80Zm640 0v-120H640v-80h200v200h-80Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M200-120q-33 0-56.5-23.5T120-200v-560q0-33 23.5-56.5T200-840h280v80H200v560h560v-280h80v280q0 33-23.5 56.5T760-120H200Zm188-212-56-56 372-372H560v-80h280v280h-80v-144L388-332Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M522-80v-82q34-5 66.5-18t61.5-34l56 58q-42 32-88 51.5T522-80Zm-80 0Q304-98 213-199.5T122-438q0-75 28.5-140.5t77-114q48.5-48.5 114-77T482-798h6l-62-62 56-58 160 160-160 160-56-56 64-64h-8q-117 0-198.5 81.5T202-438q0 104 68 182.5T442-162v82Zm322-134-58-56q21-29 34-61.5t18-66.5h82q-5 50-24.5 96T764-214Zm76-264h-82q-5-34-18-66.5T706-606l58-56q32 39 51 86t25 98Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M522-80v-82q34-5 66.5-18t61.5-34l56 58q-42 32-88 51.5T522-80Zm-80 0Q304-98 213-199.5T122-438q0-75 28.5-140.5t77-114q48.5-48.5 114-77T482-798h6l-62-62 56-58 160 160-160 160-56-56 64-64h-8q-117 0-198.5 81.5T202-438q0 104 68 182.5T442-162v82Zm322-134-58-56q21-29 34-61.5t18-66.5h82q-5 50-24.5 96T764-214Zm76-264h-82q-5-34-18-66.5T706-606l58-56q32 39 51 86t25 98Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Zm-40-60v-80h-80v-80h80v-80h80v80h80v80h-80v80h-80Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400Zm-40-60v-80h-80v-80h80v-80h80v80h80v80h-80v80h-80Z"/></svg>@@ -0,0 +1 @@
1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400ZM280-540v-80h200v80H280Z"/></svg>
@@ -0,0 +1 @@1
<svg xmlns="http://www.w3.org/2000/svg" height="24" viewBox="0 -960 960 960" width="24"><path d="M784-120 532-372q-30 24-69 38t-83 14q-109 0-184.5-75.5T120-580q0-109 75.5-184.5T380-840q109 0 184.5 75.5T640-580q0 44-14 83t-38 69l252 252-56 56ZM380-400q75 0 127.5-52.5T560-580q0-75-52.5-127.5T380-760q-75 0-127.5 52.5T200-580q0 75 52.5 127.5T380-400ZM280-540v-80h200v80H280Z"/></svg>@@ -16,6 +16,7 @@ use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};
16
16
use calling::meeting::LiveMeeting;
17
17
use crate::card_state::{CardState, TaskDialogState};
18
18
use crate::data::{self, Directory};
19
use crate::image_view_gallery::ViewerRequest;
19
20
use crate::local_previews::{LocalPreview, load_local_previews};
20
21
use crate::message_actions::{ForwardSource, SavedSet};
21
22
use crate::notice::Notice;
@@ -59,6 +60,7 @@ pub enum AppEvent {
59
60
CallHistory,
60
61
Translation,
61
62
Forward,
63
ImageViewer,
62
64
StatusMessage,
63
65
NotificationSettings,
64
66
Profile,
@@ -110,6 +112,7 @@ pub struct AppState {
110
112
pub calls_list: crate::call::CallsList,
111
113
pub pins: HashMap<String, Vec<PinnedMessage>>,
112
114
pub forward_request: Option<ForwardSource>,
115
pub image_viewer_request: Option<ViewerRequest>,
113
116
pub own_status: PresenceStatus,
114
117
pub own_email: String,
115
118
pub status_menu_open: bool,
@@ -205,6 +208,7 @@ impl AppState {
205
208
calls_list: crate::call::CallsList::default(),
206
209
pins: HashMap::new(),
207
210
forward_request: None,
211
image_viewer_request: None,
208
212
own_status: PresenceStatus::default(),
209
213
own_email: String::new(),
210
214
status_menu_open: false,
@@ -437,8 +441,17 @@ impl AppState {
437
441
changed = true;
438
442
}
439
443
None => {
440
let done = data::fetch_image(&engine, image);
441
self.on_done(done, cx, |_, _| {});
444
let done = data::fetch_image(&engine, image.clone());
445
cx.spawn(async move |this, cx| {
446
if !matches!(done.await, Ok(Ok(()))) {
447
this.update(cx, |state, cx| {
448
state.directory.mark_image_failed(&image.url);
449
cx.notify();
450
})
451
.ok();
452
}
453
})
454
.detach();
442
455
}
443
456
}
444
457
}
@@ -16,6 +16,7 @@ use crate::call::{ActiveCall, CallLauncher, CallMedia, MissedCall, Rings};16
use calling::meeting::LiveMeeting;16
use calling::meeting::LiveMeeting;17
use crate::card_state::{CardState, TaskDialogState};17
use crate::card_state::{CardState, TaskDialogState};18
use crate::data::{self, Directory};18
use crate::data::{self, Directory};19
use crate::image_view_gallery::ViewerRequest;19
use crate::local_previews::{LocalPreview, load_local_previews};20
use crate::local_previews::{LocalPreview, load_local_previews};20
use crate::message_actions::{ForwardSource, SavedSet};21
use crate::message_actions::{ForwardSource, SavedSet};21
use crate::notice::Notice;22
use crate::notice::Notice;@@ -59,6 +60,7 @@ pub enum AppEvent {59
CallHistory,60
CallHistory,60
Translation,61
Translation,61
Forward,62
Forward,63
ImageViewer,62
StatusMessage,64
StatusMessage,63
NotificationSettings,65
NotificationSettings,64
Profile,66
Profile,@@ -110,6 +112,7 @@ pub struct AppState {110
pub calls_list: crate::call::CallsList,112
pub calls_list: crate::call::CallsList,111
pub pins: HashMap<String, Vec<PinnedMessage>>,113
pub pins: HashMap<String, Vec<PinnedMessage>>,112
pub forward_request: Option<ForwardSource>,114
pub forward_request: Option<ForwardSource>,115
pub image_viewer_request: Option<ViewerRequest>,113
pub own_status: PresenceStatus,116
pub own_status: PresenceStatus,114
pub own_email: String,117
pub own_email: String,115
pub status_menu_open: bool,118
pub status_menu_open: bool,@@ -205,6 +208,7 @@ impl AppState {205
calls_list: crate::call::CallsList::default(),208
calls_list: crate::call::CallsList::default(),206
pins: HashMap::new(),209
pins: HashMap::new(),207
forward_request: None,210
forward_request: None,211
image_viewer_request: None,208
own_status: PresenceStatus::default(),212
own_status: PresenceStatus::default(),209
own_email: String::new(),213
own_email: String::new(),210
status_menu_open: false,214
status_menu_open: false,@@ -437,8 +441,17 @@ impl AppState {437
changed = true;441
changed = true;438
}442
}439
None => {443
None => {440
let done = data::fetch_image(&engine, image);444
let done = data::fetch_image(&engine, image.clone());441
self.on_done(done, cx, |_, _| {});445
cx.spawn(async move |this, cx| {446
if !matches!(done.await, Ok(Ok(()))) {447
this.update(cx, |state, cx| {448
state.directory.mark_image_failed(&image.url);449
cx.notify();450
})451
.ok();452
}453
})454
.detach();442
}455
}443
}456
}444
}457
}@@ -8,7 +8,7 @@ macro_rules! symbols {
8
8
};
9
9
}
10
10
11
const SYMBOLS: [(&str, &[u8]); 32] = symbols![
11
const SYMBOLS: [(&str, &[u8]); 40] = symbols![
12
12
"done",
13
13
"done_all",
14
14
"keyboard_return",
@@ -41,6 +41,14 @@ const SYMBOLS: [(&str, &[u8]); 32] = symbols![
41
41
"status_dnd",
42
42
"status_away",
43
43
"status_ring",
44
"zoom_in",
45
"zoom_out",
46
"rotate_right",
47
"forward",
48
"open_in_new",
49
"chevron_left",
50
"chevron_right",
51
"fullscreen",
44
52
];
45
53
46
54
pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {8
};8
};9
}9
}10
10
11
const SYMBOLS: [(&str, &[u8]); 32] = symbols![11
const SYMBOLS: [(&str, &[u8]); 40] = symbols![12
"done",12
"done",13
"done_all",13
"done_all",14
"keyboard_return",14
"keyboard_return",@@ -41,6 +41,14 @@ const SYMBOLS: [(&str, &[u8]); 32] = symbols![41
"status_dnd",41
"status_dnd",42
"status_away",42
"status_away",43
"status_ring",43
"status_ring",44
"zoom_in",45
"zoom_out",46
"rotate_right",47
"forward",48
"open_in_new",49
"chevron_left",50
"chevron_right",51
"fullscreen",44
];52
];45
53
46
pub struct AppAssets;54
pub struct AppAssets;@@ -2,15 +2,16 @@ 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, RealtimeEvent, StatusKind, TypingEvent};
5
use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent};
6
6
use chrono::{DateTime, Local, Offset, Utc};
7
7
use graph::Graph;
8
8
use session::{Session, SessionConfig, Transport};
9
9
use store::Store;
10
10
use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};
11
use tokio::sync::mpsc;
11
use tokio::sync::{Notify, mpsc, watch};
12
12
13
13
use crate::call::{CallLauncher, fetch_window};
14
use crate::presence_link::{self, LinkSignal};
14
15
15
16
pub type Engine = SyncEngine<Graph>;
16
17
@@ -99,17 +100,32 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {
99
100
}
100
101
}
101
102
103
fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {
104
match kind {
105
StatusKind::Connected => Some(LinkSignal::Connected),
106
StatusKind::Disconnected => Some(LinkSignal::Disconnected),
107
StatusKind::MessageLoss | StatusKind::Error => None,
108
}
109
}
110
102
111
pub fn start(
103
112
store: Arc<Store>,
104
113
transport: Arc<dyn Transport>,
105
114
ringable: bool,
115
activity: watch::Receiver<bool>,
106
116
) -> mpsc::UnboundedReceiver<BackendEvent> {
107
117
let (sender, receiver) = mpsc::unbounded_channel();
108
crate::runtime::handle().spawn(supervise(store, transport, ringable, sender));
118
crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));
109
119
receiver
110
120
}
111
121
112
async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: bool, events: EventSender) {
122
async fn supervise(
123
store: Arc<Store>,
124
transport: Arc<dyn Transport>,
125
ringable: bool,
126
activity: watch::Receiver<bool>,
127
events: EventSender,
128
) {
113
129
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));
114
130
let session = loop {
115
131
match Session::with_transport(transport.clone(), SessionConfig::default()).await {
@@ -140,11 +156,16 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: b
140
156
let _ = events.send(BackendEvent::Calls(launcher));
141
157
tokio::spawn(forward_core_events(engine.clone(), events.clone()));
142
158
let (nudge, nudges) = mpsc::unbounded_channel();
159
let resend = Arc::new(Notify::new());
160
let link = presence_link::start(&session, activity.clone(), resend.clone());
143
161
tokio::spawn(realtime_loop(
144
162
session.clone(),
145
163
engine.clone(),
146
164
events.clone(),
147
165
nudge,
166
activity,
167
resend,
168
link,
148
169
));
149
170
tokio::spawn(calendar_loop(session.clone(), events.clone()));
150
171
tokio::spawn(pins_loop(session, events.clone()));
@@ -206,12 +227,31 @@ async fn realtime_loop(
206
227
engine: Arc<Engine>,
207
228
events: EventSender,
208
229
nudge: mpsc::UnboundedSender<()>,
230
mut activity: watch::Receiver<bool>,
231
resend: Arc<Notify>,
232
link: mpsc::UnboundedSender<LinkSignal>,
209
233
) {
210
234
loop {
211
235
let _ = events.send(BackendEvent::Live(LiveState::Connecting));
212
match Realtime::start(&session).await {
236
let config = RealtimeConfig {
237
initially_active: *activity.borrow(),
238
..RealtimeConfig::default()
239
};
240
match Realtime::start_with(&session, config).await {
213
241
Ok(mut realtime) => {
214
while let Some(event) = realtime.recv().await {
242
loop {
243
let event = tokio::select! {
244
event = realtime.recv() => event,
245
Ok(()) = activity.changed() => {
246
realtime.set_activity(*activity.borrow_and_update());
247
continue;
248
}
249
_ = resend.notified() => {
250
realtime.resend_activity();
251
continue;
252
}
253
};
254
let Some(event) = event else { break };
215
255
match event {
216
256
RealtimeEvent::Message(message) => {
217
257
let _ = events.send(BackendEvent::Live(LiveState::Live));
@@ -235,6 +275,9 @@ async fn realtime_loop(
235
275
}
236
276
RealtimeEvent::Status(status) => {
237
277
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));
278
if let Some(signal) = link_signal_for(status.kind) {
279
let _ = link.send(signal);
280
}
238
281
let receipt_engine = engine.clone();
239
282
let receipt_status = status.clone();
240
283
tokio::spawn(async move {
@@ -249,15 +292,18 @@ async fn realtime_loop(
249
292
}
250
293
}
251
294
RealtimeEvent::Endpoint(endpoint) => {
295
let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));
252
296
let engine = engine.clone();
253
297
tokio::spawn(async move { engine.presence_endpoint(endpoint).await });
254
298
}
255
299
}
256
300
}
257
301
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));
302
let _ = link.send(LinkSignal::Disconnected);
258
303
}
259
304
Err(_) => {
260
305
let _ = events.send(BackendEvent::Live(LiveState::Failed));
306
let _ = link.send(LinkSignal::Disconnected);
261
307
}
262
308
}
263
309
tokio::time::sleep(REALTIME_RETRY).await;
@@ -468,4 +514,12 @@ mod tests {
468
514
);
469
515
assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);
470
516
}
517
518
#[test]
519
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));
522
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);
523
assert_eq!(link_signal_for(StatusKind::Error), None);
524
}
471
525
}
@@ -2,15 +2,16 @@ 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, RealtimeEvent, StatusKind, TypingEvent};5
use chatsvc::{Calendar, CalendarEvent, EventKind, MessageEvent, Pins, Realtime, RealtimeConfig, RealtimeEvent, StatusKind, TypingEvent};6
use chrono::{DateTime, Local, Offset, Utc};6
use chrono::{DateTime, Local, Offset, Utc};7
use graph::Graph;7
use graph::Graph;8
use session::{Session, SessionConfig, Transport};8
use session::{Session, SessionConfig, Transport};9
use store::Store;9
use store::Store;10
use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};10
use teams_core::{ChatsvcFolderSource, CoreEvent, SyncEngine};11
use tokio::sync::mpsc;11
use tokio::sync::{Notify, mpsc, watch};12
12
13
use crate::call::{CallLauncher, fetch_window};13
use crate::call::{CallLauncher, fetch_window};14
use crate::presence_link::{self, LinkSignal};14
15
15
pub type Engine = SyncEngine<Graph>;16
pub type Engine = SyncEngine<Graph>;16
17
@@ -99,17 +100,32 @@ pub fn live_state_for(kind: StatusKind) -> LiveState {99
}100
}100
}101
}101
102
103
fn link_signal_for(kind: StatusKind) -> Option<LinkSignal> {104
match kind {105
StatusKind::Connected => Some(LinkSignal::Connected),106
StatusKind::Disconnected => Some(LinkSignal::Disconnected),107
StatusKind::MessageLoss | StatusKind::Error => None,108
}109
}110
102
pub fn start(111
pub fn start(103
store: Arc<Store>,112
store: Arc<Store>,104
transport: Arc<dyn Transport>,113
transport: Arc<dyn Transport>,105
ringable: bool,114
ringable: bool,115
activity: watch::Receiver<bool>,106
) -> mpsc::UnboundedReceiver<BackendEvent> {116
) -> mpsc::UnboundedReceiver<BackendEvent> {107
let (sender, receiver) = mpsc::unbounded_channel();117
let (sender, receiver) = mpsc::unbounded_channel();108
crate::runtime::handle().spawn(supervise(store, transport, ringable, sender));118
crate::runtime::handle().spawn(supervise(store, transport, ringable, activity, sender));109
receiver119
receiver110
}120
}111
121
112
async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: bool, events: EventSender) {122
async fn supervise(123
store: Arc<Store>,124
transport: Arc<dyn Transport>,125
ringable: bool,126
activity: watch::Receiver<bool>,127
events: EventSender,128
) {113
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));129
let _ = events.send(BackendEvent::Connection(ConnectionState::Connecting));114
let session = loop {130
let session = loop {115
match Session::with_transport(transport.clone(), SessionConfig::default()).await {131
match Session::with_transport(transport.clone(), SessionConfig::default()).await {@@ -140,11 +156,16 @@ async fn supervise(store: Arc<Store>, transport: Arc<dyn Transport>, ringable: b140
let _ = events.send(BackendEvent::Calls(launcher));156
let _ = events.send(BackendEvent::Calls(launcher));141
tokio::spawn(forward_core_events(engine.clone(), events.clone()));157
tokio::spawn(forward_core_events(engine.clone(), events.clone()));142
let (nudge, nudges) = mpsc::unbounded_channel();158
let (nudge, nudges) = mpsc::unbounded_channel();159
let resend = Arc::new(Notify::new());160
let link = presence_link::start(&session, activity.clone(), resend.clone());143
tokio::spawn(realtime_loop(161
tokio::spawn(realtime_loop(144
session.clone(),162
session.clone(),145
engine.clone(),163
engine.clone(),146
events.clone(),164
events.clone(),147
nudge,165
nudge,166
activity,167
resend,168
link,148
));169
));149
tokio::spawn(calendar_loop(session.clone(), events.clone()));170
tokio::spawn(calendar_loop(session.clone(), events.clone()));150
tokio::spawn(pins_loop(session, events.clone()));171
tokio::spawn(pins_loop(session, events.clone()));@@ -206,12 +227,31 @@ async fn realtime_loop(206
engine: Arc<Engine>,227
engine: Arc<Engine>,207
events: EventSender,228
events: EventSender,208
nudge: mpsc::UnboundedSender<()>,229
nudge: mpsc::UnboundedSender<()>,230
mut activity: watch::Receiver<bool>,231
resend: Arc<Notify>,232
link: mpsc::UnboundedSender<LinkSignal>,209
) {233
) {210
loop {234
loop {211
let _ = events.send(BackendEvent::Live(LiveState::Connecting));235
let _ = events.send(BackendEvent::Live(LiveState::Connecting));212
match Realtime::start(&session).await {236
let config = RealtimeConfig {237
initially_active: *activity.borrow(),238
..RealtimeConfig::default()239
};240
match Realtime::start_with(&session, config).await {213
Ok(mut realtime) => {241
Ok(mut realtime) => {214
while let Some(event) = realtime.recv().await {242
loop {243
let event = tokio::select! {244
event = realtime.recv() => event,245
Ok(()) = activity.changed() => {246
realtime.set_activity(*activity.borrow_and_update());247
continue;248
}249
_ = resend.notified() => {250
realtime.resend_activity();251
continue;252
}253
};254
let Some(event) = event else { break };215
match event {255
match event {216
RealtimeEvent::Message(message) => {256
RealtimeEvent::Message(message) => {217
let _ = events.send(BackendEvent::Live(LiveState::Live));257
let _ = events.send(BackendEvent::Live(LiveState::Live));@@ -235,6 +275,9 @@ async fn realtime_loop(235
}275
}236
RealtimeEvent::Status(status) => {276
RealtimeEvent::Status(status) => {237
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));277
let _ = events.send(BackendEvent::Live(live_state_for(status.kind)));278
if let Some(signal) = link_signal_for(status.kind) {279
let _ = link.send(signal);280
}238
let receipt_engine = engine.clone();281
let receipt_engine = engine.clone();239
let receipt_status = status.clone();282
let receipt_status = status.clone();240
tokio::spawn(async move {283
tokio::spawn(async move {@@ -249,15 +292,18 @@ async fn realtime_loop(249
}292
}250
}293
}251
RealtimeEvent::Endpoint(endpoint) => {294
RealtimeEvent::Endpoint(endpoint) => {295
let _ = link.send(LinkSignal::Endpoint(endpoint.endpoint_id.clone()));252
let engine = engine.clone();296
let engine = engine.clone();253
tokio::spawn(async move { engine.presence_endpoint(endpoint).await });297
tokio::spawn(async move { engine.presence_endpoint(endpoint).await });254
}298
}255
}299
}256
}300
}257
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));301
let _ = events.send(BackendEvent::Live(LiveState::Reconnecting));302
let _ = link.send(LinkSignal::Disconnected);258
}303
}259
Err(_) => {304
Err(_) => {260
let _ = events.send(BackendEvent::Live(LiveState::Failed));305
let _ = events.send(BackendEvent::Live(LiveState::Failed));306
let _ = link.send(LinkSignal::Disconnected);261
}307
}262
}308
}263
tokio::time::sleep(REALTIME_RETRY).await;309
tokio::time::sleep(REALTIME_RETRY).await;@@ -468,4 +514,12 @@ mod tests {468
);514
);469
assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);515
assert_eq!(live_state_for(StatusKind::Connected), LiveState::Live);470
}516
}517
518
#[test]519
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));522
assert_eq!(link_signal_for(StatusKind::MessageLoss), None);523
assert_eq!(link_signal_for(StatusKind::Error), None);524
}471
}525
}@@ -133,8 +133,11 @@ pub struct Directory {
133
133
pub(crate) presence_pending: HashSet<String>,
134
134
pub(crate) images: HashMap<String, ImageEntry>,
135
135
pub(crate) images_requested: HashSet<String>,
136
pub(crate) images_failed: HashMap<String, Instant>,
136
137
}
137
138
139
const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);
140
138
141
impl Directory {
139
142
pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {
140
143
self.avatars.get(user_id)
@@ -144,6 +147,15 @@ impl Directory {
144
147
self.images.get(key)
145
148
}
146
149
150
pub fn image_failed(&self, key: &str) -> bool {
151
self.images_failed.contains_key(key) && !self.images.contains_key(key)
152
}
153
154
pub fn mark_image_failed(&mut self, key: &str) {
155
self.images_failed.insert(key.to_owned(), Instant::now());
156
self.images_requested.remove(key);
157
}
158
147
159
pub fn set_image(&mut self, key: &str, path: &Path) {
148
160
let size = image::image_dimensions(path).ok();
149
161
self.images.insert(
@@ -158,7 +170,13 @@ impl Directory {
158
170
pub fn images_to_request(&mut self, keys: impl IntoIterator<Item = String>) -> Vec<String> {
159
171
keys.into_iter()
160
172
.filter(|key| {
161
!self.images.contains_key(key) && self.images_requested.insert(key.clone())
173
let failed_recently = self
174
.images_failed
175
.get(key)
176
.is_some_and(|failed| failed.elapsed() < IMAGE_RETRY_AFTER);
177
!self.images.contains_key(key)
178
&& !failed_recently
179
&& self.images_requested.insert(key.clone())
162
180
})
163
181
.collect()
164
182
}
@@ -595,6 +613,28 @@ mod tests {
595
613
assert_eq!(directory.pending_avatars().len(), 2);
596
614
}
597
615
616
#[test]
617
fn a_failed_image_is_requested_again_only_after_the_retry_delay() {
618
let mut directory = Directory::default();
619
assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);
620
directory.mark_image_failed("a");
621
assert!(directory.images_to_request(["a".to_owned()]).is_empty());
622
directory
623
.images_failed
624
.insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);
625
assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);
626
}
627
628
#[test]
629
fn a_failed_image_is_only_failed_until_it_arrives() {
630
let mut directory = Directory::default();
631
assert!(!directory.image_failed("a"));
632
directory.mark_image_failed("a");
633
assert!(directory.image_failed("a"));
634
directory.set_image("a", Path::new("a.png"));
635
assert!(!directory.image_failed("a"));
636
}
637
598
638
#[test]
599
639
fn images_are_requested_once() {
600
640
let mut directory = Directory::default();
@@ -133,8 +133,11 @@ pub struct Directory {133
pub(crate) presence_pending: HashSet<String>,133
pub(crate) presence_pending: HashSet<String>,134
pub(crate) images: HashMap<String, ImageEntry>,134
pub(crate) images: HashMap<String, ImageEntry>,135
pub(crate) images_requested: HashSet<String>,135
pub(crate) images_requested: HashSet<String>,136
pub(crate) images_failed: HashMap<String, Instant>,136
}137
}137
138
139
const IMAGE_RETRY_AFTER: Duration = Duration::from_secs(60);140
138
impl Directory {141
impl Directory {139
pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {142
pub fn avatar(&self, user_id: &str) -> Option<&AvatarState> {140
self.avatars.get(user_id)143
self.avatars.get(user_id)@@ -144,6 +147,15 @@ impl Directory {144
self.images.get(key)147
self.images.get(key)145
}148
}146
149
150
pub fn image_failed(&self, key: &str) -> bool {151
self.images_failed.contains_key(key) && !self.images.contains_key(key)152
}153
154
pub fn mark_image_failed(&mut self, key: &str) {155
self.images_failed.insert(key.to_owned(), Instant::now());156
self.images_requested.remove(key);157
}158
147
pub fn set_image(&mut self, key: &str, path: &Path) {159
pub fn set_image(&mut self, key: &str, path: &Path) {148
let size = image::image_dimensions(path).ok();160
let size = image::image_dimensions(path).ok();149
self.images.insert(161
self.images.insert(@@ -158,7 +170,13 @@ impl Directory {158
pub fn images_to_request(&mut self, keys: impl IntoIterator<Item = String>) -> Vec<String> {170
pub fn images_to_request(&mut self, keys: impl IntoIterator<Item = String>) -> Vec<String> {159
keys.into_iter()171
keys.into_iter()160
.filter(|key| {172
.filter(|key| {161
!self.images.contains_key(key) && self.images_requested.insert(key.clone())173
let failed_recently = self174
.images_failed175
.get(key)176
.is_some_and(|failed| failed.elapsed() < IMAGE_RETRY_AFTER);177
!self.images.contains_key(key)178
&& !failed_recently179
&& self.images_requested.insert(key.clone())162
})180
})163
.collect()181
.collect()164
}182
}@@ -595,6 +613,28 @@ mod tests {595
assert_eq!(directory.pending_avatars().len(), 2);613
assert_eq!(directory.pending_avatars().len(), 2);596
}614
}597
615
616
#[test]617
fn a_failed_image_is_requested_again_only_after_the_retry_delay() {618
let mut directory = Directory::default();619
assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);620
directory.mark_image_failed("a");621
assert!(directory.images_to_request(["a".to_owned()]).is_empty());622
directory623
.images_failed624
.insert("a".to_owned(), Instant::now() - IMAGE_RETRY_AFTER);625
assert_eq!(directory.images_to_request(["a".to_owned()]), vec!["a"]);626
}627
628
#[test]629
fn a_failed_image_is_only_failed_until_it_arrives() {630
let mut directory = Directory::default();631
assert!(!directory.image_failed("a"));632
directory.mark_image_failed("a");633
assert!(directory.image_failed("a"));634
directory.set_image("a", Path::new("a.png"));635
assert!(!directory.image_failed("a"));636
}637
598
#[test]638
#[test]599
fn images_are_requested_once() {639
fn images_are_requested_once() {600
let mut directory = Directory::default();640
let mut directory = Directory::default();@@ -0,0 +1,170 @@
1
use chrono::{FixedOffset, NaiveDate};
2
use teams_core::ImageRef;
3
4
use crate::format;
5
use crate::rows::{MessageRow, Row};
6
7
#[derive(Debug, Clone, PartialEq)]
8
pub struct GalleryItem {
9
pub message_key: String,
10
pub image: ImageRef,
11
pub sender_id: Option<String>,
12
pub author: String,
13
pub time: String,
14
pub caption: String,
15
}
16
17
#[derive(Debug, Clone, PartialEq)]
18
pub struct ViewerRequest {
19
pub conversation_id: String,
20
pub conversation_title: String,
21
pub items: Vec<GalleryItem>,
22
pub index: usize,
23
}
24
25
pub fn caption_of(row: &MessageRow) -> String {
26
row.blocks
27
.iter()
28
.filter_map(|block| block.markdown())
29
.collect::<Vec<_>>()
30
.join(" ")
31
.split_whitespace()
32
.collect::<Vec<_>>()
33
.join(" ")
34
}
35
36
pub fn viewer_time_label(row: &MessageRow, today: NaiveDate, offset: FixedOffset) -> String {
37
let label = format::post_time_label(row.created_at, today, offset);
38
if row.created_at.with_timezone(&offset).date_naive() == today {
39
format!("Today {label}")
40
} else {
41
label
42
}
43
}
44
45
pub fn collect_gallery(rows: &[Row], today: NaiveDate, offset: FixedOffset) -> Vec<GalleryItem> {
46
rows.iter()
47
.flat_map(Row::messages)
48
.filter(|message| !message.deleted)
49
.flat_map(|message| {
50
let caption = caption_of(message);
51
let time = viewer_time_label(message, today, offset);
52
message.images.iter().map(move |image| GalleryItem {
53
message_key: message.key.clone(),
54
image: image.clone(),
55
sender_id: message.sender_id.clone(),
56
author: message.author.clone(),
57
time: time.clone(),
58
caption: caption.clone(),
59
})
60
})
61
.collect()
62
}
63
64
pub fn position_of(items: &[GalleryItem], message_key: &str, url: &str) -> Option<usize> {
65
items
66
.iter()
67
.position(|item| item.message_key == message_key && item.image.url == url)
68
}
69
70
#[cfg(test)]
71
mod tests {
72
use std::collections::HashMap;
73
74
use chrono::{TimeZone, Utc};
75
use store::MessageRecord;
76
77
use super::*;
78
use crate::rows::{RowContext, message_row};
79
use crate::translation::TranslationContext;
80
81
fn offset() -> FixedOffset {
82
FixedOffset::east_opt(0).unwrap()
83
}
84
85
fn today() -> NaiveDate {
86
NaiveDate::from_ymd_opt(2026, 10, 7).unwrap()
87
}
88
89
fn context() -> RowContext {
90
RowContext {
91
offset: offset(),
92
today: today(),
93
my_user_id: None,
94
names: HashMap::new(),
95
pending_reactions: HashMap::new(),
96
card_overrides: HashMap::new(),
97
translation: TranslationContext::default(),
98
}
99
}
100
101
fn record(id: &str, day: u32, body_html: &str) -> MessageRecord {
102
MessageRecord {
103
conversation_id: "c".into(),
104
message_id: id.into(),
105
reply_to_id: None,
106
sender_id: Some("u".into()),
107
sender_name: Some("Mara".into()),
108
sender_application_id: None,
109
links_json: "[]".to_owned(),
110
created_at: Utc.with_ymd_and_hms(2026, 10, day, 13, 40, 0).unwrap(),
111
edited_at: None,
112
deleted: false,
113
body_html: body_html.to_owned(),
114
attachments_json: "[]".into(),
115
reactions_json: "[]".into(),
116
mentions_json: "[]".into(),
117
subject: None,
118
}
119
}
120
121
fn rows(records: &[MessageRecord]) -> Vec<Row> {
122
records
123
.iter()
124
.map(|record| Row::Message(Box::new(message_row(record, &context()))))
125
.collect()
126
}
127
128
#[test]
129
fn images_come_in_message_order_and_skip_text_only_and_deleted_messages() {
130
let mut deleted = record("d", 7, "<img src=\"https://x/deleted\">");
131
deleted.deleted = true;
132
let records = [
133
record("a", 6, "<p>first</p><img src=\"https://x/one\"><img src=\"https://x/two\">"),
134
record("b", 6, "<p>no image</p>"),
135
deleted,
136
record("c", 7, "<img src=\"https://x/three\">"),
137
];
138
let items = collect_gallery(&rows(&records), today(), offset());
139
let urls: Vec<&str> = items.iter().map(|item| item.image.url.as_str()).collect();
140
assert_eq!(urls, ["https://x/one", "https://x/two", "https://x/three"]);
141
assert_eq!(items[0].message_key, "a");
142
assert_eq!(items[2].message_key, "c");
143
}
144
145
#[test]
146
fn items_carry_author_caption_and_time() {
147
let records = [
148
record("a", 6, "<p>Release notes</p><p>second line</p><img src=\"https://x/one\">"),
149
record("b", 7, "<img src=\"https://x/two\">"),
150
];
151
let items = collect_gallery(&rows(&records), today(), offset());
152
assert_eq!(items[0].author, "Mara");
153
assert_eq!(items[0].caption, "Release notes second line");
154
assert_eq!(items[0].time, "Yesterday 13:40");
155
assert_eq!(items[1].caption, "");
156
assert_eq!(items[1].time, "Today 13:40");
157
}
158
159
#[test]
160
fn position_matches_message_and_url() {
161
let records = [
162
record("a", 6, "<img src=\"https://x/one\">"),
163
record("b", 6, "<img src=\"https://x/one\">"),
164
];
165
let items = collect_gallery(&rows(&records), today(), offset());
166
assert_eq!(position_of(&items, "b", "https://x/one"), Some(1));
167
assert_eq!(position_of(&items, "a", "https://x/one"), Some(0));
168
assert_eq!(position_of(&items, "a", "https://x/other"), None);
169
}
170
}
@@ -0,0 +1,170 @@1
use chrono::{FixedOffset, NaiveDate};2
use teams_core::ImageRef;3
4
use crate::format;5
use crate::rows::{MessageRow, Row};6
7
#[derive(Debug, Clone, PartialEq)]8
pub struct GalleryItem {9
pub message_key: String,10
pub image: ImageRef,11
pub sender_id: Option<String>,12
pub author: String,13
pub time: String,14
pub caption: String,15
}16
17
#[derive(Debug, Clone, PartialEq)]18
pub struct ViewerRequest {19
pub conversation_id: String,20
pub conversation_title: String,21
pub items: Vec<GalleryItem>,22
pub index: usize,23
}24
25
pub fn caption_of(row: &MessageRow) -> String {26
row.blocks27
.iter()28
.filter_map(|block| block.markdown())29
.collect::<Vec<_>>()30
.join(" ")31
.split_whitespace()32
.collect::<Vec<_>>()33
.join(" ")34
}35
36
pub fn viewer_time_label(row: &MessageRow, today: NaiveDate, offset: FixedOffset) -> String {37
let label = format::post_time_label(row.created_at, today, offset);38
if row.created_at.with_timezone(&offset).date_naive() == today {39
format!("Today {label}")40
} else {41
label42
}43
}44
45
pub fn collect_gallery(rows: &[Row], today: NaiveDate, offset: FixedOffset) -> Vec<GalleryItem> {46
rows.iter()47
.flat_map(Row::messages)48
.filter(|message| !message.deleted)49
.flat_map(|message| {50
let caption = caption_of(message);51
let time = viewer_time_label(message, today, offset);52
message.images.iter().map(move |image| GalleryItem {53
message_key: message.key.clone(),54
image: image.clone(),55
sender_id: message.sender_id.clone(),56
author: message.author.clone(),57
time: time.clone(),58
caption: caption.clone(),59
})60
})61
.collect()62
}63
64
pub fn position_of(items: &[GalleryItem], message_key: &str, url: &str) -> Option<usize> {65
items66
.iter()67
.position(|item| item.message_key == message_key && item.image.url == url)68
}69
70
#[cfg(test)]71
mod tests {72
use std::collections::HashMap;73
74
use chrono::{TimeZone, Utc};75
use store::MessageRecord;76
77
use super::*;78
use crate::rows::{RowContext, message_row};79
use crate::translation::TranslationContext;80
81
fn offset() -> FixedOffset {82
FixedOffset::east_opt(0).unwrap()83
}84
85
fn today() -> NaiveDate {86
NaiveDate::from_ymd_opt(2026, 10, 7).unwrap()87
}88
89
fn context() -> RowContext {90
RowContext {91
offset: offset(),92
today: today(),93
my_user_id: None,94
names: HashMap::new(),95
pending_reactions: HashMap::new(),96
card_overrides: HashMap::new(),97
translation: TranslationContext::default(),98
}99
}100
101
fn record(id: &str, day: u32, body_html: &str) -> MessageRecord {102
MessageRecord {103
conversation_id: "c".into(),104
message_id: id.into(),105
reply_to_id: None,106
sender_id: Some("u".into()),107
sender_name: Some("Mara".into()),108
sender_application_id: None,109
links_json: "[]".to_owned(),110
created_at: Utc.with_ymd_and_hms(2026, 10, day, 13, 40, 0).unwrap(),111
edited_at: None,112
deleted: false,113
body_html: body_html.to_owned(),114
attachments_json: "[]".into(),115
reactions_json: "[]".into(),116
mentions_json: "[]".into(),117
subject: None,118
}119
}120
121
fn rows(records: &[MessageRecord]) -> Vec<Row> {122
records123
.iter()124
.map(|record| Row::Message(Box::new(message_row(record, &context()))))125
.collect()126
}127
128
#[test]129
fn images_come_in_message_order_and_skip_text_only_and_deleted_messages() {130
let mut deleted = record("d", 7, "<img src=\"https://x/deleted\">");131
deleted.deleted = true;132
let records = [133
record("a", 6, "<p>first</p><img src=\"https://x/one\"><img src=\"https://x/two\">"),134
record("b", 6, "<p>no image</p>"),135
deleted,136
record("c", 7, "<img src=\"https://x/three\">"),137
];138
let items = collect_gallery(&rows(&records), today(), offset());139
let urls: Vec<&str> = items.iter().map(|item| item.image.url.as_str()).collect();140
assert_eq!(urls, ["https://x/one", "https://x/two", "https://x/three"]);141
assert_eq!(items[0].message_key, "a");142
assert_eq!(items[2].message_key, "c");143
}144
145
#[test]146
fn items_carry_author_caption_and_time() {147
let records = [148
record("a", 6, "<p>Release notes</p><p>second line</p><img src=\"https://x/one\">"),149
record("b", 7, "<img src=\"https://x/two\">"),150
];151
let items = collect_gallery(&rows(&records), today(), offset());152
assert_eq!(items[0].author, "Mara");153
assert_eq!(items[0].caption, "Release notes second line");154
assert_eq!(items[0].time, "Yesterday 13:40");155
assert_eq!(items[1].caption, "");156
assert_eq!(items[1].time, "Today 13:40");157
}158
159
#[test]160
fn position_matches_message_and_url() {161
let records = [162
record("a", 6, "<img src=\"https://x/one\">"),163
record("b", 6, "<img src=\"https://x/one\">"),164
];165
let items = collect_gallery(&rows(&records), today(), offset());166
assert_eq!(position_of(&items, "b", "https://x/one"), Some(1));167
assert_eq!(position_of(&items, "a", "https://x/one"), Some(0));168
assert_eq!(position_of(&items, "a", "https://x/other"), None);169
}170
}@@ -0,0 +1,251 @@
1
use std::ops::Range;
2
3
pub type Pair = (f32, f32);
4
5
pub const MAX_ZOOM: f32 = 4.;
6
pub const ZOOM_STEP: f32 = 1.25;
7
const WHEEL_SENSITIVITY: f32 = 0.01;
8
const SCALE_EPSILON: f32 = 0.001;
9
10
pub fn rotated_size(size: Pair, quarter_turns: u8) -> Pair {
11
if quarter_turns % 2 == 0 {
12
size
13
} else {
14
(size.1, size.0)
15
}
16
}
17
18
pub fn next_rotation(quarter_turns: u8) -> u8 {
19
(quarter_turns + 1) % 4
20
}
21
22
pub fn fit_scale(image: Pair, stage: Pair) -> f32 {
23
if image.0 <= 0. || image.1 <= 0. || stage.0 <= 0. || stage.1 <= 0. {
24
return 1.;
25
}
26
(stage.0 / image.0).min(stage.1 / image.1).min(1.)
27
}
28
29
pub fn clamp_scale(scale: f32, fit: f32) -> f32 {
30
scale.clamp(fit, MAX_ZOOM.max(fit))
31
}
32
33
pub fn display_size(image: Pair, scale: f32) -> Pair {
34
(image.0 * scale, image.1 * scale)
35
}
36
37
pub fn clamp_pan(pan: Pair, display: Pair, stage: Pair) -> Pair {
38
let limit = |display: f32, stage: f32| ((display - stage) / 2.).max(0.);
39
let (limit_x, limit_y) = (limit(display.0, stage.0), limit(display.1, stage.1));
40
(
41
pan.0.clamp(-limit_x, limit_x),
42
pan.1.clamp(-limit_y, limit_y),
43
)
44
}
45
46
pub fn image_origin(display: Pair, stage: Pair, pan: Pair) -> Pair {
47
(
48
(stage.0 - display.0) / 2. + pan.0,
49
(stage.1 - display.1) / 2. + pan.1,
50
)
51
}
52
53
#[derive(Debug, Clone, Copy, PartialEq)]
54
pub struct View {
55
pub scale: f32,
56
pub pan: Pair,
57
}
58
59
pub fn zoom_at(view: View, wanted: f32, anchor: Pair, image: Pair, stage: Pair) -> View {
60
let fit = fit_scale(image, stage);
61
let scale = clamp_scale(wanted, fit);
62
let ratio = scale / view.scale;
63
let pan = (
64
anchor.0 - (anchor.0 - view.pan.0) * ratio,
65
anchor.1 - (anchor.1 - view.pan.1) * ratio,
66
);
67
View {
68
scale,
69
pan: clamp_pan(pan, display_size(image, scale), stage),
70
}
71
}
72
73
pub fn wheel_scale(scale: f32, delta_y: f32) -> f32 {
74
scale * (delta_y * WHEEL_SENSITIVITY).exp()
75
}
76
77
pub fn step_scale(scale: f32, direction: i32) -> f32 {
78
scale * ZOOM_STEP.powi(direction)
79
}
80
81
pub fn toggle_target(scale: f32, fit: f32) -> f32 {
82
if scale > fit + SCALE_EPSILON {
83
fit
84
} else {
85
1_f32.max(fit)
86
}
87
}
88
89
pub fn percent_label(scale: f32) -> String {
90
format!("{}%", (scale * 100.).round() as u32)
91
}
92
93
pub fn step_index(current: usize, len: usize, delta: isize) -> usize {
94
if len == 0 {
95
return 0;
96
}
97
current
98
.saturating_add_signed(delta)
99
.min(len - 1)
100
}
101
102
pub fn counter_label(index: usize, len: usize) -> String {
103
format!("{} of {}", index + 1, len)
104
}
105
106
pub fn thumbnail_window(index: usize, len: usize, capacity: usize) -> Range<usize> {
107
let capacity = capacity.max(1).min(len);
108
let start = index
109
.saturating_sub(capacity / 2)
110
.min(len.saturating_sub(capacity));
111
start..start + capacity
112
}
113
114
#[cfg(test)]
115
mod tests {
116
use super::*;
117
118
const STAGE: Pair = (800., 600.);
119
120
#[test]
121
fn fit_contains_large_images_and_never_upscales() {
122
assert_eq!(fit_scale((1600., 1200.), STAGE), 0.5);
123
assert_eq!(fit_scale((1600., 300.), STAGE), 0.5);
124
assert_eq!(fit_scale((100., 100.), STAGE), 1.);
125
assert_eq!(fit_scale((0., 100.), STAGE), 1.);
126
}
127
128
#[test]
129
fn rotation_swaps_the_sides_on_odd_quarter_turns() {
130
assert_eq!(rotated_size((400., 200.), 0), (400., 200.));
131
assert_eq!(rotated_size((400., 200.), 1), (200., 400.));
132
assert_eq!(rotated_size((400., 200.), 2), (400., 200.));
133
assert_eq!(rotated_size((400., 200.), 3), (200., 400.));
134
assert_eq!(next_rotation(3), 0);
135
assert_eq!(next_rotation(0), 1);
136
}
137
138
#[test]
139
fn scale_is_limited_to_fit_and_four_times_the_source() {
140
assert_eq!(clamp_scale(0.1, 0.5), 0.5);
141
assert_eq!(clamp_scale(9., 0.5), MAX_ZOOM);
142
assert_eq!(clamp_scale(2., 0.5), 2.);
143
}
144
145
#[test]
146
fn pan_is_clamped_to_the_image_bounds() {
147
let display = (1600., 400.);
148
assert_eq!(clamp_pan((900., 50.), display, STAGE), (400., 0.));
149
assert_eq!(clamp_pan((-900., -50.), display, STAGE), (-400., 0.));
150
assert_eq!(clamp_pan((10., 10.), (400., 300.), STAGE), (0., 0.));
151
}
152
153
#[test]
154
fn image_origin_centers_and_follows_the_pan() {
155
assert_eq!(image_origin((400., 300.), STAGE, (0., 0.)), (200., 150.));
156
assert_eq!(image_origin((1600., 600.), STAGE, (-100., 0.)), (-500., 0.));
157
}
158
159
#[test]
160
fn zoom_keeps_the_point_under_the_cursor_fixed() {
161
let image = (2000., 1500.);
162
let start = View {
163
scale: 0.4,
164
pan: (0., 0.),
165
};
166
let anchor = (100., 50.);
167
let zoomed = zoom_at(start, 1., anchor, image, STAGE);
168
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);
171
assert!((before.0 - after.0).abs() < 0.01);
172
assert!((before.1 - after.1).abs() < 0.01);
173
}
174
175
#[test]
176
fn zooming_back_to_fit_recenters() {
177
let image = (2000., 1500.);
178
let zoomed = View {
179
scale: 2.,
180
pan: (300., -200.),
181
};
182
let fit = zoom_at(zoomed, 0.1, (50., 50.), image, STAGE);
183
assert_eq!(fit.scale, 0.4);
184
assert_eq!(fit.pan, (0., 0.));
185
}
186
187
#[test]
188
fn zoom_never_pans_past_the_edges() {
189
let image = (2000., 1500.);
190
let start = View {
191
scale: 0.4,
192
pan: (0., 0.),
193
};
194
let zoomed = zoom_at(start, 4., (-400., -300.), image, STAGE);
195
let limit = (2000. * 4. - 800.) / 2.;
196
assert!(zoomed.pan.0.abs() <= limit);
197
}
198
199
#[test]
200
fn wheel_zooms_in_up_and_out_down_symmetrically() {
201
assert!(wheel_scale(1., 20.) > 1.);
202
assert!(wheel_scale(1., -20.) < 1.);
203
assert!((wheel_scale(wheel_scale(1., 20.), -20.) - 1.).abs() < 1e-5);
204
assert_eq!(wheel_scale(1., 0.), 1.);
205
}
206
207
#[test]
208
fn keyboard_steps_multiply_and_divide_by_the_step() {
209
assert_eq!(step_scale(1., 1), ZOOM_STEP);
210
assert!((step_scale(ZOOM_STEP, -1) - 1.).abs() < 1e-6);
211
}
212
213
#[test]
214
fn double_click_toggles_between_fit_and_full_size() {
215
assert_eq!(toggle_target(0.4, 0.4), 1.);
216
assert_eq!(toggle_target(1., 0.4), 0.4);
217
assert_eq!(toggle_target(2., 0.4), 0.4);
218
assert_eq!(toggle_target(1., 1.), 1.);
219
}
220
221
#[test]
222
fn percent_label_is_relative_to_the_source_size() {
223
assert_eq!(percent_label(1.), "100%");
224
assert_eq!(percent_label(0.375), "38%");
225
assert_eq!(percent_label(4.), "400%");
226
}
227
228
#[test]
229
fn navigation_stops_at_both_ends() {
230
assert_eq!(step_index(0, 5, -1), 0);
231
assert_eq!(step_index(4, 5, 1), 4);
232
assert_eq!(step_index(2, 5, 1), 3);
233
assert_eq!(step_index(2, 5, -1), 1);
234
assert_eq!(step_index(0, 0, 1), 0);
235
}
236
237
#[test]
238
fn counter_is_one_based() {
239
assert_eq!(counter_label(2, 12), "3 of 12");
240
}
241
242
#[test]
243
fn thumbnail_window_follows_the_current_image_inside_the_list() {
244
assert_eq!(thumbnail_window(0, 20, 5), 0..5);
245
assert_eq!(thumbnail_window(10, 20, 5), 8..13);
246
assert_eq!(thumbnail_window(19, 20, 5), 15..20);
247
assert_eq!(thumbnail_window(1, 3, 5), 0..3);
248
assert_eq!(thumbnail_window(0, 0, 5), 0..0);
249
assert_eq!(thumbnail_window(2, 4, 0), 2..3);
250
}
251
}
@@ -0,0 +1,251 @@1
use std::ops::Range;2
3
pub type Pair = (f32, f32);4
5
pub const MAX_ZOOM: f32 = 4.;6
pub const ZOOM_STEP: f32 = 1.25;7
const WHEEL_SENSITIVITY: f32 = 0.01;8
const SCALE_EPSILON: f32 = 0.001;9
10
pub fn rotated_size(size: Pair, quarter_turns: u8) -> Pair {11
if quarter_turns % 2 == 0 {12
size13
} else {14
(size.1, size.0)15
}16
}17
18
pub fn next_rotation(quarter_turns: u8) -> u8 {19
(quarter_turns + 1) % 420
}21
22
pub fn fit_scale(image: Pair, stage: Pair) -> f32 {23
if image.0 <= 0. || image.1 <= 0. || stage.0 <= 0. || stage.1 <= 0. {24
return 1.;25
}26
(stage.0 / image.0).min(stage.1 / image.1).min(1.)27
}28
29
pub fn clamp_scale(scale: f32, fit: f32) -> f32 {30
scale.clamp(fit, MAX_ZOOM.max(fit))31
}32
33
pub fn display_size(image: Pair, scale: f32) -> Pair {34
(image.0 * scale, image.1 * scale)35
}36
37
pub fn clamp_pan(pan: Pair, display: Pair, stage: Pair) -> Pair {38
let limit = |display: f32, stage: f32| ((display - stage) / 2.).max(0.);39
let (limit_x, limit_y) = (limit(display.0, stage.0), limit(display.1, stage.1));40
(41
pan.0.clamp(-limit_x, limit_x),42
pan.1.clamp(-limit_y, limit_y),43
)44
}45
46
pub fn image_origin(display: Pair, stage: Pair, pan: Pair) -> Pair {47
(48
(stage.0 - display.0) / 2. + pan.0,49
(stage.1 - display.1) / 2. + pan.1,50
)51
}52
53
#[derive(Debug, Clone, Copy, PartialEq)]54
pub struct View {55
pub scale: f32,56
pub pan: Pair,57
}58
59
pub fn zoom_at(view: View, wanted: f32, anchor: Pair, image: Pair, stage: Pair) -> View {60
let fit = fit_scale(image, stage);61
let scale = clamp_scale(wanted, fit);62
let ratio = scale / view.scale;63
let pan = (64
anchor.0 - (anchor.0 - view.pan.0) * ratio,65
anchor.1 - (anchor.1 - view.pan.1) * ratio,66
);67
View {68
scale,69
pan: clamp_pan(pan, display_size(image, scale), stage),70
}71
}72
73
pub fn wheel_scale(scale: f32, delta_y: f32) -> f32 {74
scale * (delta_y * WHEEL_SENSITIVITY).exp()75
}76
77
pub fn step_scale(scale: f32, direction: i32) -> f32 {78
scale * ZOOM_STEP.powi(direction)79
}80
81
pub fn toggle_target(scale: f32, fit: f32) -> f32 {82
if scale > fit + SCALE_EPSILON {83
fit84
} else {85
1_f32.max(fit)86
}87
}88
89
pub fn percent_label(scale: f32) -> String {90
format!("{}%", (scale * 100.).round() as u32)91
}92
93
pub fn step_index(current: usize, len: usize, delta: isize) -> usize {94
if len == 0 {95
return 0;96
}97
current98
.saturating_add_signed(delta)99
.min(len - 1)100
}101
102
pub fn counter_label(index: usize, len: usize) -> String {103
format!("{} of {}", index + 1, len)104
}105
106
pub fn thumbnail_window(index: usize, len: usize, capacity: usize) -> Range<usize> {107
let capacity = capacity.max(1).min(len);108
let start = index109
.saturating_sub(capacity / 2)110
.min(len.saturating_sub(capacity));111
start..start + capacity112
}113
114
#[cfg(test)]115
mod tests {116
use super::*;117
118
const STAGE: Pair = (800., 600.);119
120
#[test]121
fn fit_contains_large_images_and_never_upscales() {122
assert_eq!(fit_scale((1600., 1200.), STAGE), 0.5);123
assert_eq!(fit_scale((1600., 300.), STAGE), 0.5);124
assert_eq!(fit_scale((100., 100.), STAGE), 1.);125
assert_eq!(fit_scale((0., 100.), STAGE), 1.);126
}127
128
#[test]129
fn rotation_swaps_the_sides_on_odd_quarter_turns() {130
assert_eq!(rotated_size((400., 200.), 0), (400., 200.));131
assert_eq!(rotated_size((400., 200.), 1), (200., 400.));132
assert_eq!(rotated_size((400., 200.), 2), (400., 200.));133
assert_eq!(rotated_size((400., 200.), 3), (200., 400.));134
assert_eq!(next_rotation(3), 0);135
assert_eq!(next_rotation(0), 1);136
}137
138
#[test]139
fn scale_is_limited_to_fit_and_four_times_the_source() {140
assert_eq!(clamp_scale(0.1, 0.5), 0.5);141
assert_eq!(clamp_scale(9., 0.5), MAX_ZOOM);142
assert_eq!(clamp_scale(2., 0.5), 2.);143
}144
145
#[test]146
fn pan_is_clamped_to_the_image_bounds() {147
let display = (1600., 400.);148
assert_eq!(clamp_pan((900., 50.), display, STAGE), (400., 0.));149
assert_eq!(clamp_pan((-900., -50.), display, STAGE), (-400., 0.));150
assert_eq!(clamp_pan((10., 10.), (400., 300.), STAGE), (0., 0.));151
}152
153
#[test]154
fn image_origin_centers_and_follows_the_pan() {155
assert_eq!(image_origin((400., 300.), STAGE, (0., 0.)), (200., 150.));156
assert_eq!(image_origin((1600., 600.), STAGE, (-100., 0.)), (-500., 0.));157
}158
159
#[test]160
fn zoom_keeps_the_point_under_the_cursor_fixed() {161
let image = (2000., 1500.);162
let start = View {163
scale: 0.4,164
pan: (0., 0.),165
};166
let anchor = (100., 50.);167
let zoomed = zoom_at(start, 1., anchor, image, STAGE);168
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);171
assert!((before.0 - after.0).abs() < 0.01);172
assert!((before.1 - after.1).abs() < 0.01);173
}174
175
#[test]176
fn zooming_back_to_fit_recenters() {177
let image = (2000., 1500.);178
let zoomed = View {179
scale: 2.,180
pan: (300., -200.),181
};182
let fit = zoom_at(zoomed, 0.1, (50., 50.), image, STAGE);183
assert_eq!(fit.scale, 0.4);184
assert_eq!(fit.pan, (0., 0.));185
}186
187
#[test]188
fn zoom_never_pans_past_the_edges() {189
let image = (2000., 1500.);190
let start = View {191
scale: 0.4,192
pan: (0., 0.),193
};194
let zoomed = zoom_at(start, 4., (-400., -300.), image, STAGE);195
let limit = (2000. * 4. - 800.) / 2.;196
assert!(zoomed.pan.0.abs() <= limit);197
}198
199
#[test]200
fn wheel_zooms_in_up_and_out_down_symmetrically() {201
assert!(wheel_scale(1., 20.) > 1.);202
assert!(wheel_scale(1., -20.) < 1.);203
assert!((wheel_scale(wheel_scale(1., 20.), -20.) - 1.).abs() < 1e-5);204
assert_eq!(wheel_scale(1., 0.), 1.);205
}206
207
#[test]208
fn keyboard_steps_multiply_and_divide_by_the_step() {209
assert_eq!(step_scale(1., 1), ZOOM_STEP);210
assert!((step_scale(ZOOM_STEP, -1) - 1.).abs() < 1e-6);211
}212
213
#[test]214
fn double_click_toggles_between_fit_and_full_size() {215
assert_eq!(toggle_target(0.4, 0.4), 1.);216
assert_eq!(toggle_target(1., 0.4), 0.4);217
assert_eq!(toggle_target(2., 0.4), 0.4);218
assert_eq!(toggle_target(1., 1.), 1.);219
}220
221
#[test]222
fn percent_label_is_relative_to_the_source_size() {223
assert_eq!(percent_label(1.), "100%");224
assert_eq!(percent_label(0.375), "38%");225
assert_eq!(percent_label(4.), "400%");226
}227
228
#[test]229
fn navigation_stops_at_both_ends() {230
assert_eq!(step_index(0, 5, -1), 0);231
assert_eq!(step_index(4, 5, 1), 4);232
assert_eq!(step_index(2, 5, 1), 3);233
assert_eq!(step_index(2, 5, -1), 1);234
assert_eq!(step_index(0, 0, 1), 0);235
}236
237
#[test]238
fn counter_is_one_based() {239
assert_eq!(counter_label(2, 12), "3 of 12");240
}241
242
#[test]243
fn thumbnail_window_follows_the_current_image_inside_the_list() {244
assert_eq!(thumbnail_window(0, 20, 5), 0..5);245
assert_eq!(thumbnail_window(10, 20, 5), 8..13);246
assert_eq!(thumbnail_window(19, 20, 5), 15..20);247
assert_eq!(thumbnail_window(1, 3, 5), 0..3);248
assert_eq!(thumbnail_window(0, 0, 5), 0..0);249
assert_eq!(thumbnail_window(2, 4, 0), 2..3);250
}251
}@@ -33,6 +33,8 @@ mod format;
33
33
mod frame_log;
34
34
mod fuzzy;
35
35
mod gifs;
36
mod image_view_gallery;
37
mod image_view_math;
36
38
mod local_previews;
37
39
mod message_actions;
38
40
mod notice;
@@ -41,6 +43,7 @@ mod notify;
41
43
mod outbox;
42
44
mod pending_rows;
43
45
mod people;
46
mod presence_link;
44
47
mod profile_model;
45
48
mod profile_state;
46
49
mod reaction_model;
@@ -62,6 +65,7 @@ mod translation;
62
65
mod translation_actions;
63
66
mod typing;
64
67
mod updater;
68
mod user_activity;
65
69
mod views;
66
70
67
71
use std::path::PathBuf;
@@ -82,6 +86,7 @@ const WINDOW_WIDTH: f32 = 1240.;
82
86
const WINDOW_HEIGHT: f32 = 820.;
83
87
const WINDOW_MIN_WIDTH: f32 = 640.;
84
88
const WINDOW_MIN_HEIGHT: f32 = 480.;
89
const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);
85
90
const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
86
91
const DATABASE_FILE: &str = "cache.sqlite3";
87
92
#[cfg(windows)]
@@ -217,10 +222,12 @@ fn main() {
217
222
open_store(&path)
218
223
};
219
224
let store = Arc::new(store);
225
let user_input = user_activity::UserInput::new();
220
226
let receiver = (!arguments.demo)
221
227
.then(|| {
222
228
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
223
backend::start(store.clone(), transport, !arguments.read_only)
229
let activity = user_activity::track(user_input.clone());
230
backend::start(store.clone(), transport, !arguments.read_only, activity)
224
231
});
225
232
226
233
let mut application = gpui_kit::application();
@@ -246,7 +253,8 @@ fn main() {
246
253
state
247
254
});
248
255
cx.set_global(app_state::AppHandle(state.clone()));
249
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
256
cx.set_global(views::shell::UserInputHandle(user_input));
257
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
250
258
if arguments.demo {
251
259
state.update(cx, |state, cx| {
252
260
demo::seed_directory(state);
@@ -290,6 +298,7 @@ fn main() {
290
298
.detach();
291
299
cx.activate(true);
292
300
});
301
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
293
302
#[cfg(windows)]
294
303
updater::exit_now();
295
304
}
@@ -33,6 +33,8 @@ mod format;33
mod frame_log;33
mod frame_log;34
mod fuzzy;34
mod fuzzy;35
mod gifs;35
mod gifs;36
mod image_view_gallery;37
mod image_view_math;36
mod local_previews;38
mod local_previews;37
mod message_actions;39
mod message_actions;38
mod notice;40
mod notice;@@ -41,6 +43,7 @@ mod notify;41
mod outbox;43
mod outbox;42
mod pending_rows;44
mod pending_rows;43
mod people;45
mod people;46
mod presence_link;44
mod profile_model;47
mod profile_model;45
mod profile_state;48
mod profile_state;46
mod reaction_model;49
mod reaction_model;@@ -62,6 +65,7 @@ mod translation;62
mod translation_actions;65
mod translation_actions;63
mod typing;66
mod typing;64
mod updater;67
mod updater;68
mod user_activity;65
mod views;69
mod views;66
70
67
use std::path::PathBuf;71
use std::path::PathBuf;@@ -82,6 +86,7 @@ const WINDOW_WIDTH: f32 = 1240.;82
const WINDOW_HEIGHT: f32 = 820.;86
const WINDOW_HEIGHT: f32 = 820.;83
const WINDOW_MIN_WIDTH: f32 = 640.;87
const WINDOW_MIN_WIDTH: f32 = 640.;84
const WINDOW_MIN_HEIGHT: f32 = 480.;88
const WINDOW_MIN_HEIGHT: f32 = 480.;89
const ENDPOINT_UNREGISTER_TIMEOUT: Duration = Duration::from_millis(800);85
const SINGLE_INSTANCE_NAME: &str = "rusty-teams";90
const SINGLE_INSTANCE_NAME: &str = "rusty-teams";86
const DATABASE_FILE: &str = "cache.sqlite3";91
const DATABASE_FILE: &str = "cache.sqlite3";87
#[cfg(windows)]92
#[cfg(windows)]@@ -217,10 +222,12 @@ fn main() {217
open_store(&path)222
open_store(&path)218
};223
};219
let store = Arc::new(store);224
let store = Arc::new(store);225
let user_input = user_activity::UserInput::new();220
let receiver = (!arguments.demo)226
let receiver = (!arguments.demo)221
.then(|| {227
.then(|| {222
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());228
let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());223
backend::start(store.clone(), transport, !arguments.read_only)229
let activity = user_activity::track(user_input.clone());230
backend::start(store.clone(), transport, !arguments.read_only, activity)224
});231
});225
232
226
let mut application = gpui_kit::application();233
let mut application = gpui_kit::application();@@ -246,7 +253,8 @@ fn main() {246
state253
state247
});254
});248
cx.set_global(app_state::AppHandle(state.clone()));255
cx.set_global(app_state::AppHandle(state.clone()));249
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);256
cx.set_global(views::shell::UserInputHandle(user_input));257
agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);250
if arguments.demo {258
if arguments.demo {251
state.update(cx, |state, cx| {259
state.update(cx, |state, cx| {252
demo::seed_directory(state);260
demo::seed_directory(state);@@ -290,6 +298,7 @@ fn main() {290
.detach();298
.detach();291
cx.activate(true);299
cx.activate(true);292
});300
});301
presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);293
#[cfg(windows)]302
#[cfg(windows)]294
updater::exit_now();303
updater::exit_now();295
}304
}@@ -7,6 +7,7 @@ use teams_core::{PinnedMessage, SavedMessage};
7
7
8
8
use crate::app_state::{AppEvent, AppState, Selection};
9
9
use crate::format;
10
use crate::image_view_gallery::ViewerRequest;
10
11
use crate::notice::short_error;
11
12
use crate::notify::selection_for;
12
13
use crate::rows::{message_text, reply_excerpt};
@@ -335,6 +336,16 @@ impl AppState {
335
336
cx.notify();
336
337
}
337
338
339
pub fn request_image_viewer(&mut self, request: ViewerRequest, cx: &mut Context<Self>) {
340
self.image_viewer_request = Some(request);
341
cx.emit(AppEvent::ImageViewer);
342
cx.notify();
343
}
344
345
pub fn take_image_viewer_request(&mut self) -> Option<ViewerRequest> {
346
self.image_viewer_request.take()
347
}
348
338
349
pub fn take_forward_request(&mut self) -> Option<ForwardSource> {
339
350
self.forward_request.take()
340
351
}
@@ -7,6 +7,7 @@ use teams_core::{PinnedMessage, SavedMessage};7
7
8
use crate::app_state::{AppEvent, AppState, Selection};8
use crate::app_state::{AppEvent, AppState, Selection};9
use crate::format;9
use crate::format;10
use crate::image_view_gallery::ViewerRequest;10
use crate::notice::short_error;11
use crate::notice::short_error;11
use crate::notify::selection_for;12
use crate::notify::selection_for;12
use crate::rows::{message_text, reply_excerpt};13
use crate::rows::{message_text, reply_excerpt};@@ -335,6 +336,16 @@ impl AppState {335
cx.notify();336
cx.notify();336
}337
}337
338
339
pub fn request_image_viewer(&mut self, request: ViewerRequest, cx: &mut Context<Self>) {340
self.image_viewer_request = Some(request);341
cx.emit(AppEvent::ImageViewer);342
cx.notify();343
}344
345
pub fn take_image_viewer_request(&mut self) -> Option<ViewerRequest> {346
self.image_viewer_request.take()347
}348
338
pub fn take_forward_request(&mut self) -> Option<ForwardSource> {349
pub fn take_forward_request(&mut self) -> Option<ForwardSource> {339
self.forward_request.take()350
self.forward_request.take()340
}351
}@@ -0,0 +1,407 @@
1
use std::sync::{Arc, OnceLock};
2
use std::time::Duration;
3
4
use chatsvc::cards::CardTransport;
5
use chatsvc::{ActivityReporting, PresenceService, error_status, is_endpoint_missing};
6
use session::Session;
7
use tokio::sync::{Notify, mpsc, oneshot, watch};
8
use tokio::time::{Instant, MissedTickBehavior, interval};
9
10
const FALLBACK_AFTER: Duration = Duration::from_secs(120);
11
const FALLBACK_INTERVAL: Duration = Duration::from_secs(120);
12
const CHECK_INTERVAL: Duration = Duration::from_secs(30);
13
const RETRY_BASE: Duration = Duration::from_secs(30);
14
const RETRY_MAX: Duration = Duration::from_secs(240);
15
const PERMANENT_FAILURE_RETRY: Duration = Duration::from_secs(30 * 60);
16
17
static UNREGISTER: OnceLock<mpsc::UnboundedSender<oneshot::Sender<()>>> = OnceLock::new();
18
19
#[derive(Debug, Clone, PartialEq, Eq)]
20
pub enum LinkSignal {
21
Endpoint(String),
22
Connected,
23
Disconnected,
24
}
25
26
pub fn report_due(down_for: Option<Duration>, since_last_report: Option<Duration>, activity_changed: bool) -> bool {
27
down_for.is_some_and(|down_for| down_for >= FALLBACK_AFTER)
28
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))
29
}
30
31
pub fn retry_delay(failures: u32) -> Duration {
32
let doublings = failures.saturating_sub(1).min(8);
33
(RETRY_BASE * 2u32.pow(doublings)).min(RETRY_MAX)
34
}
35
36
pub fn is_permanent_failure(status: Option<u16>) -> bool {
37
matches!(status, Some(400..=499)) && !matches!(status, Some(401 | 404 | 408 | 429))
38
}
39
40
pub fn start(
41
session: &Session,
42
activity: watch::Receiver<bool>,
43
resend: Arc<Notify>,
44
) -> mpsc::UnboundedSender<LinkSignal> {
45
let (signals, receiver) = mpsc::unbounded_channel();
46
let (unregister, unregisters) = mpsc::unbounded_channel();
47
let _ = UNREGISTER.set(unregister);
48
let link = Link::new(PresenceService::new(session), activity, resend);
49
tokio::spawn(link.run(receiver, unregisters));
50
signals
51
}
52
53
/// Gives up after `timeout` so quitting is never held back.
54
pub fn unregister_on_exit(timeout: Duration) {
55
let Some(unregister) = UNREGISTER.get() else {
56
return;
57
};
58
let (done, finished) = oneshot::channel();
59
if unregister.send(done).is_err() {
60
return;
61
}
62
let _ = crate::runtime::handle().block_on(tokio::time::timeout(timeout, finished));
63
}
64
65
#[derive(Default)]
66
struct RetryState {
67
failures: u32,
68
next_attempt: Option<Instant>,
69
last_error: Option<String>,
70
}
71
72
impl RetryState {
73
fn may_attempt(&self, now: Instant) -> bool {
74
self.next_attempt.is_none_or(|next| now >= next)
75
}
76
77
fn succeeded(&mut self) {
78
*self = RetryState::default();
79
}
80
81
fn failed(&mut self, now: Instant, error: &chatsvc::Error) -> Option<String> {
82
self.failures += 1;
83
let delay = if is_permanent_failure(error_status(error)) {
84
PERMANENT_FAILURE_RETRY
85
} else {
86
retry_delay(self.failures)
87
};
88
self.next_attempt = Some(now + delay);
89
let message = error.to_string();
90
let is_new = self.last_error.as_deref() != Some(message.as_str());
91
self.last_error = Some(message.clone());
92
is_new.then_some(message)
93
}
94
}
95
96
struct Link<T: CardTransport> {
97
service: PresenceService<T>,
98
activity: watch::Receiver<bool>,
99
resend: Arc<Notify>,
100
endpoint_id: Option<String>,
101
registered: bool,
102
applied: ActivityReporting,
103
down_since: Option<Instant>,
104
last_report: Option<Instant>,
105
retry: RetryState,
106
}
107
108
impl<T: CardTransport> Link<T> {
109
fn new(service: PresenceService<T>, activity: watch::Receiver<bool>, resend: Arc<Notify>) -> Self {
110
Link {
111
service,
112
activity,
113
resend,
114
endpoint_id: None,
115
registered: false,
116
applied: ActivityReporting::Transport,
117
down_since: None,
118
last_report: None,
119
retry: RetryState::default(),
120
}
121
}
122
123
async fn run(
124
mut self,
125
mut signals: mpsc::UnboundedReceiver<LinkSignal>,
126
mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>,
127
) {
128
let mut check = interval(CHECK_INTERVAL);
129
check.set_missed_tick_behavior(MissedTickBehavior::Delay);
130
loop {
131
tokio::select! {
132
signal = signals.recv() => {
133
let Some(signal) = signal else { return };
134
self.apply(signal).await;
135
}
136
Ok(()) = self.activity.changed() => {
137
self.activity.borrow_and_update();
138
self.reconcile(true).await;
139
}
140
_ = check.tick() => self.reconcile(false).await,
141
Some(done) = unregisters.recv() => {
142
if let Some(endpoint_id) = &self.endpoint_id {
143
let _ = self.service.unregister_endpoint(endpoint_id).await;
144
}
145
let _ = done.send(());
146
}
147
}
148
}
149
}
150
151
async fn apply(&mut self, signal: LinkSignal) {
152
match signal {
153
LinkSignal::Endpoint(endpoint_id) => {
154
if self.endpoint_id.as_deref() == Some(endpoint_id.as_str()) {
155
return;
156
}
157
if let Some(previous) = self.endpoint_id.replace(endpoint_id) {
158
let _ = self.service.unregister_endpoint(&previous).await;
159
}
160
self.registered = false;
161
self.applied = ActivityReporting::Transport;
162
self.down_since = None;
163
self.last_report = None;
164
self.retry.succeeded();
165
}
166
LinkSignal::Connected => {
167
if self.down_since.take().is_some() {
168
self.last_report = None;
169
self.retry.succeeded();
170
}
171
}
172
LinkSignal::Disconnected => {
173
self.down_since.get_or_insert_with(Instant::now);
174
}
175
}
176
self.reconcile(false).await;
177
}
178
179
async fn reconcile(&mut self, activity_changed: bool) {
180
let Some(endpoint_id) = self.endpoint_id.clone() else {
181
return;
182
};
183
let now = Instant::now();
184
let down_for = self.down_since.map(|since| now.duration_since(since));
185
let wanted = match down_for {
186
Some(down_for) if down_for >= FALLBACK_AFTER => ActivityReporting::Direct,
187
_ => ActivityReporting::Transport,
188
};
189
if (!self.registered || self.applied != wanted) && self.retry.may_attempt(now) {
190
self.register(&endpoint_id, wanted, now).await;
191
}
192
if wanted != ActivityReporting::Direct || !self.registered || self.applied != wanted {
193
return;
194
}
195
let since_last_report = self.last_report.map(|last| now.duration_since(last));
196
if report_due(down_for, since_last_report, activity_changed) {
197
self.last_report = Some(now);
198
let active = *self.activity.borrow();
199
self.report_with_recovery(&endpoint_id, active).await;
200
}
201
}
202
203
async fn register(&mut self, endpoint_id: &str, reporting: ActivityReporting, now: Instant) {
204
match self.service.register_endpoint(endpoint_id, reporting).await {
205
Ok(()) => {
206
self.registered = true;
207
self.applied = reporting;
208
self.retry.succeeded();
209
if reporting == ActivityReporting::Transport {
210
self.resend.notify_one();
211
}
212
}
213
Err(error) => {
214
if let Some(message) = self.retry.failed(now, &error) {
215
crate::diagnostics::record(format!("presence: endpoint not registered: {message}"));
216
}
217
}
218
}
219
}
220
221
async fn report_with_recovery(&self, endpoint_id: &str, active: bool) {
222
let Err(error) = self.service.report_activity(endpoint_id, active).await else {
223
return;
224
};
225
if is_endpoint_missing(&error)
226
&& self
227
.service
228
.register_endpoint(endpoint_id, ActivityReporting::Direct)
229
.await
230
.is_ok()
231
&& self.service.report_activity(endpoint_id, active).await.is_ok()
232
{
233
return;
234
}
235
crate::diagnostics::record(format!("presence: activity not reported: {error}"));
236
}
237
}
238
239
#[cfg(test)]
240
mod tests {
241
use std::sync::Mutex;
242
243
use chatsvc::Result;
244
use session::{ApiResponse, Method, Request, Scope};
245
246
use super::*;
247
248
const PRESENCE: &str = "https://presence.teams.microsoft.com/v1/me";
249
250
type Sent = Arc<Mutex<Vec<(Method, String, Option<String>)>>>;
251
252
struct Scripted {
253
statuses: Mutex<Vec<u16>>,
254
sent: Sent,
255
}
256
257
impl CardTransport for Scripted {
258
async fn send(&self, request: Request, _scope: Scope) -> Result<ApiResponse> {
259
let reporting = request
260
.body
261
.as_ref()
262
.and_then(|body| body["activityReporting"].as_str())
263
.map(str::to_owned);
264
self.sent.lock().unwrap().push((request.method, request.url, reporting));
265
let mut statuses = self.statuses.lock().unwrap();
266
let status = if statuses.is_empty() { 200 } else { statuses.remove(0) };
267
Ok(ApiResponse {
268
status,
269
body: serde_json::Value::Null,
270
retry_after: None,
271
})
272
}
273
}
274
275
fn link(statuses: Vec<u16>) -> (Link<Scripted>, Sent, Arc<Notify>) {
276
let sent: Sent = Arc::default();
277
let resend = Arc::new(Notify::new());
278
let (_, activity) = watch::channel(true);
279
let service = PresenceService::with_transport(Scripted {
280
statuses: Mutex::new(statuses),
281
sent: sent.clone(),
282
});
283
(Link::new(service, activity, resend.clone()), sent, resend)
284
}
285
286
fn calls(sent: &Sent) -> Vec<String> {
287
sent.lock()
288
.unwrap()
289
.iter()
290
.map(|(method, url, reporting)| {
291
let path = url.strip_prefix(PRESENCE).unwrap();
292
format!("{} {path} {}", method.as_str(), reporting.as_deref().unwrap_or("-"))
293
})
294
.collect()
295
}
296
297
fn seconds(count: u64) -> Duration {
298
Duration::from_secs(count)
299
}
300
301
#[test]
302
fn fallback_starts_after_two_minutes_down_and_repeats_every_two_minutes() {
303
assert!(!report_due(None, None, true));
304
assert!(!report_due(Some(seconds(119)), None, true));
305
assert!(report_due(Some(seconds(120)), None, false));
306
assert!(!report_due(Some(seconds(150)), Some(seconds(30)), false));
307
assert!(report_due(Some(seconds(240)), Some(seconds(120)), false));
308
assert!(report_due(Some(seconds(150)), Some(seconds(30)), true));
309
}
310
311
#[test]
312
fn retry_delay_doubles_up_to_four_minutes() {
313
let delays: Vec<u64> = (1..=6).map(|failures| retry_delay(failures).as_secs()).collect();
314
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);
315
}
316
317
#[test]
318
fn only_client_errors_other_than_auth_and_missing_are_permanent() {
319
assert!(is_permanent_failure(Some(400)));
320
assert!(is_permanent_failure(Some(403)));
321
assert!(!is_permanent_failure(Some(401)));
322
assert!(!is_permanent_failure(Some(404)));
323
assert!(!is_permanent_failure(Some(429)));
324
assert!(!is_permanent_failure(Some(500)));
325
assert!(!is_permanent_failure(None));
326
}
327
328
#[tokio::test]
329
async fn a_repeated_identical_failure_is_logged_once_and_backs_off() {
330
let error = chatsvc::Error::UnexpectedAnswer("x".into());
331
let mut retry = RetryState::default();
332
let now = Instant::now();
333
assert!(retry.failed(now, &error).is_some());
334
assert!(retry.failed(now, &error).is_none());
335
assert!(!retry.may_attempt(now + seconds(59)));
336
assert!(retry.may_attempt(now + seconds(60)));
337
retry.succeeded();
338
assert!(retry.may_attempt(now));
339
}
340
341
#[tokio::test]
342
async fn a_permanent_failure_retries_only_after_half_an_hour_or_a_new_endpoint() {
343
let (mut link, sent, _) = link(vec![403]);
344
link.apply(LinkSignal::Endpoint("a".into())).await;
345
link.reconcile(false).await;
346
assert_eq!(calls(&sent).len(), 1);
347
assert!(!link.retry.may_attempt(Instant::now() + seconds(29 * 60)));
348
assert!(link.retry.may_attempt(Instant::now() + seconds(31 * 60)));
349
link.apply(LinkSignal::Endpoint("b".into())).await;
350
assert_eq!(calls(&sent).len(), 3);
351
}
352
353
#[tokio::test]
354
async fn the_same_endpoint_announced_again_is_not_registered_again() {
355
let (mut link, sent, resend) = link(vec![]);
356
link.apply(LinkSignal::Endpoint("a".into())).await;
357
link.apply(LinkSignal::Endpoint("a".into())).await;
358
link.apply(LinkSignal::Connected).await;
359
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);
360
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");
361
}
362
363
#[tokio::test]
364
async fn a_new_endpoint_removes_the_old_one_first() {
365
let (mut link, sent, _) = link(vec![]);
366
link.apply(LinkSignal::Endpoint("a".into())).await;
367
link.apply(LinkSignal::Endpoint("b".into())).await;
368
assert_eq!(
369
calls(&sent),
370
["PUT /endpoints/ Transport", "DELETE /endpoints/a -", "PUT /endpoints/ Transport"]
371
);
372
}
373
374
#[tokio::test]
375
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {
376
let (mut link, sent, resend) = link(vec![]);
377
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));
380
link.reconcile(false).await;
381
link.apply(LinkSignal::Connected).await;
382
assert_eq!(
383
calls(&sent),
384
[
385
"PUT /endpoints/ Transport",
386
"PUT /endpoints/ Direct",
387
"POST /reportmyactivity/ -",
388
"PUT /endpoints/ Transport",
389
]
390
);
391
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");
392
}
393
394
#[tokio::test]
395
async fn a_missing_endpoint_is_registered_again_before_the_report_is_repeated() {
396
let (link, sent, _) = link(vec![404, 200, 200]);
397
link.report_with_recovery("epid-1", true).await;
398
assert_eq!(
399
calls(&sent),
400
[
401
"POST /reportmyactivity/ -",
402
"PUT /endpoints/ Direct",
403
"POST /reportmyactivity/ -",
404
]
405
);
406
}
407
}
@@ -0,0 +1,407 @@1
use std::sync::{Arc, OnceLock};2
use std::time::Duration;3
4
use chatsvc::cards::CardTransport;5
use chatsvc::{ActivityReporting, PresenceService, error_status, is_endpoint_missing};6
use session::Session;7
use tokio::sync::{Notify, mpsc, oneshot, watch};8
use tokio::time::{Instant, MissedTickBehavior, interval};9
10
const FALLBACK_AFTER: Duration = Duration::from_secs(120);11
const FALLBACK_INTERVAL: Duration = Duration::from_secs(120);12
const CHECK_INTERVAL: Duration = Duration::from_secs(30);13
const RETRY_BASE: Duration = Duration::from_secs(30);14
const RETRY_MAX: Duration = Duration::from_secs(240);15
const PERMANENT_FAILURE_RETRY: Duration = Duration::from_secs(30 * 60);16
17
static UNREGISTER: OnceLock<mpsc::UnboundedSender<oneshot::Sender<()>>> = OnceLock::new();18
19
#[derive(Debug, Clone, PartialEq, Eq)]20
pub enum LinkSignal {21
Endpoint(String),22
Connected,23
Disconnected,24
}25
26
pub fn report_due(down_for: Option<Duration>, since_last_report: Option<Duration>, activity_changed: bool) -> bool {27
down_for.is_some_and(|down_for| down_for >= FALLBACK_AFTER)28
&& (activity_changed || since_last_report.is_none_or(|since| since >= FALLBACK_INTERVAL))29
}30
31
pub fn retry_delay(failures: u32) -> Duration {32
let doublings = failures.saturating_sub(1).min(8);33
(RETRY_BASE * 2u32.pow(doublings)).min(RETRY_MAX)34
}35
36
pub fn is_permanent_failure(status: Option<u16>) -> bool {37
matches!(status, Some(400..=499)) && !matches!(status, Some(401 | 404 | 408 | 429))38
}39
40
pub fn start(41
session: &Session,42
activity: watch::Receiver<bool>,43
resend: Arc<Notify>,44
) -> mpsc::UnboundedSender<LinkSignal> {45
let (signals, receiver) = mpsc::unbounded_channel();46
let (unregister, unregisters) = mpsc::unbounded_channel();47
let _ = UNREGISTER.set(unregister);48
let link = Link::new(PresenceService::new(session), activity, resend);49
tokio::spawn(link.run(receiver, unregisters));50
signals51
}52
53
/// Gives up after `timeout` so quitting is never held back.54
pub fn unregister_on_exit(timeout: Duration) {55
let Some(unregister) = UNREGISTER.get() else {56
return;57
};58
let (done, finished) = oneshot::channel();59
if unregister.send(done).is_err() {60
return;61
}62
let _ = crate::runtime::handle().block_on(tokio::time::timeout(timeout, finished));63
}64
65
#[derive(Default)]66
struct RetryState {67
failures: u32,68
next_attempt: Option<Instant>,69
last_error: Option<String>,70
}71
72
impl RetryState {73
fn may_attempt(&self, now: Instant) -> bool {74
self.next_attempt.is_none_or(|next| now >= next)75
}76
77
fn succeeded(&mut self) {78
*self = RetryState::default();79
}80
81
fn failed(&mut self, now: Instant, error: &chatsvc::Error) -> Option<String> {82
self.failures += 1;83
let delay = if is_permanent_failure(error_status(error)) {84
PERMANENT_FAILURE_RETRY85
} else {86
retry_delay(self.failures)87
};88
self.next_attempt = Some(now + delay);89
let message = error.to_string();90
let is_new = self.last_error.as_deref() != Some(message.as_str());91
self.last_error = Some(message.clone());92
is_new.then_some(message)93
}94
}95
96
struct Link<T: CardTransport> {97
service: PresenceService<T>,98
activity: watch::Receiver<bool>,99
resend: Arc<Notify>,100
endpoint_id: Option<String>,101
registered: bool,102
applied: ActivityReporting,103
down_since: Option<Instant>,104
last_report: Option<Instant>,105
retry: RetryState,106
}107
108
impl<T: CardTransport> Link<T> {109
fn new(service: PresenceService<T>, activity: watch::Receiver<bool>, resend: Arc<Notify>) -> Self {110
Link {111
service,112
activity,113
resend,114
endpoint_id: None,115
registered: false,116
applied: ActivityReporting::Transport,117
down_since: None,118
last_report: None,119
retry: RetryState::default(),120
}121
}122
123
async fn run(124
mut self,125
mut signals: mpsc::UnboundedReceiver<LinkSignal>,126
mut unregisters: mpsc::UnboundedReceiver<oneshot::Sender<()>>,127
) {128
let mut check = interval(CHECK_INTERVAL);129
check.set_missed_tick_behavior(MissedTickBehavior::Delay);130
loop {131
tokio::select! {132
signal = signals.recv() => {133
let Some(signal) = signal else { return };134
self.apply(signal).await;135
}136
Ok(()) = self.activity.changed() => {137
self.activity.borrow_and_update();138
self.reconcile(true).await;139
}140
_ = check.tick() => self.reconcile(false).await,141
Some(done) = unregisters.recv() => {142
if let Some(endpoint_id) = &self.endpoint_id {143
let _ = self.service.unregister_endpoint(endpoint_id).await;144
}145
let _ = done.send(());146
}147
}148
}149
}150
151
async fn apply(&mut self, signal: LinkSignal) {152
match signal {153
LinkSignal::Endpoint(endpoint_id) => {154
if self.endpoint_id.as_deref() == Some(endpoint_id.as_str()) {155
return;156
}157
if let Some(previous) = self.endpoint_id.replace(endpoint_id) {158
let _ = self.service.unregister_endpoint(&previous).await;159
}160
self.registered = false;161
self.applied = ActivityReporting::Transport;162
self.down_since = None;163
self.last_report = None;164
self.retry.succeeded();165
}166
LinkSignal::Connected => {167
if self.down_since.take().is_some() {168
self.last_report = None;169
self.retry.succeeded();170
}171
}172
LinkSignal::Disconnected => {173
self.down_since.get_or_insert_with(Instant::now);174
}175
}176
self.reconcile(false).await;177
}178
179
async fn reconcile(&mut self, activity_changed: bool) {180
let Some(endpoint_id) = self.endpoint_id.clone() else {181
return;182
};183
let now = Instant::now();184
let down_for = self.down_since.map(|since| now.duration_since(since));185
let wanted = match down_for {186
Some(down_for) if down_for >= FALLBACK_AFTER => ActivityReporting::Direct,187
_ => ActivityReporting::Transport,188
};189
if (!self.registered || self.applied != wanted) && self.retry.may_attempt(now) {190
self.register(&endpoint_id, wanted, now).await;191
}192
if wanted != ActivityReporting::Direct || !self.registered || self.applied != wanted {193
return;194
}195
let since_last_report = self.last_report.map(|last| now.duration_since(last));196
if report_due(down_for, since_last_report, activity_changed) {197
self.last_report = Some(now);198
let active = *self.activity.borrow();199
self.report_with_recovery(&endpoint_id, active).await;200
}201
}202
203
async fn register(&mut self, endpoint_id: &str, reporting: ActivityReporting, now: Instant) {204
match self.service.register_endpoint(endpoint_id, reporting).await {205
Ok(()) => {206
self.registered = true;207
self.applied = reporting;208
self.retry.succeeded();209
if reporting == ActivityReporting::Transport {210
self.resend.notify_one();211
}212
}213
Err(error) => {214
if let Some(message) = self.retry.failed(now, &error) {215
crate::diagnostics::record(format!("presence: endpoint not registered: {message}"));216
}217
}218
}219
}220
221
async fn report_with_recovery(&self, endpoint_id: &str, active: bool) {222
let Err(error) = self.service.report_activity(endpoint_id, active).await else {223
return;224
};225
if is_endpoint_missing(&error)226
&& self227
.service228
.register_endpoint(endpoint_id, ActivityReporting::Direct)229
.await230
.is_ok()231
&& self.service.report_activity(endpoint_id, active).await.is_ok()232
{233
return;234
}235
crate::diagnostics::record(format!("presence: activity not reported: {error}"));236
}237
}238
239
#[cfg(test)]240
mod tests {241
use std::sync::Mutex;242
243
use chatsvc::Result;244
use session::{ApiResponse, Method, Request, Scope};245
246
use super::*;247
248
const PRESENCE: &str = "https://presence.teams.microsoft.com/v1/me";249
250
type Sent = Arc<Mutex<Vec<(Method, String, Option<String>)>>>;251
252
struct Scripted {253
statuses: Mutex<Vec<u16>>,254
sent: Sent,255
}256
257
impl CardTransport for Scripted {258
async fn send(&self, request: Request, _scope: Scope) -> Result<ApiResponse> {259
let reporting = request260
.body261
.as_ref()262
.and_then(|body| body["activityReporting"].as_str())263
.map(str::to_owned);264
self.sent.lock().unwrap().push((request.method, request.url, reporting));265
let mut statuses = self.statuses.lock().unwrap();266
let status = if statuses.is_empty() { 200 } else { statuses.remove(0) };267
Ok(ApiResponse {268
status,269
body: serde_json::Value::Null,270
retry_after: None,271
})272
}273
}274
275
fn link(statuses: Vec<u16>) -> (Link<Scripted>, Sent, Arc<Notify>) {276
let sent: Sent = Arc::default();277
let resend = Arc::new(Notify::new());278
let (_, activity) = watch::channel(true);279
let service = PresenceService::with_transport(Scripted {280
statuses: Mutex::new(statuses),281
sent: sent.clone(),282
});283
(Link::new(service, activity, resend.clone()), sent, resend)284
}285
286
fn calls(sent: &Sent) -> Vec<String> {287
sent.lock()288
.unwrap()289
.iter()290
.map(|(method, url, reporting)| {291
let path = url.strip_prefix(PRESENCE).unwrap();292
format!("{} {path} {}", method.as_str(), reporting.as_deref().unwrap_or("-"))293
})294
.collect()295
}296
297
fn seconds(count: u64) -> Duration {298
Duration::from_secs(count)299
}300
301
#[test]302
fn fallback_starts_after_two_minutes_down_and_repeats_every_two_minutes() {303
assert!(!report_due(None, None, true));304
assert!(!report_due(Some(seconds(119)), None, true));305
assert!(report_due(Some(seconds(120)), None, false));306
assert!(!report_due(Some(seconds(150)), Some(seconds(30)), false));307
assert!(report_due(Some(seconds(240)), Some(seconds(120)), false));308
assert!(report_due(Some(seconds(150)), Some(seconds(30)), true));309
}310
311
#[test]312
fn retry_delay_doubles_up_to_four_minutes() {313
let delays: Vec<u64> = (1..=6).map(|failures| retry_delay(failures).as_secs()).collect();314
assert_eq!(delays, [30, 60, 120, 240, 240, 240]);315
}316
317
#[test]318
fn only_client_errors_other_than_auth_and_missing_are_permanent() {319
assert!(is_permanent_failure(Some(400)));320
assert!(is_permanent_failure(Some(403)));321
assert!(!is_permanent_failure(Some(401)));322
assert!(!is_permanent_failure(Some(404)));323
assert!(!is_permanent_failure(Some(429)));324
assert!(!is_permanent_failure(Some(500)));325
assert!(!is_permanent_failure(None));326
}327
328
#[tokio::test]329
async fn a_repeated_identical_failure_is_logged_once_and_backs_off() {330
let error = chatsvc::Error::UnexpectedAnswer("x".into());331
let mut retry = RetryState::default();332
let now = Instant::now();333
assert!(retry.failed(now, &error).is_some());334
assert!(retry.failed(now, &error).is_none());335
assert!(!retry.may_attempt(now + seconds(59)));336
assert!(retry.may_attempt(now + seconds(60)));337
retry.succeeded();338
assert!(retry.may_attempt(now));339
}340
341
#[tokio::test]342
async fn a_permanent_failure_retries_only_after_half_an_hour_or_a_new_endpoint() {343
let (mut link, sent, _) = link(vec![403]);344
link.apply(LinkSignal::Endpoint("a".into())).await;345
link.reconcile(false).await;346
assert_eq!(calls(&sent).len(), 1);347
assert!(!link.retry.may_attempt(Instant::now() + seconds(29 * 60)));348
assert!(link.retry.may_attempt(Instant::now() + seconds(31 * 60)));349
link.apply(LinkSignal::Endpoint("b".into())).await;350
assert_eq!(calls(&sent).len(), 3);351
}352
353
#[tokio::test]354
async fn the_same_endpoint_announced_again_is_not_registered_again() {355
let (mut link, sent, resend) = link(vec![]);356
link.apply(LinkSignal::Endpoint("a".into())).await;357
link.apply(LinkSignal::Endpoint("a".into())).await;358
link.apply(LinkSignal::Connected).await;359
assert_eq!(calls(&sent), ["PUT /endpoints/ Transport"]);360
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");361
}362
363
#[tokio::test]364
async fn a_new_endpoint_removes_the_old_one_first() {365
let (mut link, sent, _) = link(vec![]);366
link.apply(LinkSignal::Endpoint("a".into())).await;367
link.apply(LinkSignal::Endpoint("b".into())).await;368
assert_eq!(369
calls(&sent),370
["PUT /endpoints/ Transport", "DELETE /endpoints/a -", "PUT /endpoints/ Transport"]371
);372
}373
374
#[tokio::test]375
async fn long_downtime_switches_to_direct_reporting_and_a_reconnect_switches_back() {376
let (mut link, sent, resend) = link(vec![]);377
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));380
link.reconcile(false).await;381
link.apply(LinkSignal::Connected).await;382
assert_eq!(383
calls(&sent),384
[385
"PUT /endpoints/ Transport",386
"PUT /endpoints/ Direct",387
"POST /reportmyactivity/ -",388
"PUT /endpoints/ Transport",389
]390
);391
tokio::time::timeout(Duration::from_millis(500), resend.notified()).await.expect("resend");392
}393
394
#[tokio::test]395
async fn a_missing_endpoint_is_registered_again_before_the_report_is_repeated() {396
let (link, sent, _) = link(vec![404, 200, 200]);397
link.report_with_recovery("epid-1", true).await;398
assert_eq!(399
calls(&sent),400
[401
"POST /reportmyactivity/ -",402
"PUT /endpoints/ Direct",403
"POST /reportmyactivity/ -",404
]405
);406
}407
}@@ -0,0 +1,176 @@
1
use std::sync::Arc;
2
use std::sync::atomic::{AtomicU64, Ordering};
3
use std::time::{Duration, Instant};
4
5
use gpui_kit::{DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};
6
use tokio::sync::watch;
7
8
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);
9
const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);
10
11
pub struct UserInput {
12
origin: Instant,
13
last_input_millis: AtomicU64,
14
}
15
16
const NO_INPUT: u64 = u64::MAX;
17
18
impl UserInput {
19
pub fn new() -> Arc<Self> {
20
Arc::new(UserInput {
21
origin: Instant::now(),
22
last_input_millis: AtomicU64::new(NO_INPUT),
23
})
24
}
25
26
pub fn touch(&self) {
27
let elapsed = self.origin.elapsed().as_millis() as u64;
28
self.last_input_millis.store(elapsed, Ordering::Relaxed);
29
}
30
31
fn last_input(&self) -> Option<Instant> {
32
match self.last_input_millis.load(Ordering::Relaxed) {
33
NO_INPUT => None,
34
millis => Some(self.origin + Duration::from_millis(millis)),
35
}
36
}
37
}
38
39
pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {
40
canvas(
41
|_, _, _| {},
42
move |_, _, window, _| {
43
let moved = input.clone();
44
window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {
45
if phase == DispatchPhase::Capture {
46
moved.touch();
47
}
48
});
49
let pressed = input.clone();
50
window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {
51
if phase == DispatchPhase::Capture {
52
pressed.touch();
53
}
54
});
55
let scrolled = input.clone();
56
window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {
57
if phase == DispatchPhase::Capture {
58
scrolled.touch();
59
}
60
});
61
let typed = input.clone();
62
window.on_key_event(move |_: &KeyDownEvent, phase, _, _| {
63
if phase == DispatchPhase::Capture {
64
typed.touch();
65
}
66
});
67
},
68
)
69
}
70
71
pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {
72
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));
73
app_input.max(system_input)
74
}
75
76
pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {
77
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)
78
}
79
80
pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {
81
let current = is_active(last_input, now, idle_after);
82
(current != previous).then_some(current)
83
}
84
85
pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {
86
let (sender, receiver) = watch::channel(false);
87
crate::runtime::handle().spawn(async move {
88
let mut interval = tokio::time::interval(SAMPLE_INTERVAL);
89
loop {
90
interval.tick().await;
91
let now = Instant::now();
92
let last_input = latest_input(input.last_input(), system_idle(), now);
93
let previous = *sender.borrow();
94
if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) {
95
sender.send_replace(current);
96
}
97
}
98
});
99
receiver
100
}
101
102
#[cfg(windows)]
103
fn system_idle() -> Option<Duration> {
104
use windows::Win32::System::SystemInformation::GetTickCount;
105
use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
106
107
let mut info = LASTINPUTINFO {
108
cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32,
109
dwTime: 0,
110
};
111
unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| {
112
let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime);
113
Duration::from_millis(u64::from(idle_millis))
114
})
115
}
116
117
#[cfg(not(windows))]
118
fn system_idle() -> Option<Duration> {
119
None
120
}
121
122
#[cfg(test)]
123
mod tests {
124
use super::*;
125
126
fn seconds(count: u64) -> Duration {
127
Duration::from_secs(count)
128
}
129
130
#[test]
131
fn active_until_the_idle_threshold() {
132
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));
136
}
137
138
#[test]
139
fn without_any_input_the_user_is_inactive() {
140
assert!(!is_active(None, Instant::now(), IDLE_AFTER));
141
assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);
142
}
143
144
#[test]
145
fn only_a_change_of_state_is_reported() {
146
let last_input = Some(Instant::now());
147
let at = |offset: u64| last_input.unwrap() + seconds(offset);
148
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));
153
}
154
155
#[test]
156
fn system_input_counts_when_newer_than_app_input() {
157
let now = Instant::now() + seconds(1000);
158
let app_input = Some(now - seconds(900));
159
assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));
160
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);
161
assert_eq!(latest_input(app_input, None, now), app_input);
162
assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));
163
assert_eq!(latest_input(None, None, now), None);
164
}
165
166
#[test]
167
fn touch_sets_and_moves_the_last_input_forward() {
168
let input = UserInput::new();
169
assert_eq!(input.last_input(), None);
170
input.touch();
171
let first = input.last_input().unwrap();
172
std::thread::sleep(Duration::from_millis(5));
173
input.touch();
174
assert!(input.last_input().unwrap() > first);
175
}
176
}
@@ -0,0 +1,176 @@1
use std::sync::Arc;2
use std::sync::atomic::{AtomicU64, Ordering};3
use std::time::{Duration, Instant};4
5
use gpui_kit::{DispatchPhase, IntoElement, KeyDownEvent, MouseDownEvent, MouseMoveEvent, ScrollWheelEvent, canvas};6
use tokio::sync::watch;7
8
pub const IDLE_AFTER: Duration = Duration::from_secs(5 * 60);9
const SAMPLE_INTERVAL: Duration = Duration::from_secs(15);10
11
pub struct UserInput {12
origin: Instant,13
last_input_millis: AtomicU64,14
}15
16
const NO_INPUT: u64 = u64::MAX;17
18
impl UserInput {19
pub fn new() -> Arc<Self> {20
Arc::new(UserInput {21
origin: Instant::now(),22
last_input_millis: AtomicU64::new(NO_INPUT),23
})24
}25
26
pub fn touch(&self) {27
let elapsed = self.origin.elapsed().as_millis() as u64;28
self.last_input_millis.store(elapsed, Ordering::Relaxed);29
}30
31
fn last_input(&self) -> Option<Instant> {32
match self.last_input_millis.load(Ordering::Relaxed) {33
NO_INPUT => None,34
millis => Some(self.origin + Duration::from_millis(millis)),35
}36
}37
}38
39
pub fn input_probe(input: Arc<UserInput>) -> impl IntoElement {40
canvas(41
|_, _, _| {},42
move |_, _, window, _| {43
let moved = input.clone();44
window.on_mouse_event(move |_: &MouseMoveEvent, phase, _, _| {45
if phase == DispatchPhase::Capture {46
moved.touch();47
}48
});49
let pressed = input.clone();50
window.on_mouse_event(move |_: &MouseDownEvent, phase, _, _| {51
if phase == DispatchPhase::Capture {52
pressed.touch();53
}54
});55
let scrolled = input.clone();56
window.on_mouse_event(move |_: &ScrollWheelEvent, phase, _, _| {57
if phase == DispatchPhase::Capture {58
scrolled.touch();59
}60
});61
let typed = input.clone();62
window.on_key_event(move |_: &KeyDownEvent, phase, _, _| {63
if phase == DispatchPhase::Capture {64
typed.touch();65
}66
});67
},68
)69
}70
71
pub fn latest_input(app_input: Option<Instant>, system_idle: Option<Duration>, now: Instant) -> Option<Instant> {72
let system_input = system_idle.and_then(|idle| now.checked_sub(idle));73
app_input.max(system_input)74
}75
76
pub fn is_active(last_input: Option<Instant>, now: Instant, idle_after: Duration) -> bool {77
last_input.is_some_and(|last_input| now.saturating_duration_since(last_input) < idle_after)78
}79
80
pub fn activity_change(previous: bool, last_input: Option<Instant>, now: Instant, idle_after: Duration) -> Option<bool> {81
let current = is_active(last_input, now, idle_after);82
(current != previous).then_some(current)83
}84
85
pub fn track(input: Arc<UserInput>) -> watch::Receiver<bool> {86
let (sender, receiver) = watch::channel(false);87
crate::runtime::handle().spawn(async move {88
let mut interval = tokio::time::interval(SAMPLE_INTERVAL);89
loop {90
interval.tick().await;91
let now = Instant::now();92
let last_input = latest_input(input.last_input(), system_idle(), now);93
let previous = *sender.borrow();94
if let Some(current) = activity_change(previous, last_input, now, IDLE_AFTER) {95
sender.send_replace(current);96
}97
}98
});99
receiver100
}101
102
#[cfg(windows)]103
fn system_idle() -> Option<Duration> {104
use windows::Win32::System::SystemInformation::GetTickCount;105
use windows::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};106
107
let mut info = LASTINPUTINFO {108
cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32,109
dwTime: 0,110
};111
unsafe { GetLastInputInfo(&mut info) }.as_bool().then(|| {112
let idle_millis = unsafe { GetTickCount() }.wrapping_sub(info.dwTime);113
Duration::from_millis(u64::from(idle_millis))114
})115
}116
117
#[cfg(not(windows))]118
fn system_idle() -> Option<Duration> {119
None120
}121
122
#[cfg(test)]123
mod tests {124
use super::*;125
126
fn seconds(count: u64) -> Duration {127
Duration::from_secs(count)128
}129
130
#[test]131
fn active_until_the_idle_threshold() {132
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));136
}137
138
#[test]139
fn without_any_input_the_user_is_inactive() {140
assert!(!is_active(None, Instant::now(), IDLE_AFTER));141
assert_eq!(activity_change(false, None, Instant::now(), IDLE_AFTER), None);142
}143
144
#[test]145
fn only_a_change_of_state_is_reported() {146
let last_input = Some(Instant::now());147
let at = |offset: u64| last_input.unwrap() + seconds(offset);148
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));153
}154
155
#[test]156
fn system_input_counts_when_newer_than_app_input() {157
let now = Instant::now() + seconds(1000);158
let app_input = Some(now - seconds(900));159
assert_eq!(latest_input(app_input, Some(seconds(20)), now), Some(now - seconds(20)));160
assert_eq!(latest_input(app_input, Some(seconds(2000)), now), app_input);161
assert_eq!(latest_input(app_input, None, now), app_input);162
assert_eq!(latest_input(None, Some(seconds(20)), now), Some(now - seconds(20)));163
assert_eq!(latest_input(None, None, now), None);164
}165
166
#[test]167
fn touch_sets_and_moves_the_last_input_forward() {168
let input = UserInput::new();169
assert_eq!(input.last_input(), None);170
input.touch();171
let first = input.last_input().unwrap();172
std::thread::sleep(Duration::from_millis(5));173
input.touch();174
assert!(input.last_input().unwrap() > first);175
}176
}@@ -18,7 +18,7 @@ use crate::theme;
18
18
19
19
const AVATAR_SIZE: f32 = 32.;
20
20
const KIND_MARKER_SIZE: f32 = 16.;
21
const BUTTON_SIZE: f32 = 28.;
21
const BUTTON_SIZE: f32 = 32.;
22
22
const MARK_READ_SIZE: f32 = 20.;
23
23
const FILTER_KEY: &str = "activity_filter";
24
24
@@ -92,7 +92,7 @@ impl ActivityPanel {
92
92
format!("activity-filter-{}", filter.label()).into(),
93
93
))
94
94
.h(px(24.))
95
.px(px(10.))
95
.px(px(12.))
96
96
.flex()
97
97
.items_center()
98
98
.rounded_full()
@@ -115,13 +115,11 @@ impl ActivityPanel {
115
115
});
116
116
v_flex()
117
117
.flex_none()
118
.pl(px(16.))
119
.pr(px(12.))
120
.pt(px(12.))
121
.pb(px(8.))
122
.gap(px(8.))
123
118
.child(
124
119
h_flex()
120
.h(px(52.))
121
.pl(px(16.))
122
.pr(px(12.))
125
123
.gap(px(4.))
126
124
.items_center()
127
125
.child(
@@ -139,7 +137,7 @@ impl ActivityPanel {
139
137
.h(px(BUTTON_SIZE))
140
138
.flex()
141
139
.items_center()
142
.rounded(px(6.))
140
.rounded(px(8.))
143
141
.cursor_pointer()
144
142
.text_size(px(12.))
145
143
.text_color(theme::accent_text())
@@ -158,7 +156,7 @@ impl ActivityPanel {
158
156
.flex_none()
159
157
.items_center()
160
158
.justify_center()
161
.rounded(px(6.))
159
.rounded(px(8.))
162
160
.cursor_pointer()
163
161
.hover(|button| button.bg(theme::surface_raised()))
164
162
.child(icon(IconName::Settings, 16., theme::text_muted()))
@@ -167,7 +165,13 @@ impl ActivityPanel {
167
165
})),
168
166
),
169
167
)
170
.child(h_flex().gap(px(6.)).children(pills))
168
.child(
169
h_flex()
170
.px(px(16.))
171
.pb(px(12.))
172
.gap(px(6.))
173
.children(pills),
174
)
171
175
}
172
176
173
177
fn row(
@@ -197,7 +201,7 @@ impl ActivityPanel {
197
201
.mx(px(6.))
198
202
.px(px(10.))
199
203
.py(px(8.))
200
.gap(px(10.))
204
.gap(px(12.))
201
205
.items_start()
202
206
.rounded(px(8.))
203
207
.cursor_pointer()
@@ -292,8 +296,6 @@ fn status_slot(
292
296
.items_center()
293
297
.justify_center()
294
298
.rounded(px(6.))
295
.border_1()
296
.border_color(theme::border_strong())
297
299
.bg(theme::surface_raised())
298
300
.cursor_pointer()
299
301
.child(icon(IconName::Check, 12., theme::text()))
@@ -18,7 +18,7 @@ use crate::theme;18
18
19
const AVATAR_SIZE: f32 = 32.;19
const AVATAR_SIZE: f32 = 32.;20
const KIND_MARKER_SIZE: f32 = 16.;20
const KIND_MARKER_SIZE: f32 = 16.;21
const BUTTON_SIZE: f32 = 28.;21
const BUTTON_SIZE: f32 = 32.;22
const MARK_READ_SIZE: f32 = 20.;22
const MARK_READ_SIZE: f32 = 20.;23
const FILTER_KEY: &str = "activity_filter";23
const FILTER_KEY: &str = "activity_filter";24
24
@@ -92,7 +92,7 @@ impl ActivityPanel {92
format!("activity-filter-{}", filter.label()).into(),92
format!("activity-filter-{}", filter.label()).into(),93
))93
))94
.h(px(24.))94
.h(px(24.))95
.px(px(10.))95
.px(px(12.))96
.flex()96
.flex()97
.items_center()97
.items_center()98
.rounded_full()98
.rounded_full()@@ -115,13 +115,11 @@ impl ActivityPanel {115
});115
});116
v_flex()116
v_flex()117
.flex_none()117
.flex_none()118
.pl(px(16.))119
.pr(px(12.))120
.pt(px(12.))121
.pb(px(8.))122
.gap(px(8.))123
.child(118
.child(124
h_flex()119
h_flex()120
.h(px(52.))121
.pl(px(16.))122
.pr(px(12.))125
.gap(px(4.))123
.gap(px(4.))126
.items_center()124
.items_center()127
.child(125
.child(@@ -139,7 +137,7 @@ impl ActivityPanel {139
.h(px(BUTTON_SIZE))137
.h(px(BUTTON_SIZE))140
.flex()138
.flex()141
.items_center()139
.items_center()142
.rounded(px(6.))140
.rounded(px(8.))143
.cursor_pointer()141
.cursor_pointer()144
.text_size(px(12.))142
.text_size(px(12.))145
.text_color(theme::accent_text())143
.text_color(theme::accent_text())@@ -158,7 +156,7 @@ impl ActivityPanel {158
.flex_none()156
.flex_none()159
.items_center()157
.items_center()160
.justify_center()158
.justify_center()161
.rounded(px(6.))159
.rounded(px(8.))162
.cursor_pointer()160
.cursor_pointer()163
.hover(|button| button.bg(theme::surface_raised()))161
.hover(|button| button.bg(theme::surface_raised()))164
.child(icon(IconName::Settings, 16., theme::text_muted()))162
.child(icon(IconName::Settings, 16., theme::text_muted()))@@ -167,7 +165,13 @@ impl ActivityPanel {167
})),165
})),168
),166
),169
)167
)170
.child(h_flex().gap(px(6.)).children(pills))168
.child(169
h_flex()170
.px(px(16.))171
.pb(px(12.))172
.gap(px(6.))173
.children(pills),174
)171
}175
}172
176
173
fn row(177
fn row(@@ -197,7 +201,7 @@ impl ActivityPanel {197
.mx(px(6.))201
.mx(px(6.))198
.px(px(10.))202
.px(px(10.))199
.py(px(8.))203
.py(px(8.))200
.gap(px(10.))204
.gap(px(12.))201
.items_start()205
.items_start()202
.rounded(px(8.))206
.rounded(px(8.))203
.cursor_pointer()207
.cursor_pointer()@@ -292,8 +296,6 @@ fn status_slot(292
.items_center()296
.items_center()293
.justify_center()297
.justify_center()294
.rounded(px(6.))298
.rounded(px(6.))295
.border_1()296
.border_color(theme::border_strong())297
.bg(theme::surface_raised())299
.bg(theme::surface_raised())298
.cursor_pointer()300
.cursor_pointer()299
.child(icon(IconName::Check, 12., theme::text()))301
.child(icon(IconName::Check, 12., theme::text()))@@ -26,9 +26,10 @@ const PREVIEW_HEIGHT: f32 = 120.;
26
26
const PREVIEW_GAP: f32 = 4.;
27
27
const PREVIEW_RADIUS: f32 = 10.;
28
28
const CHIP_WIDTH: f32 = 220.;
29
const CHIP_HEIGHT: f32 = 48.;
29
const CHIP_HEIGHT: f32 = 52.;
30
30
const CHIP_BADGE_SIZE: f32 = 30.;
31
31
const REMOVE_SIZE: f32 = 18.;
32
const CHIP_REMOVE_SIZE: f32 = 28.;
32
33
const TRAY_GAP: f32 = 8.;
33
34
const PROGRESS_HEIGHT: f32 = 2.;
34
35
@@ -780,15 +781,15 @@ type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);
780
781
fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {
781
782
div()
782
783
.id(ElementId::Name(format!("attachment-remove-{id}").into()))
783
.size(px(REMOVE_SIZE))
784
.size(px(CHIP_REMOVE_SIZE))
784
785
.flex_none()
785
786
.flex()
786
787
.items_center()
787
788
.justify_center()
788
.rounded_full()
789
.rounded(px(7.))
789
790
.cursor_pointer()
790
.hover(|button| button.bg(theme::row_hover()))
791
.child(icon(IconName::Close, 10., theme::text_muted()))
791
.hover(|button| button.bg(theme::popup_hover()))
792
.child(icon(IconName::Close, 14., theme::text_muted()))
792
793
.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))
793
794
}
794
795
@@ -904,10 +905,10 @@ fn chip<T: 'static>(
904
905
.w(px(CHIP_WIDTH))
905
906
.h(px(CHIP_HEIGHT))
906
907
.flex_none()
907
.gap(px(9.))
908
.px(px(9.))
908
.gap(px(12.))
909
.px(px(12.))
909
910
.items_center()
910
.rounded(px(8.))
911
.rounded(px(10.))
911
912
.overflow_hidden()
912
913
.bg(theme::popup_hover())
913
914
.border_1()
@@ -985,8 +986,8 @@ pub fn render_tray<T: 'static>(
985
986
.w_full()
986
987
.flex_wrap()
987
988
.gap(px(TRAY_GAP))
988
.px(px(12.))
989
.pt(px(10.))
989
.px(px(8.))
990
.pt(px(8.))
990
991
.pb(px(2.))
991
992
.children(elements),
992
993
)
@@ -26,9 +26,10 @@ const PREVIEW_HEIGHT: f32 = 120.;26
const PREVIEW_GAP: f32 = 4.;26
const PREVIEW_GAP: f32 = 4.;27
const PREVIEW_RADIUS: f32 = 10.;27
const PREVIEW_RADIUS: f32 = 10.;28
const CHIP_WIDTH: f32 = 220.;28
const CHIP_WIDTH: f32 = 220.;29
const CHIP_HEIGHT: f32 = 48.;29
const CHIP_HEIGHT: f32 = 52.;30
const CHIP_BADGE_SIZE: f32 = 30.;30
const CHIP_BADGE_SIZE: f32 = 30.;31
const REMOVE_SIZE: f32 = 18.;31
const REMOVE_SIZE: f32 = 18.;32
const CHIP_REMOVE_SIZE: f32 = 28.;32
const TRAY_GAP: f32 = 8.;33
const TRAY_GAP: f32 = 8.;33
const PROGRESS_HEIGHT: f32 = 2.;34
const PROGRESS_HEIGHT: f32 = 2.;34
35
@@ -780,15 +781,15 @@ type ItemAction<T> = fn(&mut T, u64, &mut Window, &mut Context<T>);780
fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {781
fn remove_button<T: 'static>(id: u64, remove: ItemAction<T>, cx: &mut Context<T>) -> Stateful<Div> {781
div()782
div()782
.id(ElementId::Name(format!("attachment-remove-{id}").into()))783
.id(ElementId::Name(format!("attachment-remove-{id}").into()))783
.size(px(REMOVE_SIZE))784
.size(px(CHIP_REMOVE_SIZE))784
.flex_none()785
.flex_none()785
.flex()786
.flex()786
.items_center()787
.items_center()787
.justify_center()788
.justify_center()788
.rounded_full()789
.rounded(px(7.))789
.cursor_pointer()790
.cursor_pointer()790
.hover(|button| button.bg(theme::row_hover()))791
.hover(|button| button.bg(theme::popup_hover()))791
.child(icon(IconName::Close, 10., theme::text_muted()))792
.child(icon(IconName::Close, 14., theme::text_muted()))792
.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))793
.on_click(cx.listener(move |this, _, window, cx| remove(this, id, window, cx)))793
}794
}794
795
@@ -904,10 +905,10 @@ fn chip<T: 'static>(904
.w(px(CHIP_WIDTH))905
.w(px(CHIP_WIDTH))905
.h(px(CHIP_HEIGHT))906
.h(px(CHIP_HEIGHT))906
.flex_none()907
.flex_none()907
.gap(px(9.))908
.gap(px(12.))908
.px(px(9.))909
.px(px(12.))909
.items_center()910
.items_center()910
.rounded(px(8.))911
.rounded(px(10.))911
.overflow_hidden()912
.overflow_hidden()912
.bg(theme::popup_hover())913
.bg(theme::popup_hover())913
.border_1()914
.border_1()@@ -985,8 +986,8 @@ pub fn render_tray<T: 'static>(985
.w_full()986
.w_full()986
.flex_wrap()987
.flex_wrap()987
.gap(px(TRAY_GAP))988
.gap(px(TRAY_GAP))988
.px(px(12.))989
.px(px(8.))989
.pt(px(10.))990
.pt(px(8.))990
.pb(px(2.))991
.pb(px(2.))991
.children(elements),992
.children(elements),992
)993
)@@ -29,6 +29,7 @@ const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";
29
29
const LOCAL_IMAGE_SUFFIX: &str = "/$value";
30
30
31
31
pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;
32
pub type ImageOpen = Rc<dyn Fn(&str, &mut App)>;
32
33
33
34
#[derive(Clone)]
34
35
pub struct FileActions {
@@ -68,7 +69,12 @@ pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {
68
69
fit_image_within(declared_size(image).or(loaded), max_height)
69
70
}
70
71
71
fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {
72
fn image_view(
73
image: &ImageRef,
74
id: String,
75
directory: &Directory,
76
open_image: Option<&ImageOpen>,
77
) -> AnyElement {
72
78
let (width, height) = image_size(image, directory);
73
79
let frame = div()
74
80
.id(ElementId::Name(id.into()))
@@ -97,6 +103,7 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement
97
103
.into_any_element();
98
104
};
99
105
let path = entry.path.clone();
106
let (url, open_image) = (image.url.clone(), open_image.cloned());
100
107
frame
101
108
.cursor_pointer()
102
109
.child(
@@ -105,7 +112,10 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement
105
112
.rounded(px(IMAGE_RADIUS))
106
113
.object_fit(ObjectFit::Cover),
107
114
)
108
.on_click(move |_, _, cx| cx.open_with_system(&path))
115
.on_click(move |_, _, cx| match &open_image {
116
Some(open_image) => open_image(&url, cx),
117
None => cx.open_with_system(&path),
118
})
109
119
.into_any_element()
110
120
}
111
121
@@ -239,11 +249,11 @@ fn file_view(
239
249
.overflow_hidden()
240
250
.w(px(FILE_CARD_WIDTH))
241
251
.max_w(relative(1.))
242
.gap(px(10.))
252
.gap(px(12.))
243
253
.px(px(8.))
244
.py(px(7.))
254
.py(px(8.))
245
255
.items_center()
246
.rounded(px(9.))
256
.rounded(px(10.))
247
257
.bg(theme::surface())
248
258
.cursor_pointer()
249
259
.hover(|card| card.bg(theme::row_hover()))
@@ -324,6 +334,7 @@ pub fn message_body(
324
334
id: &str,
325
335
own: bool,
326
336
directory: &Directory,
337
open_image: Option<&ImageOpen>,
327
338
cx: &App,
328
339
) -> Vec<AnyElement> {
329
340
if !blocks
@@ -351,6 +362,7 @@ pub fn message_body(
351
362
&images[position],
352
363
format!("{id}-image-{position}"),
353
364
directory,
365
open_image,
354
366
)),
355
367
Some(Placement::Local(position)) => elements.push(local_image_view(
356
368
&local_images[position],
@@ -371,6 +383,7 @@ pub fn attachments_view(
371
383
id: &str,
372
384
directory: &Directory,
373
385
file_actions: Option<&FileActions>,
386
open_image: Option<&ImageOpen>,
374
387
) -> Option<Div> {
375
388
let placed = placements(blocks, images, local_images.len());
376
389
let unplaced_images: Vec<(usize, &ImageRef)> = images
@@ -392,7 +405,7 @@ pub fn attachments_view(
392
405
.items_start()
393
406
.children(
394
407
unplaced_images.into_iter().map(|(index, image)| {
395
image_view(image, format!("{id}-image-{index}"), directory)
408
image_view(image, format!("{id}-image-{index}"), directory, open_image)
396
409
}),
397
410
)
398
411
.children(
@@ -29,6 +29,7 @@ const LOCAL_IMAGE_PREFIX: &str = "../hostedContents/";29
const LOCAL_IMAGE_SUFFIX: &str = "/$value";29
const LOCAL_IMAGE_SUFFIX: &str = "/$value";30
30
31
pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;31
pub type FileActivate = Rc<dyn Fn(usize, &mut App)>;32
pub type ImageOpen = Rc<dyn Fn(&str, &mut App)>;32
33
33
#[derive(Clone)]34
#[derive(Clone)]34
pub struct FileActions {35
pub struct FileActions {@@ -68,7 +69,12 @@ pub fn image_size(image: &ImageRef, directory: &Directory) -> (f32, f32) {68
fit_image_within(declared_size(image).or(loaded), max_height)69
fit_image_within(declared_size(image).or(loaded), max_height)69
}70
}70
71
71
fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement {72
fn image_view(73
image: &ImageRef,74
id: String,75
directory: &Directory,76
open_image: Option<&ImageOpen>,77
) -> AnyElement {72
let (width, height) = image_size(image, directory);78
let (width, height) = image_size(image, directory);73
let frame = div()79
let frame = div()74
.id(ElementId::Name(id.into()))80
.id(ElementId::Name(id.into()))@@ -97,6 +103,7 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement97
.into_any_element();103
.into_any_element();98
};104
};99
let path = entry.path.clone();105
let path = entry.path.clone();106
let (url, open_image) = (image.url.clone(), open_image.cloned());100
frame107
frame101
.cursor_pointer()108
.cursor_pointer()102
.child(109
.child(@@ -105,7 +112,10 @@ fn image_view(image: &ImageRef, id: String, directory: &Directory) -> AnyElement105
.rounded(px(IMAGE_RADIUS))112
.rounded(px(IMAGE_RADIUS))106
.object_fit(ObjectFit::Cover),113
.object_fit(ObjectFit::Cover),107
)114
)108
.on_click(move |_, _, cx| cx.open_with_system(&path))115
.on_click(move |_, _, cx| match &open_image {116
Some(open_image) => open_image(&url, cx),117
None => cx.open_with_system(&path),118
})109
.into_any_element()119
.into_any_element()110
}120
}111
121
@@ -239,11 +249,11 @@ fn file_view(239
.overflow_hidden()249
.overflow_hidden()240
.w(px(FILE_CARD_WIDTH))250
.w(px(FILE_CARD_WIDTH))241
.max_w(relative(1.))251
.max_w(relative(1.))242
.gap(px(10.))252
.gap(px(12.))243
.px(px(8.))253
.px(px(8.))244
.py(px(7.))254
.py(px(8.))245
.items_center()255
.items_center()246
.rounded(px(9.))256
.rounded(px(10.))247
.bg(theme::surface())257
.bg(theme::surface())248
.cursor_pointer()258
.cursor_pointer()249
.hover(|card| card.bg(theme::row_hover()))259
.hover(|card| card.bg(theme::row_hover()))@@ -324,6 +334,7 @@ pub fn message_body(324
id: &str,334
id: &str,325
own: bool,335
own: bool,326
directory: &Directory,336
directory: &Directory,337
open_image: Option<&ImageOpen>,327
cx: &App,338
cx: &App,328
) -> Vec<AnyElement> {339
) -> Vec<AnyElement> {329
if !blocks340
if !blocks@@ -351,6 +362,7 @@ pub fn message_body(351
&images[position],362
&images[position],352
format!("{id}-image-{position}"),363
format!("{id}-image-{position}"),353
directory,364
directory,365
open_image,354
)),366
)),355
Some(Placement::Local(position)) => elements.push(local_image_view(367
Some(Placement::Local(position)) => elements.push(local_image_view(356
&local_images[position],368
&local_images[position],@@ -371,6 +383,7 @@ pub fn attachments_view(371
id: &str,383
id: &str,372
directory: &Directory,384
directory: &Directory,373
file_actions: Option<&FileActions>,385
file_actions: Option<&FileActions>,386
open_image: Option<&ImageOpen>,374
) -> Option<Div> {387
) -> Option<Div> {375
let placed = placements(blocks, images, local_images.len());388
let placed = placements(blocks, images, local_images.len());376
let unplaced_images: Vec<(usize, &ImageRef)> = images389
let unplaced_images: Vec<(usize, &ImageRef)> = images@@ -392,7 +405,7 @@ pub fn attachments_view(392
.items_start()405
.items_start()393
.children(406
.children(394
unplaced_images.into_iter().map(|(index, image)| {407
unplaced_images.into_iter().map(|(index, image)| {395
image_view(image, format!("{id}-image-{index}"), directory)408
image_view(image, format!("{id}-image-{index}"), directory, open_image)396
}),409
}),397
)410
)398
.children(411
.children(@@ -78,7 +78,7 @@ pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
78
78
.min_h_0()
79
79
.items_center()
80
80
.justify_center()
81
.gap(px(14.))
81
.gap(px(12.))
82
82
.child(
83
83
div()
84
84
.size(px(96.))
@@ -113,7 +113,7 @@ pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<Any
113
113
.h_full()
114
114
.items_center()
115
115
.justify_center()
116
.gap(px(14.))
116
.gap(px(12.))
117
117
.rounded(px(STAGE_RADIUS))
118
118
.bg(hsla(0., 0., 0.04, 1.))
119
119
.text_color(theme::white())
@@ -179,12 +179,9 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
179
179
.max_w(relative(1.))
180
180
.p(px(20.))
181
181
.gap(px(12.))
182
.rounded(px(12.))
183
.bg(theme::background())
184
.border_1()
185
.border_color(theme::border_strong())
182
.rounded(px(10.))
183
.bg(theme::popup())
186
184
.text_color(theme::text())
187
.shadow_lg()
188
185
.occlude()
189
186
.child(
190
187
h_flex()
@@ -78,7 +78,7 @@ pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen78
.min_h_0()78
.min_h_0()79
.items_center()79
.items_center()80
.justify_center()80
.justify_center()81
.gap(px(14.))81
.gap(px(12.))82
.child(82
.child(83
div()83
div()84
.size(px(96.))84
.size(px(96.))@@ -113,7 +113,7 @@ pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<Any113
.h_full()113
.h_full()114
.items_center()114
.items_center()115
.justify_center()115
.justify_center()116
.gap(px(14.))116
.gap(px(12.))117
.rounded(px(STAGE_RADIUS))117
.rounded(px(STAGE_RADIUS))118
.bg(hsla(0., 0., 0.04, 1.))118
.bg(hsla(0., 0., 0.04, 1.))119
.text_color(theme::white())119
.text_color(theme::white())@@ -179,12 +179,9 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE179
.max_w(relative(1.))179
.max_w(relative(1.))180
.p(px(20.))180
.p(px(20.))181
.gap(px(12.))181
.gap(px(12.))182
.rounded(px(12.))182
.rounded(px(10.))183
.bg(theme::background())183
.bg(theme::popup())184
.border_1()185
.border_color(theme::border_strong())186
.text_color(theme::text())184
.text_color(theme::text())187
.shadow_lg()188
.occlude()185
.occlude()189
.child(186
.child(190
h_flex()187
h_flex()@@ -25,14 +25,14 @@ const PILL_HEIGHT: f32 = 26.;
25
25
const LOBBY_LIST_WIDTH: f32 = 340.;
26
26
const LOBBY_NAME_LIMIT: usize = 28;
27
27
const CAPTION_WIDTH: f32 = 720.;
28
const CAPTION_BOTTOM: f32 = 2. * 18. + CONTROL_SIZE + 1. + 16.;
28
const CAPTION_BOTTOM: f32 = 2. * 16. + CONTROL_SIZE + 16.;
29
29
const CAPTION_FADE_SECONDS: f32 = 1.;
30
30
const CAPTION_BACKGROUND: f32 = 0.72;
31
31
const FOCUS_RADIUS: f32 = 12.;
32
32
const FOCUS_AVATAR: f32 = 140.;
33
33
const CHIP_HEIGHT: f32 = 24.;
34
34
const MORE_SIZE: f32 = 28.;
35
const SMALL_CONTROL: f32 = 28.;
35
const CAMERA_MENU_WIDTH: f32 = 28.;
36
36
const NAME_LIMIT: usize = 32;
37
37
38
38
fn dark_text() -> Hsla {
@@ -40,7 +40,7 @@ fn dark_text() -> Hsla {
40
40
}
41
41
42
42
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 { (transparent_black(), dark_text()) };
43
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (dark_text().opacity(0.12), dark_text()) };
44
44
div()
45
45
.id(id)
46
46
.h(px(PILL_HEIGHT))
@@ -49,8 +49,6 @@ pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool)
49
49
.flex_none()
50
50
.items_center()
51
51
.rounded_full()
52
.border_1()
53
.border_color(dark_text())
54
52
.bg(background)
55
53
.text_color(foreground)
56
54
.text_size(px(BANNER_TEXT))
@@ -200,7 +198,7 @@ pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mr
200
198
201
199
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {
202
200
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());
203
div().absolute().top(px(10.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(
201
div().absolute().top(px(6.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(
204
202
Button::new(SharedString::from(format!("call-tile-more-{mri}")))
205
203
.icon(IconName::Ellipsis)
206
204
.ghost()
@@ -323,17 +321,17 @@ pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds
323
321
Button::new("call-camera-menu")
324
322
.ghost()
325
323
.p_0()
326
.size(px(SMALL_CONTROL))
324
.w(px(CAMERA_MENU_WIDTH))
325
.h(px(super::call_view::CONTROL_SIZE))
327
326
.rounded_full()
328
327
.child(
329
328
div()
330
329
.id("call-camera-menu-face")
331
.size(px(SMALL_CONTROL))
330
.w(px(CAMERA_MENU_WIDTH))
331
.h(px(super::call_view::CONTROL_SIZE))
332
332
.flex()
333
333
.items_center()
334
334
.justify_center()
335
.rounded_full()
336
.bg(theme::surface_raised())
337
335
.child(icon(IconName::ChevronUp, 16., theme::text())),
338
336
)
339
337
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))
@@ -375,7 +373,7 @@ pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {
375
373
.max_w_full()
376
374
.gap(px(4.))
377
375
.px(px(16.))
378
.py(px(10.))
376
.py(px(8.))
379
377
.rounded(px(10.))
380
378
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))
381
379
.text_color(theme::white())
@@ -454,8 +452,8 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu
454
452
.child(
455
453
h_flex()
456
454
.absolute()
457
.top(px(14.))
458
.left(px(14.))
455
.top(px(12.))
456
.left(px(12.))
459
457
.gap(px(6.))
460
458
.when(focus.spotlight, |chips| chips.child(spotlight_chip()))
461
459
.when(focus.pinned, |chips| chips.child(pin_chip())),
@@ -463,10 +461,10 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu
463
461
.child(
464
462
h_flex()
465
463
.absolute()
466
.left(px(14.))
467
.bottom(px(14.))
464
.left(px(12.))
465
.bottom(px(12.))
468
466
.gap(px(8.))
469
.px(px(10.))
467
.px(px(8.))
470
468
.py(px(4.))
471
469
.rounded(px(6.))
472
470
.bg(hsla(0., 0., 0., 0.6))
@@ -500,7 +498,7 @@ pub fn captions_hint_chip(model: &CallModel) -> Option<AnyElement> {
500
498
.justify_center()
501
499
.child(
502
500
div()
503
.px(px(14.))
501
.px(px(12.))
504
502
.py(px(6.))
505
503
.rounded_full()
506
504
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))
@@ -25,14 +25,14 @@ const PILL_HEIGHT: f32 = 26.;25
const LOBBY_LIST_WIDTH: f32 = 340.;25
const LOBBY_LIST_WIDTH: f32 = 340.;26
const LOBBY_NAME_LIMIT: usize = 28;26
const LOBBY_NAME_LIMIT: usize = 28;27
const CAPTION_WIDTH: f32 = 720.;27
const CAPTION_WIDTH: f32 = 720.;28
const CAPTION_BOTTOM: f32 = 2. * 18. + CONTROL_SIZE + 1. + 16.;28
const CAPTION_BOTTOM: f32 = 2. * 16. + CONTROL_SIZE + 16.;29
const CAPTION_FADE_SECONDS: f32 = 1.;29
const CAPTION_FADE_SECONDS: f32 = 1.;30
const CAPTION_BACKGROUND: f32 = 0.72;30
const CAPTION_BACKGROUND: f32 = 0.72;31
const FOCUS_RADIUS: f32 = 12.;31
const FOCUS_RADIUS: f32 = 12.;32
const FOCUS_AVATAR: f32 = 140.;32
const FOCUS_AVATAR: f32 = 140.;33
const CHIP_HEIGHT: f32 = 24.;33
const CHIP_HEIGHT: f32 = 24.;34
const MORE_SIZE: f32 = 28.;34
const MORE_SIZE: f32 = 28.;35
const SMALL_CONTROL: f32 = 28.;35
const CAMERA_MENU_WIDTH: f32 = 28.;36
const NAME_LIMIT: usize = 32;36
const NAME_LIMIT: usize = 32;37
37
38
fn dark_text() -> Hsla {38
fn dark_text() -> Hsla {@@ -40,7 +40,7 @@ fn dark_text() -> Hsla {40
}40
}41
41
42
pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool) -> Stateful<Div> {42
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 { (transparent_black(), dark_text()) };43
let (background, foreground) = if filled { (dark_text(), theme::white()) } else { (dark_text().opacity(0.12), dark_text()) };44
div()44
div()45
.id(id)45
.id(id)46
.h(px(PILL_HEIGHT))46
.h(px(PILL_HEIGHT))@@ -49,8 +49,6 @@ pub(super) fn pill(id: impl Into<ElementId>, label: &'static str, filled: bool)49
.flex_none()49
.flex_none()50
.items_center()50
.items_center()51
.rounded_full()51
.rounded_full()52
.border_1()53
.border_color(dark_text())54
.bg(background)52
.bg(background)55
.text_color(foreground)53
.text_color(foreground)56
.text_size(px(BANNER_TEXT))54
.text_size(px(BANNER_TEXT))@@ -200,7 +198,7 @@ pub fn tile_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel, mr200
198
201
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {199
fn more_overlay(app: &Entity<AppState>, model: &CallModel, mri: &str, name: &str, own: bool, group: SharedString) -> Div {202
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());200
let (app, model, mri_owned, name) = (app.clone(), model.clone(), mri.to_owned(), name.to_owned());203
div().absolute().top(px(10.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(201
div().absolute().top(px(6.)).right(px(38.)).opacity(0.).group_hover(group, |more| more.opacity(1.)).child(204
Button::new(SharedString::from(format!("call-tile-more-{mri}")))202
Button::new(SharedString::from(format!("call-tile-more-{mri}")))205
.icon(IconName::Ellipsis)203
.icon(IconName::Ellipsis)206
.ghost()204
.ghost()@@ -323,17 +321,17 @@ pub fn camera_menu_button(app: &Entity<AppState>, model: &CallModel, backgrounds323
Button::new("call-camera-menu")321
Button::new("call-camera-menu")324
.ghost()322
.ghost()325
.p_0()323
.p_0()326
.size(px(SMALL_CONTROL))324
.w(px(CAMERA_MENU_WIDTH))325
.h(px(super::call_view::CONTROL_SIZE))327
.rounded_full()326
.rounded_full()328
.child(327
.child(329
div()328
div()330
.id("call-camera-menu-face")329
.id("call-camera-menu-face")331
.size(px(SMALL_CONTROL))330
.w(px(CAMERA_MENU_WIDTH))331
.h(px(super::call_view::CONTROL_SIZE))332
.flex()332
.flex()333
.items_center()333
.items_center()334
.justify_center()334
.justify_center()335
.rounded_full()336
.bg(theme::surface_raised())337
.child(icon(IconName::ChevronUp, 16., theme::text())),335
.child(icon(IconName::ChevronUp, 16., theme::text())),338
)336
)339
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))337
.dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| camera_menu(popup, &app, &model, &backgrounds))@@ -375,7 +373,7 @@ pub fn captions_overlay(model: &CallModel, now: Instant) -> Option<AnyElement> {375
.max_w_full()373
.max_w_full()376
.gap(px(4.))374
.gap(px(4.))377
.px(px(16.))375
.px(px(16.))378
.py(px(10.))376
.py(px(8.))379
.rounded(px(10.))377
.rounded(px(10.))380
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))378
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))381
.text_color(theme::white())379
.text_color(theme::white())@@ -454,8 +452,8 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu454
.child(452
.child(455
h_flex()453
h_flex()456
.absolute()454
.absolute()457
.top(px(14.))455
.top(px(12.))458
.left(px(14.))456
.left(px(12.))459
.gap(px(6.))457
.gap(px(6.))460
.when(focus.spotlight, |chips| chips.child(spotlight_chip()))458
.when(focus.spotlight, |chips| chips.child(spotlight_chip()))461
.when(focus.pinned, |chips| chips.child(pin_chip())),459
.when(focus.pinned, |chips| chips.child(pin_chip())),@@ -463,10 +461,10 @@ pub fn render_focus_stage(app: &Entity<AppState>, state: &AppState, focus: &Focu463
.child(461
.child(464
h_flex()462
h_flex()465
.absolute()463
.absolute()466
.left(px(14.))464
.left(px(12.))467
.bottom(px(14.))465
.bottom(px(12.))468
.gap(px(8.))466
.gap(px(8.))469
.px(px(10.))467
.px(px(8.))470
.py(px(4.))468
.py(px(4.))471
.rounded(px(6.))469
.rounded(px(6.))472
.bg(hsla(0., 0., 0., 0.6))470
.bg(hsla(0., 0., 0., 0.6))@@ -500,7 +498,7 @@ pub fn captions_hint_chip(model: &CallModel) -> Option<AnyElement> {500
.justify_center()498
.justify_center()501
.child(499
.child(502
div()500
div()503
.px(px(14.))501
.px(px(12.))504
.py(px(6.))502
.py(px(6.))505
.rounded_full()503
.rounded_full()506
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))504
.bg(hsla(0., 0., 0., CAPTION_BACKGROUND))@@ -20,7 +20,8 @@ use super::call_extras::{BackgroundMenu, consent_overlay, consult_banner, hold_p
20
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};
21
21
use super::call_stage::render_stage;
22
22
use super::conversation::ConversationView;
23
use super::widgets::{count_badge, icon, symbol};
23
use super::shell::ISLAND_GAP;
24
use super::widgets::{count_badge, icon};
24
25
use crate::app_state::AppState;
25
26
use crate::call::TileSize;
26
27
use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};
@@ -45,7 +46,7 @@ const STRIP_TILE: TileSize = TileSize {
45
46
height: 131.,
46
47
avatar: 56.,
47
48
};
48
const STRIP_GAP: f32 = 10.;
49
const STRIP_GAP: f32 = 12.;
49
50
const STRIP_VISIBLE: f32 = 4.;
50
51
const TILE_RADIUS: f32 = 12.;
51
52
const NAME_PLATE_BACKGROUND: f32 = 0.6;
@@ -58,7 +59,6 @@ const MAX_WINDOW_ITEMS: usize = 12;
58
59
pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
59
60
pub const CHAT_PANEL_WIDTH: f32 = 320.;
60
61
const CHAT_HEADER_HEIGHT: f32 = 48.;
61
const HAND_GLYPH: &str = "\u{270B}";
62
62
const REACTION_RISE: f32 = 24.;
63
63
const REACTION_FADE_FROM: f32 = 0.75;
64
64
const REACTION_CELL: f32 = 40.;
@@ -98,15 +98,13 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
98
98
div()
99
99
.absolute()
100
100
.right(px(12.))
101
.bottom(px(34.))
101
.bottom(px(32.))
102
102
.size(px(36.))
103
103
.flex()
104
104
.items_center()
105
105
.justify_center()
106
106
.rounded_full()
107
.bg(theme::surface_raised())
108
.border_1()
109
.border_color(theme::border_strong())
107
.bg(theme::popup())
110
108
.text_size(px(20.))
111
109
.child(reaction_glyph(reaction))
112
110
.with_animation(
@@ -114,7 +112,7 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
114
112
Animation::new(REACTION_SHOWN),
115
113
|chip, delta| {
116
114
let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);
117
chip.bottom(px(34. + REACTION_RISE * delta)).opacity(1. - fade)
115
chip.bottom(px(32. + REACTION_RISE * delta)).opacity(1. - fade)
118
116
},
119
117
)
120
118
.into_any_element()
@@ -124,8 +122,8 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
124
122
let badges = (extras.hand.is_some() || extras.spotlight || extras.pinned).then(|| {
125
123
h_flex()
126
124
.absolute()
127
.top(px(10.))
128
.left(px(10.))
125
.top(px(8.))
126
.left(px(8.))
129
127
.gap(px(6.))
130
128
.children(extras.hand.map(|position| hand_badge(position, extras.own)))
131
129
.when(extras.spotlight, |row| row.child(spotlight_chip()))
@@ -183,8 +181,8 @@ fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {
183
181
fn mute_badge() -> Div {
184
182
div()
185
183
.absolute()
186
.top(px(10.))
187
.right(px(10.))
184
.top(px(8.))
185
.right(px(8.))
188
186
.size(px(24.))
189
187
.flex()
190
188
.items_center()
@@ -202,7 +200,7 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo
202
200
.flex_none()
203
201
.overflow_hidden()
204
202
.rounded(px(TILE_RADIUS))
205
.bg(theme::surface())
203
.bg(theme::row_hover())
206
204
.border_2()
207
205
.border_color(if speaking { theme::green() } else { transparent_black() })
208
206
.child(
@@ -219,7 +217,7 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo
219
217
.max_w(px(size.width - 24.))
220
218
.truncate()
221
219
.px(px(8.))
222
.py(px(3.))
220
.py(px(4.))
223
221
.rounded(px(6.))
224
222
.bg(hsla(0., 0., 0., NAME_PLATE_BACKGROUND))
225
223
.text_size(px(12.))
@@ -242,8 +240,8 @@ fn tile(
242
240
) -> Div {
243
241
let badge = div()
244
242
.absolute()
245
.top(px(10.))
246
.right(px(10.))
243
.top(px(8.))
244
.right(px(8.))
247
245
.size(px(24.))
248
246
.flex()
249
247
.items_center()
@@ -259,9 +257,7 @@ fn tile(
259
257
.justify_center()
260
258
.gap(px(12.))
261
259
.rounded(px(12.))
262
.bg(theme::surface())
263
.border_1()
264
.border_color(theme::border())
260
.bg(theme::row_hover())
265
261
.child(speaking_ring(avatar, speaking))
266
262
.child(
267
263
v_flex()
@@ -289,9 +285,7 @@ fn overflow_tile(size: TileSize, hidden: usize) -> Div {
289
285
.items_center()
290
286
.justify_center()
291
287
.rounded(px(12.))
292
.bg(theme::surface())
293
.border_1()
294
.border_color(theme::border())
288
.bg(theme::row_hover())
295
289
.child(
296
290
div()
297
291
.text_size(px(size.avatar * 0.5))
@@ -491,8 +485,7 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
491
485
.flex()
492
486
.items_center()
493
487
.rounded_full()
494
.border_1()
495
.border_color(theme::on_accent())
488
.bg(theme::on_accent().opacity(0.2))
496
489
.cursor_pointer()
497
490
.hover(|button| button.opacity(0.9))
498
491
.child(if sound { "Computer sound on" } else { "Computer sound off" })
@@ -536,7 +529,8 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>
536
529
fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
537
530
let raised = model.own_hand.is_some();
538
531
let background = if raised { theme::accent() } else { theme::surface_raised() };
539
let button = control_shell("call-hand", background).child(div().text_size(px(CONTROL_ICON)).child(HAND_GLYPH));
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));
540
534
let tooltip = if raised { "Lower hand" } else { "Raise hand" };
541
535
let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));
542
536
if !model.can_react() {
@@ -551,7 +545,7 @@ fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
551
545
552
546
fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
553
547
let face = control_shell("call-reactions-face", theme::surface_raised())
554
.child(symbol("mood", CONTROL_ICON, theme::text()));
548
.child(icon(IconName::FaceSlightlySmiling, CONTROL_ICON, theme::text()));
555
549
if !model.can_react() {
556
550
return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();
557
551
}
@@ -804,8 +798,6 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
804
798
.px(px(20.))
805
799
.gap(px(12.))
806
800
.items_center()
807
.border_b_1()
808
.border_color(theme::border())
809
801
.child(icon(IconName::Phone, 18., theme::accent_text()))
810
802
.child(
811
803
div()
@@ -838,14 +830,12 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
838
830
let controls = h_flex()
839
831
.w_full()
840
832
.flex_none()
841
.py(px(18.))
833
.py(px(16.))
842
834
.gap(px(12.))
843
835
.items_center()
844
836
.justify_center()
845
.border_t_1()
846
.border_color(theme::border())
847
837
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))
848
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))
838
.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))))
849
839
.child(share_button(app, model, state.call_share_sound))
850
840
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))
851
841
.child(devices_button(app, model))
@@ -859,6 +849,8 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
859
849
.flex_1()
860
850
.min_w_0()
861
851
.h_full()
852
.rounded(px(10.))
853
.overflow_hidden()
862
854
.bg(theme::surface())
863
855
.child(header)
864
856
.children(lobby_banner(app, model))
@@ -899,6 +891,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E
899
891
.flex_1()
900
892
.min_w_0()
901
893
.h_full()
894
.gap(px(ISLAND_GAP))
902
895
.child(column)
903
896
.children(chat.map(|chat| chat_panel(app, chat)))
904
897
.into_any_element(),
@@ -912,18 +905,18 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem
912
905
.w(px(CHAT_PANEL_WIDTH))
913
906
.h_full()
914
907
.flex_none()
915
.border_l_1()
916
.border_color(theme::border())
908
.rounded(px(10.))
909
.overflow_hidden()
910
.bg(theme::surface())
917
911
.child(
918
912
h_flex()
919
913
.w_full()
920
914
.h(px(CHAT_HEADER_HEIGHT))
921
915
.flex_none()
922
.px(px(16.))
916
.pl(px(20.))
917
.pr(px(12.))
923
918
.items_center()
924
919
.justify_between()
925
.border_b_1()
926
.border_color(theme::border())
927
920
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))
928
921
.child(
929
922
div()
@@ -932,11 +925,11 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem
932
925
.flex()
933
926
.items_center()
934
927
.justify_center()
935
.rounded_full()
928
.rounded(px(7.))
936
929
.cursor_pointer()
937
930
.hover(|button| button.bg(theme::row_hover()))
938
931
.tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))
939
.child(icon(IconName::Close, 16., theme::text_muted()))
932
.child(icon(IconName::Close, 14., theme::text_muted()))
940
933
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),
941
934
),
942
935
)
@@ -20,7 +20,8 @@ use super::call_extras::{BackgroundMenu, consent_overlay, consult_banner, hold_p20
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
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};21
use super::call_stage::render_stage;21
use super::call_stage::render_stage;22
use super::conversation::ConversationView;22
use super::conversation::ConversationView;23
use super::widgets::{count_badge, icon, symbol};23
use super::shell::ISLAND_GAP;24
use super::widgets::{count_badge, icon};24
use crate::app_state::AppState;25
use crate::app_state::AppState;25
use crate::call::TileSize;26
use crate::call::TileSize;26
use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};27
use crate::call::{CHAT_OPEN_TILES, CallKind, CallModel, GridLayout, MAX_TILES, Tile, TileState, grid_layout, tile_size};@@ -45,7 +46,7 @@ const STRIP_TILE: TileSize = TileSize {45
height: 131.,46
height: 131.,46
avatar: 56.,47
avatar: 56.,47
};48
};48
const STRIP_GAP: f32 = 10.;49
const STRIP_GAP: f32 = 12.;49
const STRIP_VISIBLE: f32 = 4.;50
const STRIP_VISIBLE: f32 = 4.;50
const TILE_RADIUS: f32 = 12.;51
const TILE_RADIUS: f32 = 12.;51
const NAME_PLATE_BACKGROUND: f32 = 0.6;52
const NAME_PLATE_BACKGROUND: f32 = 0.6;@@ -58,7 +59,6 @@ const MAX_WINDOW_ITEMS: usize = 12;58
pub const LOBBY_TEXT: &str = "Waiting in the lobby...";59
pub const LOBBY_TEXT: &str = "Waiting in the lobby...";59
pub const CHAT_PANEL_WIDTH: f32 = 320.;60
pub const CHAT_PANEL_WIDTH: f32 = 320.;60
const CHAT_HEADER_HEIGHT: f32 = 48.;61
const CHAT_HEADER_HEIGHT: f32 = 48.;61
const HAND_GLYPH: &str = "\u{270B}";62
const REACTION_RISE: f32 = 24.;62
const REACTION_RISE: f32 = 24.;63
const REACTION_FADE_FROM: f32 = 0.75;63
const REACTION_FADE_FROM: f32 = 0.75;64
const REACTION_CELL: f32 = 40.;64
const REACTION_CELL: f32 = 40.;@@ -98,15 +98,13 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {98
div()98
div()99
.absolute()99
.absolute()100
.right(px(12.))100
.right(px(12.))101
.bottom(px(34.))101
.bottom(px(32.))102
.size(px(36.))102
.size(px(36.))103
.flex()103
.flex()104
.items_center()104
.items_center()105
.justify_center()105
.justify_center()106
.rounded_full()106
.rounded_full()107
.bg(theme::surface_raised())107
.bg(theme::popup())108
.border_1()109
.border_color(theme::border_strong())110
.text_size(px(20.))108
.text_size(px(20.))111
.child(reaction_glyph(reaction))109
.child(reaction_glyph(reaction))112
.with_animation(110
.with_animation(@@ -114,7 +112,7 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {114
Animation::new(REACTION_SHOWN),112
Animation::new(REACTION_SHOWN),115
|chip, delta| {113
|chip, delta| {116
let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);114
let fade = ((delta - REACTION_FADE_FROM) / (1. - REACTION_FADE_FROM)).clamp(0., 1.);117
chip.bottom(px(34. + REACTION_RISE * delta)).opacity(1. - fade)115
chip.bottom(px(32. + REACTION_RISE * delta)).opacity(1. - fade)118
},116
},119
)117
)120
.into_any_element()118
.into_any_element()@@ -124,8 +122,8 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {124
let badges = (extras.hand.is_some() || extras.spotlight || extras.pinned).then(|| {122
let badges = (extras.hand.is_some() || extras.spotlight || extras.pinned).then(|| {125
h_flex()123
h_flex()126
.absolute()124
.absolute()127
.top(px(10.))125
.top(px(8.))128
.left(px(10.))126
.left(px(8.))129
.gap(px(6.))127
.gap(px(6.))130
.children(extras.hand.map(|position| hand_badge(position, extras.own)))128
.children(extras.hand.map(|position| hand_badge(position, extras.own)))131
.when(extras.spotlight, |row| row.child(spotlight_chip()))129
.when(extras.spotlight, |row| row.child(spotlight_chip()))@@ -183,8 +181,8 @@ fn speaking_ring(avatar: AnyElement, speaking: bool) -> Div {183
fn mute_badge() -> Div {181
fn mute_badge() -> Div {184
div()182
div()185
.absolute()183
.absolute()186
.top(px(10.))184
.top(px(8.))187
.right(px(10.))185
.right(px(8.))188
.size(px(24.))186
.size(px(24.))189
.flex()187
.flex()190
.items_center()188
.items_center()@@ -202,7 +200,7 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo202
.flex_none()200
.flex_none()203
.overflow_hidden()201
.overflow_hidden()204
.rounded(px(TILE_RADIUS))202
.rounded(px(TILE_RADIUS))205
.bg(theme::surface())203
.bg(theme::row_hover())206
.border_2()204
.border_2()207
.border_color(if speaking { theme::green() } else { transparent_black() })205
.border_color(if speaking { theme::green() } else { transparent_black() })208
.child(206
.child(@@ -219,7 +217,7 @@ fn video_tile(size: TileSize, image: Arc<RenderImage>, name: &str, speaking: boo219
.max_w(px(size.width - 24.))217
.max_w(px(size.width - 24.))220
.truncate()218
.truncate()221
.px(px(8.))219
.px(px(8.))222
.py(px(3.))220
.py(px(4.))223
.rounded(px(6.))221
.rounded(px(6.))224
.bg(hsla(0., 0., 0., NAME_PLATE_BACKGROUND))222
.bg(hsla(0., 0., 0., NAME_PLATE_BACKGROUND))225
.text_size(px(12.))223
.text_size(px(12.))@@ -242,8 +240,8 @@ fn tile(242
) -> Div {240
) -> Div {243
let badge = div()241
let badge = div()244
.absolute()242
.absolute()245
.top(px(10.))243
.top(px(8.))246
.right(px(10.))244
.right(px(8.))247
.size(px(24.))245
.size(px(24.))248
.flex()246
.flex()249
.items_center()247
.items_center()@@ -259,9 +257,7 @@ fn tile(259
.justify_center()257
.justify_center()260
.gap(px(12.))258
.gap(px(12.))261
.rounded(px(12.))259
.rounded(px(12.))262
.bg(theme::surface())260
.bg(theme::row_hover())263
.border_1()264
.border_color(theme::border())265
.child(speaking_ring(avatar, speaking))261
.child(speaking_ring(avatar, speaking))266
.child(262
.child(267
v_flex()263
v_flex()@@ -289,9 +285,7 @@ fn overflow_tile(size: TileSize, hidden: usize) -> Div {289
.items_center()285
.items_center()290
.justify_center()286
.justify_center()291
.rounded(px(12.))287
.rounded(px(12.))292
.bg(theme::surface())288
.bg(theme::row_hover())293
.border_1()294
.border_color(theme::border())295
.child(289
.child(296
div()290
div()297
.text_size(px(size.avatar * 0.5))291
.text_size(px(size.avatar * 0.5))@@ -491,8 +485,7 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt491
.flex()485
.flex()492
.items_center()486
.items_center()493
.rounded_full()487
.rounded_full()494
.border_1()488
.bg(theme::on_accent().opacity(0.2))495
.border_color(theme::on_accent())496
.cursor_pointer()489
.cursor_pointer()497
.hover(|button| button.opacity(0.9))490
.hover(|button| button.opacity(0.9))498
.child(if sound { "Computer sound on" } else { "Computer sound off" })491
.child(if sound { "Computer sound on" } else { "Computer sound off" })@@ -536,7 +529,8 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>536
fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {529
fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {537
let raised = model.own_hand.is_some();530
let raised = model.own_hand.is_some();538
let background = if raised { theme::accent() } else { theme::surface_raised() };531
let background = if raised { theme::accent() } else { theme::surface_raised() };539
let button = control_shell("call-hand", background).child(div().text_size(px(CONTROL_ICON)).child(HAND_GLYPH));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));540
let tooltip = if raised { "Lower hand" } else { "Raise hand" };534
let tooltip = if raised { "Lower hand" } else { "Raise hand" };541
let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));535
let button = button.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx));542
if !model.can_react() {536
if !model.can_react() {@@ -551,7 +545,7 @@ fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {551
545
552
fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {546
fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {553
let face = control_shell("call-reactions-face", theme::surface_raised())547
let face = control_shell("call-reactions-face", theme::surface_raised())554
.child(symbol("mood", CONTROL_ICON, theme::text()));548
.child(icon(IconName::FaceSlightlySmiling, CONTROL_ICON, theme::text()));555
if !model.can_react() {549
if !model.can_react() {556
return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();550
return face.opacity(DISABLED_OPACITY).cursor_default().into_any_element();557
}551
}@@ -804,8 +798,6 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E804
.px(px(20.))798
.px(px(20.))805
.gap(px(12.))799
.gap(px(12.))806
.items_center()800
.items_center()807
.border_b_1()808
.border_color(theme::border())809
.child(icon(IconName::Phone, 18., theme::accent_text()))801
.child(icon(IconName::Phone, 18., theme::accent_text()))810
.child(802
.child(811
div()803
div()@@ -838,14 +830,12 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E838
let controls = h_flex()830
let controls = h_flex()839
.w_full()831
.w_full()840
.flex_none()832
.flex_none()841
.py(px(18.))833
.py(px(16.))842
.gap(px(12.))834
.gap(px(12.))843
.items_center()835
.items_center()844
.justify_center()836
.justify_center()845
.border_t_1()846
.border_color(theme::border())847
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))837
.child(mute_button(app, model, "call-mute", CONTROL_SIZE))848
.child(h_flex().gap(px(2.)).items_center().child(camera_button(app, model)).children(camera_menu_button(app, model, BackgroundMenu::of(state))))838
.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))))849
.child(share_button(app, model, state.call_share_sound))839
.child(share_button(app, model, state.call_share_sound))850
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))840
.when(model.has_reaction_controls(), |row| row.child(hand_button(app, model)).child(reactions_button(app, model)))851
.child(devices_button(app, model))841
.child(devices_button(app, model))@@ -859,6 +849,8 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E859
.flex_1()849
.flex_1()860
.min_w_0()850
.min_w_0()861
.h_full()851
.h_full()852
.rounded(px(10.))853
.overflow_hidden()862
.bg(theme::surface())854
.bg(theme::surface())863
.child(header)855
.child(header)864
.children(lobby_banner(app, model))856
.children(lobby_banner(app, model))@@ -899,6 +891,7 @@ pub fn render_call_view(app: &Entity<AppState>, state: &AppState, chat: Option<E899
.flex_1()891
.flex_1()900
.min_w_0()892
.min_w_0()901
.h_full()893
.h_full()894
.gap(px(ISLAND_GAP))902
.child(column)895
.child(column)903
.children(chat.map(|chat| chat_panel(app, chat)))896
.children(chat.map(|chat| chat_panel(app, chat)))904
.into_any_element(),897
.into_any_element(),@@ -912,18 +905,18 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem912
.w(px(CHAT_PANEL_WIDTH))905
.w(px(CHAT_PANEL_WIDTH))913
.h_full()906
.h_full()914
.flex_none()907
.flex_none()915
.border_l_1()908
.rounded(px(10.))916
.border_color(theme::border())909
.overflow_hidden()910
.bg(theme::surface())917
.child(911
.child(918
h_flex()912
h_flex()919
.w_full()913
.w_full()920
.h(px(CHAT_HEADER_HEIGHT))914
.h(px(CHAT_HEADER_HEIGHT))921
.flex_none()915
.flex_none()922
.px(px(16.))916
.pl(px(20.))917
.pr(px(12.))923
.items_center()918
.items_center()924
.justify_between()919
.justify_between()925
.border_b_1()926
.border_color(theme::border())927
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))920
.child(div().text_size(px(15.)).font_weight(FontWeight::SEMIBOLD).child("Chat"))928
.child(921
.child(929
div()922
div()@@ -932,11 +925,11 @@ fn chat_panel(app: &Entity<AppState>, chat: Entity<ConversationView>) -> AnyElem932
.flex()925
.flex()933
.items_center()926
.items_center()934
.justify_center()927
.justify_center()935
.rounded_full()928
.rounded(px(7.))936
.cursor_pointer()929
.cursor_pointer()937
.hover(|button| button.bg(theme::row_hover()))930
.hover(|button| button.bg(theme::row_hover()))938
.tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))931
.tooltip(|window, cx| Tooltip::new("Close the chat").build(window, cx))939
.child(icon(IconName::Close, 16., theme::text_muted()))932
.child(icon(IconName::Close, 14., theme::text_muted()))940
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),933
.on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx))),941
),934
),942
)935
)@@ -61,7 +61,7 @@ fn call_row(
61
61
.mx(px(6.))
62
62
.h(px(CALL_ROW_HEIGHT))
63
63
.px(px(10.))
64
.gap(px(10.))
64
.gap(px(12.))
65
65
.items_center()
66
66
.rounded(px(8.))
67
67
.cursor_pointer()
@@ -153,7 +153,7 @@ fn join_button(id: &'static str, label: &'static str, primary: bool) -> Stateful
153
153
div()
154
154
.id(id)
155
155
.h(px(28.))
156
.px(px(10.))
156
.px(px(12.))
157
157
.flex()
158
158
.items_center()
159
159
.rounded(px(7.))
@@ -172,7 +172,7 @@ fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoEl
172
172
let paste_state = state.clone();
173
173
h_flex()
174
174
.w_full()
175
.px(px(12.))
175
.px(px(16.))
176
176
.pb(px(8.))
177
177
.gap(px(8.))
178
178
.flex_wrap()
@@ -246,7 +246,7 @@ fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyE
246
246
.mx(px(6.))
247
247
.h(px(AGENDA_ROW_HEIGHT))
248
248
.px(px(10.))
249
.gap(px(10.))
249
.gap(px(12.))
250
250
.items_center()
251
251
.rounded(px(8.))
252
252
.cursor_pointer()
@@ -61,7 +61,7 @@ fn call_row(61
.mx(px(6.))61
.mx(px(6.))62
.h(px(CALL_ROW_HEIGHT))62
.h(px(CALL_ROW_HEIGHT))63
.px(px(10.))63
.px(px(10.))64
.gap(px(10.))64
.gap(px(12.))65
.items_center()65
.items_center()66
.rounded(px(8.))66
.rounded(px(8.))67
.cursor_pointer()67
.cursor_pointer()@@ -153,7 +153,7 @@ fn join_button(id: &'static str, label: &'static str, primary: bool) -> Stateful153
div()153
div()154
.id(id)154
.id(id)155
.h(px(28.))155
.h(px(28.))156
.px(px(10.))156
.px(px(12.))157
.flex()157
.flex()158
.items_center()158
.items_center()159
.rounded(px(7.))159
.rounded(px(7.))@@ -172,7 +172,7 @@ fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoEl172
let paste_state = state.clone();172
let paste_state = state.clone();173
h_flex()173
h_flex()174
.w_full()174
.w_full()175
.px(px(12.))175
.px(px(16.))176
.pb(px(8.))176
.pb(px(8.))177
.gap(px(8.))177
.gap(px(8.))178
.flex_wrap()178
.flex_wrap()@@ -246,7 +246,7 @@ fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyE246
.mx(px(6.))246
.mx(px(6.))247
.h(px(AGENDA_ROW_HEIGHT))247
.h(px(AGENDA_ROW_HEIGHT))248
.px(px(10.))248
.px(px(10.))249
.gap(px(10.))249
.gap(px(12.))250
.items_center()250
.items_center()251
.rounded(px(8.))251
.rounded(px(8.))252
.cursor_pointer()252
.cursor_pointer()@@ -17,7 +17,7 @@ const TAB_HEIGHT: f32 = 28.;
17
17
const TAB_GAP: f32 = 4.;
18
18
const TAB_PADDING: f32 = 12.;
19
19
const TAB_TEXT_SIZE: f32 = 12.5;
20
const BAR_PADDING: f32 = 16.;
20
const BAR_PADDING: f32 = 20.;
21
21
const CHAR_WIDTH: f32 = 6.5;
22
22
const ARROW_WIDTH: f32 = 14.;
23
23
const OVERFLOW_WIDTH: f32 = 44.;
@@ -109,7 +109,7 @@ fn tab_label(
109
109
.h(px(TAB_HEIGHT))
110
110
.flex_none()
111
111
.items_center()
112
.gap(px(3.))
112
.gap(px(4.))
113
113
.px(px(TAB_PADDING))
114
114
.rounded(px(7.))
115
115
.cursor_pointer()
@@ -17,7 +17,7 @@ const TAB_HEIGHT: f32 = 28.;17
const TAB_GAP: f32 = 4.;17
const TAB_GAP: f32 = 4.;18
const TAB_PADDING: f32 = 12.;18
const TAB_PADDING: f32 = 12.;19
const TAB_TEXT_SIZE: f32 = 12.5;19
const TAB_TEXT_SIZE: f32 = 12.5;20
const BAR_PADDING: f32 = 16.;20
const BAR_PADDING: f32 = 20.;21
const CHAR_WIDTH: f32 = 6.5;21
const CHAR_WIDTH: f32 = 6.5;22
const ARROW_WIDTH: f32 = 14.;22
const ARROW_WIDTH: f32 = 14.;23
const OVERFLOW_WIDTH: f32 = 44.;23
const OVERFLOW_WIDTH: f32 = 44.;@@ -109,7 +109,7 @@ fn tab_label(109
.h(px(TAB_HEIGHT))109
.h(px(TAB_HEIGHT))110
.flex_none()110
.flex_none()111
.items_center()111
.items_center()112
.gap(px(3.))112
.gap(px(4.))113
.px(px(TAB_PADDING))113
.px(px(TAB_PADDING))114
.rounded(px(7.))114
.rounded(px(7.))115
.cursor_pointer()115
.cursor_pointer()@@ -2151,7 +2151,7 @@ impl Composer {
2151
2151
.mx(px(6.))
2152
2152
.px(px(6.))
2153
2153
.h(px(POPUP_ROW_HEIGHT))
2154
.gap(px(10.))
2154
.gap(px(8.))
2155
2155
.items_center()
2156
2156
.rounded(px(6.))
2157
2157
.cursor_pointer()
@@ -2309,11 +2309,9 @@ impl Composer {
2309
2309
.child("Formatted from Markdown")
2310
2310
.child(
2311
2311
div()
2312
.px(px(5.))
2313
.py(px(1.))
2312
.px(px(4.))
2313
.py(px(2.))
2314
2314
.rounded(px(4.))
2315
.border_1()
2316
.border_color(theme::border_strong())
2317
2315
.bg(theme::surface_raised())
2318
2316
.text_size(px(11.))
2319
2317
.text_color(theme::text())
@@ -2328,16 +2326,13 @@ impl Composer {
2328
2326
Some(
2329
2327
h_flex()
2330
2328
.w_full()
2331
.mb(px(6.))
2332
.gap(px(10.))
2329
.h(px(52.))
2330
.mb(px(8.))
2331
.gap(px(12.))
2333
2332
.items_center()
2334
.pl(px(10.))
2335
.pr(px(4.))
2336
.py(px(6.))
2337
.rounded(px(8.))
2338
.bg(theme::surface())
2339
.border_1()
2340
.border_color(theme::border())
2333
.px(px(12.))
2334
.rounded(px(10.))
2335
.bg(theme::row_hover())
2341
2336
.child(match edit.scheduled {
2342
2337
Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),
2343
2338
None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),
@@ -2371,11 +2366,12 @@ impl Composer {
2371
2366
.child(
2372
2367
div()
2373
2368
.id("edit-close")
2374
.size(px(24.))
2369
.size(px(28.))
2370
.flex_none()
2375
2371
.flex()
2376
2372
.items_center()
2377
2373
.justify_center()
2378
.rounded(px(6.))
2374
.rounded(px(7.))
2379
2375
.cursor_pointer()
2380
2376
.hover(|button| button.bg(theme::row_hover()))
2381
2377
.child(icon(IconName::Close, 14., theme::text_muted()))
@@ -2389,16 +2385,13 @@ impl Composer {
2389
2385
Some(
2390
2386
h_flex()
2391
2387
.w_full()
2392
.mb(px(6.))
2393
.gap(px(10.))
2388
.h(px(52.))
2389
.mb(px(8.))
2390
.gap(px(12.))
2394
2391
.items_center()
2395
.pl(px(10.))
2396
.pr(px(4.))
2397
.py(px(6.))
2398
.rounded(px(8.))
2399
.bg(theme::surface())
2400
.border_1()
2401
.border_color(theme::border())
2392
.px(px(12.))
2393
.rounded(px(10.))
2394
.bg(theme::row_hover())
2402
2395
.child(icon(IconName::Undo2, 14., theme::accent_text()))
2403
2396
.child(
2404
2397
v_flex()
@@ -2423,11 +2416,12 @@ impl Composer {
2423
2416
.child(
2424
2417
div()
2425
2418
.id("reply-close")
2426
.size(px(24.))
2419
.size(px(28.))
2420
.flex_none()
2427
2421
.flex()
2428
2422
.items_center()
2429
2423
.justify_center()
2430
.rounded(px(6.))
2424
.rounded(px(7.))
2431
2425
.cursor_pointer()
2432
2426
.hover(|button| button.bg(theme::row_hover()))
2433
2427
.child(icon(IconName::Close, 14., theme::text_muted()))
@@ -2572,7 +2566,7 @@ impl Render for Composer {
2572
2566
let (inset, top, bottom) = if self.inline {
2573
2567
(0., 0., 0.)
2574
2568
} else {
2575
(24., 8., 12.)
2569
(20., 8., 16.)
2576
2570
};
2577
2571
v_flex()
2578
2572
.w_full()
@@ -2151,7 +2151,7 @@ impl Composer {2151
.mx(px(6.))2151
.mx(px(6.))2152
.px(px(6.))2152
.px(px(6.))2153
.h(px(POPUP_ROW_HEIGHT))2153
.h(px(POPUP_ROW_HEIGHT))2154
.gap(px(10.))2154
.gap(px(8.))2155
.items_center()2155
.items_center()2156
.rounded(px(6.))2156
.rounded(px(6.))2157
.cursor_pointer()2157
.cursor_pointer()@@ -2309,11 +2309,9 @@ impl Composer {2309
.child("Formatted from Markdown")2309
.child("Formatted from Markdown")2310
.child(2310
.child(2311
div()2311
div()2312
.px(px(5.))2312
.px(px(4.))2313
.py(px(1.))2313
.py(px(2.))2314
.rounded(px(4.))2314
.rounded(px(4.))2315
.border_1()2316
.border_color(theme::border_strong())2317
.bg(theme::surface_raised())2315
.bg(theme::surface_raised())2318
.text_size(px(11.))2316
.text_size(px(11.))2319
.text_color(theme::text())2317
.text_color(theme::text())@@ -2328,16 +2326,13 @@ impl Composer {2328
Some(2326
Some(2329
h_flex()2327
h_flex()2330
.w_full()2328
.w_full()2331
.mb(px(6.))2329
.h(px(52.))2332
.gap(px(10.))2330
.mb(px(8.))2331
.gap(px(12.))2333
.items_center()2332
.items_center()2334
.pl(px(10.))2333
.px(px(12.))2335
.pr(px(4.))2334
.rounded(px(10.))2336
.py(px(6.))2335
.bg(theme::row_hover())2337
.rounded(px(8.))2338
.bg(theme::surface())2339
.border_1()2340
.border_color(theme::border())2341
.child(match edit.scheduled {2336
.child(match edit.scheduled {2342
Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),2337
Some(_) => symbol("schedule_send", 14., theme::accent_text()).into_any_element(),2343
None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),2338
None => icon(IconName::Pencil, 14., theme::accent_text()).into_any_element(),@@ -2371,11 +2366,12 @@ impl Composer {2371
.child(2366
.child(2372
div()2367
div()2373
.id("edit-close")2368
.id("edit-close")2374
.size(px(24.))2369
.size(px(28.))2370
.flex_none()2375
.flex()2371
.flex()2376
.items_center()2372
.items_center()2377
.justify_center()2373
.justify_center()2378
.rounded(px(6.))2374
.rounded(px(7.))2379
.cursor_pointer()2375
.cursor_pointer()2380
.hover(|button| button.bg(theme::row_hover()))2376
.hover(|button| button.bg(theme::row_hover()))2381
.child(icon(IconName::Close, 14., theme::text_muted()))2377
.child(icon(IconName::Close, 14., theme::text_muted()))@@ -2389,16 +2385,13 @@ impl Composer {2389
Some(2385
Some(2390
h_flex()2386
h_flex()2391
.w_full()2387
.w_full()2392
.mb(px(6.))2388
.h(px(52.))2393
.gap(px(10.))2389
.mb(px(8.))2390
.gap(px(12.))2394
.items_center()2391
.items_center()2395
.pl(px(10.))2392
.px(px(12.))2396
.pr(px(4.))2393
.rounded(px(10.))2397
.py(px(6.))2394
.bg(theme::row_hover())2398
.rounded(px(8.))2399
.bg(theme::surface())2400
.border_1()2401
.border_color(theme::border())2402
.child(icon(IconName::Undo2, 14., theme::accent_text()))2395
.child(icon(IconName::Undo2, 14., theme::accent_text()))2403
.child(2396
.child(2404
v_flex()2397
v_flex()@@ -2423,11 +2416,12 @@ impl Composer {2423
.child(2416
.child(2424
div()2417
div()2425
.id("reply-close")2418
.id("reply-close")2426
.size(px(24.))2419
.size(px(28.))2420
.flex_none()2427
.flex()2421
.flex()2428
.items_center()2422
.items_center()2429
.justify_center()2423
.justify_center()2430
.rounded(px(6.))2424
.rounded(px(7.))2431
.cursor_pointer()2425
.cursor_pointer()2432
.hover(|button| button.bg(theme::row_hover()))2426
.hover(|button| button.bg(theme::row_hover()))2433
.child(icon(IconName::Close, 14., theme::text_muted()))2427
.child(icon(IconName::Close, 14., theme::text_muted()))@@ -2572,7 +2566,7 @@ impl Render for Composer {2572
let (inset, top, bottom) = if self.inline {2566
let (inset, top, bottom) = if self.inline {2573
(0., 0., 0.)2567
(0., 0., 0.)2574
} else {2568
} else {2575
(24., 8., 12.)2569
(20., 8., 16.)2576
};2570
};2577
v_flex()2571
v_flex()2578
.w_full()2572
.w_full()@@ -32,7 +32,7 @@ use super::call_controls::header_call_controls;
32
32
use super::channel_tabs::ChannelPane;
33
33
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
34
34
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
35
use super::message_row::{render_message_row, render_skeleton_row};
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
38
use super::profile_card::opens_profile;
@@ -48,6 +48,7 @@ use crate::demo_library::DemoLibrary;
48
48
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};
49
49
use crate::embedded_web::EmbeddedWeb;
50
50
use crate::emoji;
51
use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
51
52
use crate::notice::short_error;
52
53
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
53
54
use crate::pending_rows::pending_row;
@@ -299,6 +300,25 @@ impl ConversationView {
299
300
}
300
301
}
301
302
303
fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {
304
let Some(current) = self.current.as_ref() else {
305
return;
306
};
307
let now = Local::now();
308
let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());
309
let Some(index) = position_of(&items, message_key, url) else {
310
return;
311
};
312
let request = ViewerRequest {
313
conversation_id: current.selection.conversation_id().to_owned(),
314
conversation_title: selection_title(&self.app.read(cx).sidebar, ¤t.selection),
315
items,
316
index,
317
};
318
self.app
319
.update(cx, |state, cx| state.request_image_viewer(request, cx));
320
}
321
302
322
fn activate_file(
303
323
&mut self,
304
324
conversation_id: &str,
@@ -565,6 +585,7 @@ impl ConversationView {
565
585
AppEvent::TaskDialog
566
586
| AppEvent::LocalPreviews
567
587
| AppEvent::Forward
588
| AppEvent::ImageViewer
568
589
| AppEvent::StatusMessage
569
590
| AppEvent::NotificationSettings
570
591
| AppEvent::Profile
@@ -702,10 +723,15 @@ impl ConversationView {
702
723
.map(|face| face.name.clone())
703
724
.collect::<Vec<_>>(),
704
725
);
726
let text_inset = match self.current.as_ref().map(|current| ¤t.mode) {
727
Some(ViewMode::Flat) => AVATAR_SIZE + AVATAR_GAP,
728
_ => 0.,
729
};
705
730
h_flex()
706
731
.h(px(TYPING_LINE_HEIGHT))
707
732
.flex_none()
708
.px(px(24.))
733
.pl(px(20. + text_inset))
734
.pr(px(20.))
709
735
.gap(px(6.))
710
736
.items_center()
711
737
.when(!faces.is_empty(), |line| {
@@ -2837,8 +2863,8 @@ impl ConversationView {
2837
2863
v_flex()
2838
2864
.items_center()
2839
2865
.gap(px(6.))
2840
.px(px(28.))
2841
.py(px(18.))
2866
.px(px(24.))
2867
.py(px(16.))
2842
2868
.rounded(px(12.))
2843
2869
.bg(black().opacity(0.55))
2844
2870
.child(symbol("upload", 28., theme::accent_text()))
@@ -2870,7 +2896,7 @@ impl ConversationView {
2870
2896
h_flex()
2871
2897
.w_full()
2872
2898
.flex_none()
2873
.px(px(24.))
2899
.px(px(20.))
2874
2900
.py(px(4.))
2875
2901
.gap(px(8.))
2876
2902
.items_center()
@@ -3047,6 +3073,7 @@ impl Render for ConversationView {
3047
3073
.w_full()
3048
3074
.min_w_0()
3049
3075
.h_full()
3076
.rounded(px(10.))
3050
3077
.bg(background)
3051
3078
.track_focus(&self.focus_handle);
3052
3079
let drafting = self.draft_active;
@@ -3156,7 +3183,7 @@ impl Render for ConversationView {
3156
3183
if let Some(notice) = &self.notice {
3157
3184
root = root.child(
3158
3185
h_flex()
3159
.px_4()
3186
.px(px(20.))
3160
3187
.py_1()
3161
3188
.gap(px(8.))
3162
3189
.items_center()
@@ -32,7 +32,7 @@ use super::call_controls::header_call_controls;32
use super::channel_tabs::ChannelPane;32
use super::channel_tabs::ChannelPane;33
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};33
use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};34
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};34
use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};35
use super::message_row::{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::profile_card::opens_profile;38
use super::profile_card::opens_profile;@@ -48,6 +48,7 @@ use crate::demo_library::DemoLibrary;48
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};48
use crate::downloads::{self, ClickAction, DownloadKey, Downloads, PartFile, RevealTarget};49
use crate::embedded_web::EmbeddedWeb;49
use crate::embedded_web::EmbeddedWeb;50
use crate::emoji;50
use crate::emoji;51
use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};51
use crate::notice::short_error;52
use crate::notice::short_error;52
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};53
use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};53
use crate::pending_rows::pending_row;54
use crate::pending_rows::pending_row;@@ -299,6 +300,25 @@ impl ConversationView {299
}300
}300
}301
}301
302
303
fn open_image_viewer(&mut self, message_key: &str, url: &str, cx: &mut Context<Self>) {304
let Some(current) = self.current.as_ref() else {305
return;306
};307
let now = Local::now();308
let items = collect_gallery(&self.rows.borrow(), now.date_naive(), now.offset().fix());309
let Some(index) = position_of(&items, message_key, url) else {310
return;311
};312
let request = ViewerRequest {313
conversation_id: current.selection.conversation_id().to_owned(),314
conversation_title: selection_title(&self.app.read(cx).sidebar, ¤t.selection),315
items,316
index,317
};318
self.app319
.update(cx, |state, cx| state.request_image_viewer(request, cx));320
}321
302
fn activate_file(322
fn activate_file(303
&mut self,323
&mut self,304
conversation_id: &str,324
conversation_id: &str,@@ -565,6 +585,7 @@ impl ConversationView {565
AppEvent::TaskDialog585
AppEvent::TaskDialog566
| AppEvent::LocalPreviews586
| AppEvent::LocalPreviews567
| AppEvent::Forward587
| AppEvent::Forward588
| AppEvent::ImageViewer568
| AppEvent::StatusMessage589
| AppEvent::StatusMessage569
| AppEvent::NotificationSettings590
| AppEvent::NotificationSettings570
| AppEvent::Profile591
| AppEvent::Profile@@ -702,10 +723,15 @@ impl ConversationView {702
.map(|face| face.name.clone())723
.map(|face| face.name.clone())703
.collect::<Vec<_>>(),724
.collect::<Vec<_>>(),704
);725
);726
let text_inset = match self.current.as_ref().map(|current| ¤t.mode) {727
Some(ViewMode::Flat) => AVATAR_SIZE + AVATAR_GAP,728
_ => 0.,729
};705
h_flex()730
h_flex()706
.h(px(TYPING_LINE_HEIGHT))731
.h(px(TYPING_LINE_HEIGHT))707
.flex_none()732
.flex_none()708
.px(px(24.))733
.pl(px(20. + text_inset))734
.pr(px(20.))709
.gap(px(6.))735
.gap(px(6.))710
.items_center()736
.items_center()711
.when(!faces.is_empty(), |line| {737
.when(!faces.is_empty(), |line| {@@ -2837,8 +2863,8 @@ impl ConversationView {2837
v_flex()2863
v_flex()2838
.items_center()2864
.items_center()2839
.gap(px(6.))2865
.gap(px(6.))2840
.px(px(28.))2866
.px(px(24.))2841
.py(px(18.))2867
.py(px(16.))2842
.rounded(px(12.))2868
.rounded(px(12.))2843
.bg(black().opacity(0.55))2869
.bg(black().opacity(0.55))2844
.child(symbol("upload", 28., theme::accent_text()))2870
.child(symbol("upload", 28., theme::accent_text()))@@ -2870,7 +2896,7 @@ impl ConversationView {2870
h_flex()2896
h_flex()2871
.w_full()2897
.w_full()2872
.flex_none()2898
.flex_none()2873
.px(px(24.))2899
.px(px(20.))2874
.py(px(4.))2900
.py(px(4.))2875
.gap(px(8.))2901
.gap(px(8.))2876
.items_center()2902
.items_center()@@ -3047,6 +3073,7 @@ impl Render for ConversationView {3047
.w_full()3073
.w_full()3048
.min_w_0()3074
.min_w_0()3049
.h_full()3075
.h_full()3076
.rounded(px(10.))3050
.bg(background)3077
.bg(background)3051
.track_focus(&self.focus_handle);3078
.track_focus(&self.focus_handle);3052
let drafting = self.draft_active;3079
let drafting = self.draft_active;@@ -3156,7 +3183,7 @@ impl Render for ConversationView {3156
if let Some(notice) = &self.notice {3183
if let Some(notice) = &self.notice {3157
root = root.child(3184
root = root.child(3158
h_flex()3185
h_flex()3159
.px_4()3186
.px(px(20.))3160
.py_1()3187
.py_1()3161
.gap(px(8.))3188
.gap(px(8.))3162
.items_center()3189
.items_center()@@ -230,9 +230,9 @@ impl ConversationView {
230
230
h_flex()
231
231
.w_full()
232
232
.flex_none()
233
.px(px(24.))
234
.pt(px(2.))
235
.pb(px(4.))
233
.px(px(20.))
234
.pt(px(12.))
235
.pb(px(12.))
236
236
.child(
237
237
h_flex()
238
238
.id("new-post")
@@ -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(cx.listener(|this, _, window, cx| {
251
this.open_new_post(window, cx)
252
}))
250
.on_click(
251
cx.listener(|this, _, window, cx| 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
);
@@ -264,7 +264,7 @@ impl ConversationView {
264
264
.focus_handle(cx)
265
265
.contains_focused(window, cx);
266
266
let subject = (!editing).then(|| {
267
div().w_full().px(px(24.)).pt(px(10.)).child(
267
div().w_full().px(px(20.)).pt(px(12.)).child(
268
268
div()
269
269
.w_full()
270
270
.h(px(36.))
@@ -296,8 +296,8 @@ impl ConversationView {
296
296
.child(
297
297
h_flex()
298
298
.w_full()
299
.px(px(24.))
300
.pb(px(10.))
299
.px(px(20.))
300
.pb(px(12.))
301
301
.justify_end()
302
302
.child(
303
303
Button::new("cancel-new-post")
@@ -230,9 +230,9 @@ impl ConversationView {230
h_flex()230
h_flex()231
.w_full()231
.w_full()232
.flex_none()232
.flex_none()233
.px(px(24.))233
.px(px(20.))234
.pt(px(2.))234
.pt(px(12.))235
.pb(px(4.))235
.pb(px(12.))236
.child(236
.child(237
h_flex()237
h_flex()238
.id("new-post")238
.id("new-post")@@ -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(cx.listener(|this, _, window, cx| {250
.on_click(251
this.open_new_post(window, cx)251
cx.listener(|this, _, window, cx| 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
);@@ -264,7 +264,7 @@ impl ConversationView {264
.focus_handle(cx)264
.focus_handle(cx)265
.contains_focused(window, cx);265
.contains_focused(window, cx);266
let subject = (!editing).then(|| {266
let subject = (!editing).then(|| {267
div().w_full().px(px(24.)).pt(px(10.)).child(267
div().w_full().px(px(20.)).pt(px(12.)).child(268
div()268
div()269
.w_full()269
.w_full()270
.h(px(36.))270
.h(px(36.))@@ -296,8 +296,8 @@ impl ConversationView {296
.child(296
.child(297
h_flex()297
h_flex()298
.w_full()298
.w_full()299
.px(px(24.))299
.px(px(20.))300
.pb(px(10.))300
.pb(px(12.))301
.justify_end()301
.justify_end()302
.child(302
.child(303
Button::new("cancel-new-post")303
Button::new("cancel-new-post")@@ -12,6 +12,7 @@ use crate::app_state::AppState;
12
12
use crate::rows::{Delivery, MessageRow, PostRow};
13
13
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
14
14
use crate::translation::TranslationLine;
15
use crate::views::attachments::ImageOpen;
15
16
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};
16
17
use crate::views::composer::Composer;
17
18
use crate::views::message_row::{DeliveryActions, RowActions};
@@ -193,6 +194,13 @@ impl RenderEnv {
193
194
.read(cx)
194
195
.file_actions(&message.key, &message.files, view.clone())
195
196
});
197
let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {
198
let (view, key) = (view.clone(), message.key.clone());
199
Rc::new(move |url: &str, cx: &mut App| {
200
view.update(cx, |this, cx| this.open_image_viewer(&key, url, cx))
201
.ok();
202
}) as ImageOpen
203
});
196
204
let bot = self.bot_identity(message, cx);
197
205
let translation = (is_real && !message.deleted)
198
206
.then(|| self.translation_actions(message))
@@ -222,6 +230,7 @@ impl RenderEnv {
222
230
react,
223
231
reaction_controls,
224
232
files,
233
open_image,
225
234
highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),
226
235
saved: self
227
236
.app
@@ -12,6 +12,7 @@ use crate::app_state::AppState;12
use crate::rows::{Delivery, MessageRow, PostRow};12
use crate::rows::{Delivery, MessageRow, PostRow};13
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;13
use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;14
use crate::translation::TranslationLine;14
use crate::translation::TranslationLine;15
use crate::views::attachments::ImageOpen;15
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};16
use crate::views::adaptive_card::{ensure_cards_inputs, request_card_refreshes};16
use crate::views::composer::Composer;17
use crate::views::composer::Composer;17
use crate::views::message_row::{DeliveryActions, RowActions};18
use crate::views::message_row::{DeliveryActions, RowActions};@@ -193,6 +194,13 @@ impl RenderEnv {193
.read(cx)194
.read(cx)194
.file_actions(&message.key, &message.files, view.clone())195
.file_actions(&message.key, &message.files, view.clone())195
});196
});197
let open_image = (is_real && !message.deleted && !message.images.is_empty()).then(|| {198
let (view, key) = (view.clone(), message.key.clone());199
Rc::new(move |url: &str, cx: &mut App| {200
view.update(cx, |this, cx| this.open_image_viewer(&key, url, cx))201
.ok();202
}) as ImageOpen203
});196
let bot = self.bot_identity(message, cx);204
let bot = self.bot_identity(message, cx);197
let translation = (is_real && !message.deleted)205
let translation = (is_real && !message.deleted)198
.then(|| self.translation_actions(message))206
.then(|| self.translation_actions(message))@@ -222,6 +230,7 @@ impl RenderEnv {222
react,230
react,223
reaction_controls,231
reaction_controls,224
files,232
files,233
open_image,225
highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),234
highlighted: self.highlighted.as_deref() == Some(message.key.as_str()),226
saved: self235
saved: self227
.app236
.app@@ -0,0 +1,1035 @@
1
use std::io::Cursor;
2
use std::path::{Path, PathBuf};
3
use std::sync::Arc;
4
use std::time::Duration;
5
6
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
7
use gpui_kit::prelude::FluentBuilder as _;
8
use gpui_kit::*;
9
10
use image::{Frame, ImageReader};
11
12
use super::avatar::person_avatar;
13
use super::widgets::symbol;
14
use crate::app_state::AppState;
15
use crate::downloads;
16
use crate::image_view_gallery::{GalleryItem, ViewerRequest};
17
use crate::theme;
18
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,
21
thumbnail_window, toggle_target, wheel_scale, zoom_at,
22
};
23
24
const HEADER_HEIGHT: f32 = 52.;
25
const FOOTER_HEIGHT: f32 = 120.;
26
const BUTTON_SIZE: f32 = 36.;
27
const BUTTON_RADIUS: f32 = 8.;
28
const BUTTON_ICON_SIZE: f32 = 20.;
29
const NAV_ICON_SIZE: f32 = 24.;
30
const ZOOM_LABEL_WIDTH: f32 = 52.;
31
const NAV_SIZE: f32 = 44.;
32
const NAV_MARGIN: f32 = 16.;
33
const AVATAR_SIZE: f32 = 32.;
34
const SIDE_PADDING: f32 = 16.;
35
const THUMBNAIL_SIZE: f32 = 48.;
36
const THUMBNAIL_GAP: f32 = 8.;
37
const THUMBNAIL_RADIUS: f32 = 6.;
38
const THUMBNAIL_BORDER: f32 = 2.;
39
const CAPTION_MAX_WIDTH: f32 = 720.;
40
const CAPTION_HEIGHT: f32 = 22.;
41
const STATUS_HEIGHT: f32 = 18.;
42
const STRIP_HEIGHT: f32 = THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER;
43
const WHEEL_LINE_HEIGHT: f32 = 20.;
44
const BACKDROP: u32 = 0x080809fc;
45
const DISABLED_OPACITY: f32 = 0.35;
46
const NOTICE_DURATION: Duration = Duration::from_secs(2);
47
48
pub enum ImageViewerEvent {
49
Close,
50
}
51
52
struct RotatedImage {
53
url: String,
54
quarter_turns: u8,
55
render: Arc<RenderImage>,
56
}
57
58
#[derive(Clone, Copy)]
59
struct Layout {
60
stage: Pair,
61
source: Pair,
62
fit: f32,
63
scale: f32,
64
pan: Pair,
65
}
66
67
pub struct ImageViewer {
68
app: Entity<AppState>,
69
conversation_id: String,
70
conversation_title: String,
71
items: Vec<GalleryItem>,
72
index: usize,
73
scale: Option<f32>,
74
pan: Pair,
75
quarter_turns: u8,
76
rotated: Option<RotatedImage>,
77
entered_fullscreen: bool,
78
drag_from: Option<Point<Pixels>>,
79
notice: Option<String>,
80
notice_serial: u64,
81
focus_handle: FocusHandle,
82
_observation: Subscription,
83
}
84
85
impl EventEmitter<ImageViewerEvent> for ImageViewer {}
86
87
fn decode(path: &Path) -> Option<image::DynamicImage> {
88
ImageReader::open(path)
89
.ok()?
90
.with_guessed_format()
91
.ok()?
92
.decode()
93
.ok()
94
}
95
96
fn rotate_decoded(decoded: image::DynamicImage, quarter_turns: u8) -> image::DynamicImage {
97
match quarter_turns {
98
1 => decoded.rotate90(),
99
2 => decoded.rotate180(),
100
3 => decoded.rotate270(),
101
_ => decoded,
102
}
103
}
104
105
fn rotated_render(path: &Path, quarter_turns: u8) -> Option<RenderImage> {
106
let mut pixels = rotate_decoded(decode(path)?, quarter_turns).to_rgba8();
107
for pixel in pixels.chunks_exact_mut(4) {
108
pixel.swap(0, 2);
109
}
110
Some(RenderImage::new(vec![Frame::new(pixels)]))
111
}
112
113
fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> {
114
let rotated = rotate_decoded(decode(path)?, quarter_turns);
115
let mut bytes = Vec::new();
116
rotated
117
.write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)
118
.ok()?;
119
Some(bytes)
120
}
121
122
fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {
123
match image::guess_format(bytes).ok()? {
124
image::ImageFormat::Png => Some(ImageFormat::Png),
125
image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),
126
image::ImageFormat::Gif => Some(ImageFormat::Gif),
127
image::ImageFormat::WebP => Some(ImageFormat::Webp),
128
image::ImageFormat::Bmp => Some(ImageFormat::Bmp),
129
_ => None,
130
}
131
}
132
133
fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {
134
if quarter_turns != 0 {
135
let bytes = rotated_png(path, quarter_turns)?;
136
return Some(ClipboardItem::new_image(&Image::from_bytes(ImageFormat::Png, bytes)));
137
}
138
let bytes = std::fs::read(path).ok()?;
139
let format = clipboard_format(&bytes)?;
140
Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))
141
}
142
143
fn suggested_name(path: &Path, rotated: bool) -> String {
144
let name = path
145
.file_name()
146
.map(|name| name.to_string_lossy().into_owned())
147
.unwrap_or_else(|| "image".to_owned());
148
if rotated {
149
return Path::new(&name).with_extension("png").to_string_lossy().into_owned();
150
}
151
if path.extension().is_some() {
152
return name;
153
}
154
let extension = std::fs::read(path)
155
.ok()
156
.and_then(|bytes| image::guess_format(&bytes).ok())
157
.and_then(|format| format.extensions_str().first().copied())
158
.unwrap_or("png");
159
format!("{name}.{extension}")
160
}
161
162
fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {
163
if quarter_turns == 0 {
164
return std::fs::copy(source, target).map(|_| ());
165
}
166
let bytes = rotated_png(source, quarter_turns)
167
.ok_or_else(|| std::io::Error::other("rotation failed"))?;
168
std::fs::write(target, bytes)
169
}
170
171
fn control_button(
172
id: &'static str,
173
glyph: &'static str,
174
tooltip: &'static str,
175
enabled: bool,
176
on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
177
) -> Stateful<Div> {
178
div()
179
.id(id)
180
.size(px(BUTTON_SIZE))
181
.flex_none()
182
.flex()
183
.items_center()
184
.justify_center()
185
.rounded(px(BUTTON_RADIUS))
186
.text_color(white())
187
.when(enabled, |button| {
188
button
189
.cursor_pointer()
190
.hover(|button| button.bg(white().opacity(0.12)))
191
})
192
.when(!enabled, |button| button.opacity(DISABLED_OPACITY))
193
.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))
194
.child(symbol(glyph, BUTTON_ICON_SIZE, white()))
195
.on_click(move |event, window, cx| {
196
cx.stop_propagation();
197
if enabled {
198
on_click(event, window, cx);
199
}
200
})
201
}
202
203
impl ImageViewer {
204
pub fn new(
205
app: Entity<AppState>,
206
request: ViewerRequest,
207
window: &mut Window,
208
cx: &mut Context<Self>,
209
) -> Self {
210
let focus_handle = cx.focus_handle();
211
window.focus(&focus_handle, cx);
212
let observation = cx.observe(&app, |_, _, cx| cx.notify());
213
let mut viewer = ImageViewer {
214
app,
215
conversation_id: request.conversation_id,
216
conversation_title: request.conversation_title,
217
index: request.index.min(request.items.len().saturating_sub(1)),
218
items: request.items,
219
scale: None,
220
pan: (0., 0.),
221
quarter_turns: 0,
222
rotated: None,
223
entered_fullscreen: false,
224
drag_from: None,
225
notice: None,
226
notice_serial: 0,
227
focus_handle,
228
_observation: observation,
229
};
230
cx.on_release_in(window, |this, window, _| {
231
this.release_rotated(window);
232
if this.entered_fullscreen && window.is_fullscreen() {
233
window.toggle_fullscreen();
234
}
235
})
236
.detach();
237
viewer.preload(window, cx);
238
viewer
239
}
240
241
pub fn focus_handle(&self) -> FocusHandle {
242
self.focus_handle.clone()
243
}
244
245
fn preload(&mut self, window: &Window, cx: &mut Context<Self>) {
246
let last_index = self.items.len().saturating_sub(1);
247
let visible = thumbnail_window(
248
self.index,
249
self.items.len(),
250
Self::thumbnail_capacity(window),
251
);
252
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));
254
let directory = &self.app.read(cx).directory;
255
let missing: Vec<_> = self
256
.items
257
.get(first..=last)
258
.unwrap_or_default()
259
.iter()
260
.map(|item| item.image.clone())
261
.filter(|image| directory.image(&image.url).is_none())
262
.collect();
263
if !missing.is_empty() {
264
self.app
265
.update(cx, |state, cx| state.request_images(missing, cx));
266
}
267
}
268
269
fn thumbnail_capacity(window: &Window) -> usize {
270
let width = f32::from(window.viewport_size().width);
271
((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))
272
.floor()
273
.max(1.) as usize
274
}
275
276
fn release_rotated(&mut self, window: &mut Window) {
277
if let Some(rotated) = self.rotated.take() {
278
window.drop_image(rotated.render).ok();
279
}
280
}
281
282
fn toggle_fullscreen(&mut self, window: &mut Window) {
283
self.entered_fullscreen = !window.is_fullscreen();
284
window.toggle_fullscreen();
285
}
286
287
fn current(&self) -> Option<&GalleryItem> {
288
self.items.get(self.index)
289
}
290
291
fn current_failed(&self, cx: &App) -> bool {
292
self.current()
293
.is_some_and(|item| self.app.read(cx).directory.image_failed(&item.image.url))
294
}
295
296
fn current_path(&self, cx: &App) -> Option<PathBuf> {
297
let item = self.current()?;
298
let entry = self.app.read(cx).directory.image(&item.image.url)?;
299
Some(entry.path.clone())
300
}
301
302
fn stage_size(window: &Window) -> Pair {
303
let viewport = window.viewport_size();
304
(
305
f32::from(viewport.width).max(1.),
306
(f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.),
307
)
308
}
309
310
fn layout(&self, window: &Window, cx: &App) -> Option<Layout> {
311
let item = self.current()?;
312
let entry = self.app.read(cx).directory.image(&item.image.url)?;
313
let stage = Self::stage_size(window);
314
let declared = item.image.width.zip(item.image.height);
315
let source = entry
316
.size
317
.or(declared)
318
.map_or(stage, |(width, height)| (width as f32, height as f32));
319
let source = rotated_size(source, self.quarter_turns);
320
let fit = fit_scale(source, stage);
321
let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit));
322
let pan = clamp_pan(self.pan, display_size(source, scale), stage);
323
Some(Layout {
324
stage,
325
source,
326
fit,
327
scale,
328
pan,
329
})
330
}
331
332
fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair {
333
let stage = Self::stage_size(window);
334
(
335
f32::from(position.x) - stage.0 / 2.,
336
f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2.,
337
)
338
}
339
340
fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) {
341
let Some(layout) = self.layout(window, cx) else {
342
return;
343
};
344
let view = zoom_at(
345
View {
346
scale: layout.scale,
347
pan: layout.pan,
348
},
349
wanted,
350
anchor,
351
layout.source,
352
layout.stage,
353
);
354
self.scale = (view.scale > layout.fit).then_some(view.scale);
355
self.pan = view.pan;
356
cx.notify();
357
}
358
359
fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) {
360
let Some(layout) = self.layout(window, cx) else {
361
return;
362
};
363
self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx);
364
}
365
366
fn zoom_fit(&mut self, cx: &mut Context<Self>) {
367
self.scale = None;
368
self.pan = (0., 0.);
369
cx.notify();
370
}
371
372
fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
373
let Some(layout) = self.layout(window, cx) else {
374
return;
375
};
376
let target = toggle_target(layout.scale, layout.fit);
377
self.zoom_to(target, Self::anchor_of(position, window), window, cx);
378
}
379
380
fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {
381
let Some(layout) = self.layout(window, cx) else {
382
return;
383
};
384
let top = f32::from(event.position.y);
385
if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 {
386
return;
387
}
388
let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();
389
let anchor = Self::anchor_of(event.position, window);
390
self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);
391
cx.stop_propagation();
392
}
393
394
fn on_mouse_move(
395
&mut self,
396
event: &MouseMoveEvent,
397
window: &mut Window,
398
cx: &mut Context<Self>,
399
) {
400
let Some(last) = self.drag_from else {
401
return;
402
};
403
if event.pressed_button != Some(MouseButton::Left) {
404
self.drag_from = None;
405
return;
406
}
407
let Some(layout) = self.layout(window, cx) else {
408
return;
409
};
410
let moved = (
411
layout.pan.0 + f32::from(event.position.x - last.x),
412
layout.pan.1 + f32::from(event.position.y - last.y),
413
);
414
self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);
415
self.drag_from = Some(event.position);
416
cx.notify();
417
}
418
419
fn end_drag(&mut self, cx: &mut Context<Self>) {
420
if self.drag_from.take().is_some() {
421
cx.notify();
422
}
423
}
424
425
fn jump(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
426
if index == self.index || index >= self.items.len() {
427
return;
428
}
429
self.index = index;
430
self.scale = None;
431
self.pan = (0., 0.);
432
self.quarter_turns = 0;
433
self.release_rotated(window);
434
self.drag_from = None;
435
self.preload(window, cx);
436
cx.notify();
437
}
438
439
fn go(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
440
self.jump(step_index(self.index, self.items.len(), delta), window, cx);
441
}
442
443
fn rotate(&mut self, window: &mut Window, cx: &mut Context<Self>) {
444
let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {
445
return;
446
};
447
let url = item.image.url.clone();
448
self.quarter_turns = next_rotation(self.quarter_turns);
449
self.scale = None;
450
self.pan = (0., 0.);
451
self.release_rotated(window);
452
let quarter_turns = self.quarter_turns;
453
if quarter_turns != 0 {
454
cx.spawn_in(window, async move |this, cx| {
455
let rotated = cx
456
.background_spawn(async move { rotated_render(&path, quarter_turns) })
457
.await;
458
this.update_in(cx, |this, window, cx| {
459
let still_current = this.quarter_turns == quarter_turns
460
&& this.current().is_some_and(|item| item.image.url == url);
461
if !still_current {
462
return;
463
}
464
match rotated {
465
Some(render) => {
466
this.release_rotated(window);
467
this.rotated = Some(RotatedImage {
468
url,
469
quarter_turns,
470
render: Arc::new(render),
471
});
472
}
473
None => {
474
this.quarter_turns = 0;
475
this.show_notice("Could not rotate", cx);
476
}
477
}
478
cx.notify();
479
})
480
.ok();
481
})
482
.detach();
483
}
484
cx.notify();
485
}
486
487
fn show_notice(&mut self, text: impl Into<String>, cx: &mut Context<Self>) {
488
self.notice_serial += 1;
489
let serial = self.notice_serial;
490
self.notice = Some(text.into());
491
cx.spawn(async move |this, cx| {
492
cx.background_executor().timer(NOTICE_DURATION).await;
493
this.update(cx, |this, cx| {
494
if this.notice_serial == serial {
495
this.notice = None;
496
cx.notify();
497
}
498
})
499
.ok();
500
})
501
.detach();
502
cx.notify();
503
}
504
505
fn rotated_render(&self) -> Option<&Arc<RenderImage>> {
506
let url = &self.current()?.image.url;
507
self.rotated
508
.as_ref()
509
.filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)
510
.map(|rotated| &rotated.render)
511
}
512
513
fn rotation_pending(&self) -> bool {
514
self.quarter_turns != 0 && self.rotated_render().is_none()
515
}
516
517
fn copy_image(&mut self, cx: &mut Context<Self>) {
518
let Some(path) = self.current_path(cx) else {
519
return;
520
};
521
if self.rotation_pending() {
522
self.show_notice("Rotating", cx);
523
return;
524
}
525
let quarter_turns = self.quarter_turns;
526
cx.spawn(async move |this, cx| {
527
let fallback = path.clone();
528
let item = cx
529
.background_spawn(async move { clipboard_item(&path, quarter_turns) })
530
.await;
531
this.update(cx, |this, cx| match item {
532
Some(item) => {
533
cx.write_to_clipboard(item);
534
this.show_notice("Image copied", cx);
535
}
536
None => {
537
cx.write_to_clipboard(ClipboardItem::new_string(fallback.display().to_string()));
538
this.show_notice("Copied file path", cx);
539
}
540
})
541
.ok();
542
})
543
.detach();
544
}
545
546
fn save_as(&mut self, cx: &mut Context<Self>) {
547
let Some(source) = self.current_path(cx) else {
548
return;
549
};
550
if self.rotation_pending() {
551
self.show_notice("Rotating", cx);
552
return;
553
}
554
let quarter_turns = self.quarter_turns;
555
cx.spawn(async move |this, cx| {
556
let name_source = source.clone();
557
let name = cx
558
.background_spawn(async move { suggested_name(&name_source, quarter_turns != 0) })
559
.await;
560
let Ok(receiver) = this.update(cx, |_, cx| {
561
cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name))
562
}) else {
563
return;
564
};
565
let Ok(Ok(Some(target))) = receiver.await else {
566
return;
567
};
568
let written = cx
569
.background_spawn(async move {
570
write_image(&source, &target, quarter_turns).map(|_| target)
571
})
572
.await;
573
this.update(cx, |this, cx| match written {
574
Ok(target) => {
575
let name = target
576
.file_name()
577
.map(|name| name.to_string_lossy().into_owned())
578
.unwrap_or_default();
579
this.show_notice(format!("Saved {name}"), cx)
580
}
581
Err(_) => this.show_notice("Could not save the image", cx),
582
})
583
.ok();
584
})
585
.detach();
586
}
587
588
fn forward(&mut self, cx: &mut Context<Self>) {
589
let Some(item) = self.current() else {
590
return;
591
};
592
let message_key = item.message_key.clone();
593
if self.app.read(cx).mode.read_only {
594
self.show_notice("Read-only mode: message not forwarded", cx);
595
return;
596
}
597
let conversation_id = self.conversation_id.clone();
598
self.app.update(cx, |state, cx| {
599
state.request_forward(&conversation_id, &message_key, cx)
600
});
601
}
602
603
fn open_externally(&mut self, cx: &mut Context<Self>) {
604
if let Some(path) = self.current_path(cx) {
605
cx.open_with_system(&path);
606
}
607
}
608
609
fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {
610
let command = event.keystroke.modifiers.secondary();
611
match (event.keystroke.key.as_str(), command) {
612
("escape", _) => cx.emit(ImageViewerEvent::Close),
613
("left", false) => self.go(-1, window, cx),
614
("right", false) => self.go(1, window, cx),
615
("r", false) => self.rotate(window, cx),
616
("f11", _) => self.toggle_fullscreen(window),
617
("=" | "+", true) => self.zoom_step(1, window, cx),
618
("-", true) => self.zoom_step(-1, window, cx),
619
("0", true) => self.zoom_fit(cx),
620
("c", true) => self.copy_image(cx),
621
("s", true) => self.save_as(cx),
622
_ => {}
623
}
624
cx.stop_propagation();
625
}
626
627
fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> {
628
let item = self.current();
629
let author = item.map(|item| item.author.clone()).unwrap_or_default();
630
let subtitle = item
631
.map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title))
632
.unwrap_or_default();
633
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);
635
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();
637
let loaded = layout.is_some();
638
h_flex()
639
.id("viewer-header")
640
.absolute()
641
.top_0()
642
.left_0()
643
.w_full()
644
.h(px(HEADER_HEIGHT))
645
.px(px(SIDE_PADDING))
646
.gap(px(12.))
647
.items_center()
648
.child(
649
h_flex()
650
.flex_1()
651
.min_w_0()
652
.gap(px(10.))
653
.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
)
665
.child(
666
v_flex()
667
.flex_1()
668
.min_w_0()
669
.child(
670
div()
671
.truncate()
672
.text_size(px(14.))
673
.font_weight(FontWeight::SEMIBOLD)
674
.text_color(white())
675
.child(author),
676
)
677
.child(
678
div()
679
.truncate()
680
.text_size(px(12.))
681
.text_color(white().opacity(0.6))
682
.child(subtitle),
683
),
684
),
685
)
686
.child(
687
h_flex()
688
.flex_none()
689
.gap(px(2.))
690
.items_center()
691
.child(control_button(
692
"viewer-zoom-out",
693
"zoom_out",
694
"Zoom out (Ctrl -)",
695
can_zoom_out,
696
cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)),
697
))
698
.child(
699
div()
700
.w(px(ZOOM_LABEL_WIDTH))
701
.flex_none()
702
.text_center()
703
.text_size(px(12.))
704
.text_color(white().opacity(0.8))
705
.child(zoom_label),
706
)
707
.child(control_button(
708
"viewer-zoom-in",
709
"zoom_in",
710
"Zoom in (Ctrl +)",
711
can_zoom_in,
712
cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)),
713
))
714
.child(control_button(
715
"viewer-rotate",
716
"rotate_right",
717
"Rotate (R)",
718
loaded,
719
cx.listener(|this, _, window, cx| this.rotate(window, cx)),
720
))
721
.child(control_button(
722
"viewer-copy",
723
"content_copy",
724
"Copy image (Ctrl C)",
725
loaded,
726
cx.listener(|this, _, _, cx| this.copy_image(cx)),
727
))
728
.child(control_button(
729
"viewer-save",
730
"download",
731
"Save as (Ctrl S)",
732
loaded,
733
cx.listener(|this, _, _, cx| this.save_as(cx)),
734
))
735
.child(control_button(
736
"viewer-forward",
737
"forward",
738
"Forward",
739
true,
740
cx.listener(|this, _, _, cx| this.forward(cx)),
741
))
742
.child(control_button(
743
"viewer-fullscreen",
744
"fullscreen",
745
"Full screen (F11)",
746
true,
747
cx.listener(|this, _, window, _| this.toggle_fullscreen(window)),
748
))
749
.child(control_button(
750
"viewer-open",
751
"open_in_new",
752
"Open in Photos",
753
loaded,
754
cx.listener(|this, _, _, cx| this.open_externally(cx)),
755
))
756
.child(control_button(
757
"viewer-close",
758
"close",
759
"Close (Esc)",
760
true,
761
cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),
762
)),
763
)
764
.on_click(|_, _, cx| cx.stop_propagation())
765
}
766
767
fn nav_button(
768
&self,
769
id: &'static str,
770
glyph: &'static str,
771
left: bool,
772
stage: Pair,
773
cx: &mut Context<Self>,
774
delta: isize,
775
) -> Stateful<Div> {
776
let top = ((stage.1 - NAV_SIZE) / 2.).max(0.);
777
div()
778
.id(id)
779
.absolute()
780
.top(px(top))
781
.when(left, |button| button.left(px(NAV_MARGIN)))
782
.when(!left, |button| button.right(px(NAV_MARGIN)))
783
.size(px(NAV_SIZE))
784
.flex()
785
.items_center()
786
.justify_center()
787
.rounded_full()
788
.bg(white().opacity(0.1))
789
.cursor_pointer()
790
.hover(|button| button.bg(white().opacity(0.2)))
791
.child(symbol(glyph, NAV_ICON_SIZE, white()))
792
.on_click(cx.listener(move |this, _, window, cx| {
793
cx.stop_propagation();
794
this.go(delta, window, cx);
795
}))
796
}
797
798
fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement {
799
let display = display_size(layout.source, layout.scale);
800
let origin = image_origin(display, layout.stage, layout.pan);
801
let Some(item) = self.current() else {
802
return div().into_any_element();
803
};
804
let source: Option<ImageSource> = if self.quarter_turns == 0 {
805
self.app
806
.read(cx)
807
.directory
808
.image(&item.image.url)
809
.map(|entry| entry.path.clone().into())
810
} else {
811
self.rotated_render().map(|render| ImageSource::Render(render.clone()))
812
};
813
let Some(source) = source else {
814
return loading_placeholder();
815
};
816
div()
817
.id("viewer-picture")
818
.absolute()
819
.left(px(origin.0))
820
.top(px(origin.1))
821
.w(px(display.0))
822
.h(px(display.1))
823
.child(img(source).size_full().object_fit(ObjectFit::Fill))
824
.on_mouse_down(
825
MouseButton::Left,
826
cx.listener(|this, event: &MouseDownEvent, _, cx| {
827
cx.stop_propagation();
828
this.drag_from = Some(event.position);
829
}),
830
)
831
.on_click(cx.listener(|this, event: &ClickEvent, window, cx| {
832
cx.stop_propagation();
833
if event.click_count() == 2 {
834
this.toggle_zoom(event.position(), window, cx);
835
}
836
}))
837
.into_any_element()
838
}
839
840
fn thumbnail(&self, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {
841
let item = &self.items[index];
842
let current = index == self.index;
843
let path = self
844
.app
845
.read(cx)
846
.directory
847
.image(&item.image.url)
848
.map(|entry| entry.path.clone());
849
div()
850
.id(ElementId::Name(format!("viewer-thumbnail-{index}").into()))
851
.size(px(THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER))
852
.flex_none()
853
.flex()
854
.items_center()
855
.justify_center()
856
.rounded(px(THUMBNAIL_RADIUS + THUMBNAIL_BORDER))
857
.border_2()
858
.border_color(if current {
859
theme::accent()
860
} else {
861
transparent_black()
862
})
863
.cursor_pointer()
864
.child(
865
div()
866
.size(px(THUMBNAIL_SIZE))
867
.flex_none()
868
.flex()
869
.items_center()
870
.justify_center()
871
.overflow_hidden()
872
.rounded(px(THUMBNAIL_RADIUS))
873
.bg(white().opacity(0.08))
874
.when(!current, |frame| frame.opacity(0.7))
875
.map(|frame| match path {
876
Some(path) => frame.child(
877
img(path)
878
.size_full()
879
.object_fit(ObjectFit::Cover),
880
),
881
None => frame.child(symbol("image", 18., white().opacity(0.5))),
882
}),
883
)
884
.on_click(cx.listener(move |this, _, window, cx| {
885
cx.stop_propagation();
886
this.jump(index, window, cx);
887
}))
888
}
889
890
fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {
891
let width = f32::from(window.viewport_size().width);
892
let range = thumbnail_window(
893
self.index,
894
self.items.len(),
895
Self::thumbnail_capacity(window),
896
);
897
let caption = self
898
.current()
899
.map(|item| item.caption.clone())
900
.unwrap_or_default();
901
let status = self
902
.notice
903
.clone()
904
.unwrap_or_else(|| counter_label(self.index, self.items.len()));
905
v_flex()
906
.id("viewer-footer")
907
.absolute()
908
.bottom_0()
909
.left_0()
910
.w_full()
911
.h(px(FOOTER_HEIGHT))
912
.pb(px(12.))
913
.gap(px(4.))
914
.items_center()
915
.justify_end()
916
.child(
917
div()
918
.w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH)))
919
.h(px(CAPTION_HEIGHT))
920
.flex_none()
921
.truncate()
922
.text_center()
923
.text_size(px(13.))
924
.text_color(white().opacity(0.9))
925
.child(caption),
926
)
927
.child(
928
div()
929
.h(px(STATUS_HEIGHT))
930
.flex_none()
931
.text_size(px(12.))
932
.text_color(white().opacity(0.6))
933
.child(status),
934
)
935
.child(
936
h_flex()
937
.h(px(STRIP_HEIGHT))
938
.flex_none()
939
.gap(px(THUMBNAIL_GAP))
940
.items_center()
941
.children(range.map(|index| self.thumbnail(index, cx))),
942
)
943
.on_click(|_, _, cx| cx.stop_propagation())
944
}
945
}
946
947
fn status_placeholder(text: &'static str) -> AnyElement {
948
v_flex()
949
.size_full()
950
.gap(px(6.))
951
.items_center()
952
.justify_center()
953
.child(symbol("image", 28., white().opacity(0.5)))
954
.child(
955
div()
956
.text_size(px(12.))
957
.text_color(white().opacity(0.6))
958
.child(text),
959
)
960
.into_any_element()
961
}
962
963
fn loading_placeholder() -> AnyElement {
964
status_placeholder("Loading image")
965
}
966
967
impl Render for ImageViewer {
968
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
969
let layout = self.layout(window, cx);
970
let stage = Self::stage_size(window);
971
let has_previous = self.index > 0;
972
let has_next = self.index + 1 < self.items.len();
973
let picture = match layout {
974
Some(layout) => self.picture(layout, cx),
975
None if self.current_failed(cx) => status_placeholder("Image unavailable"),
976
None => loading_placeholder(),
977
};
978
let header = self.header(layout, cx);
979
let footer = self.footer(window, cx);
980
div()
981
.id("image-viewer")
982
.key_context("ImageViewer")
983
.track_focus(&self.focus_handle)
984
.absolute()
985
.top_0()
986
.left_0()
987
.size_full()
988
.bg(rgba(BACKDROP))
989
.occlude()
990
.on_key_down(cx.listener(Self::on_key_down))
991
.on_scroll_wheel(cx.listener(Self::on_wheel))
992
.on_mouse_move(cx.listener(Self::on_mouse_move))
993
.on_mouse_up(
994
MouseButton::Left,
995
cx.listener(|this, _, _, cx| this.end_drag(cx)),
996
)
997
.on_mouse_up_out(
998
MouseButton::Left,
999
cx.listener(|this, _, _, cx| this.end_drag(cx)),
1000
)
1001
.on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)))
1002
.child(
1003
div()
1004
.absolute()
1005
.top(px(HEADER_HEIGHT))
1006
.left_0()
1007
.w(px(stage.0))
1008
.h(px(stage.1))
1009
.overflow_hidden()
1010
.child(picture)
1011
.when(has_previous, |stage_element| {
1012
stage_element.child(self.nav_button(
1013
"viewer-previous",
1014
"chevron_left",
1015
true,
1016
stage,
1017
cx,
1018
-1,
1019
))
1020
})
1021
.when(has_next, |stage_element| {
1022
stage_element.child(self.nav_button(
1023
"viewer-next",
1024
"chevron_right",
1025
false,
1026
stage,
1027
cx,
1028
1,
1029
))
1030
}),
1031
)
1032
.child(header)
1033
.child(footer)
1034
}
1035
}
@@ -0,0 +1,1035 @@1
use std::io::Cursor;2
use std::path::{Path, PathBuf};3
use std::sync::Arc;4
use std::time::Duration;5
6
use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};7
use gpui_kit::prelude::FluentBuilder as _;8
use gpui_kit::*;9
10
use image::{Frame, ImageReader};11
12
use super::avatar::person_avatar;13
use super::widgets::symbol;14
use crate::app_state::AppState;15
use crate::downloads;16
use crate::image_view_gallery::{GalleryItem, ViewerRequest};17
use crate::theme;18
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,21
thumbnail_window, toggle_target, wheel_scale, zoom_at,22
};23
24
const HEADER_HEIGHT: f32 = 52.;25
const FOOTER_HEIGHT: f32 = 120.;26
const BUTTON_SIZE: f32 = 36.;27
const BUTTON_RADIUS: f32 = 8.;28
const BUTTON_ICON_SIZE: f32 = 20.;29
const NAV_ICON_SIZE: f32 = 24.;30
const ZOOM_LABEL_WIDTH: f32 = 52.;31
const NAV_SIZE: f32 = 44.;32
const NAV_MARGIN: f32 = 16.;33
const AVATAR_SIZE: f32 = 32.;34
const SIDE_PADDING: f32 = 16.;35
const THUMBNAIL_SIZE: f32 = 48.;36
const THUMBNAIL_GAP: f32 = 8.;37
const THUMBNAIL_RADIUS: f32 = 6.;38
const THUMBNAIL_BORDER: f32 = 2.;39
const CAPTION_MAX_WIDTH: f32 = 720.;40
const CAPTION_HEIGHT: f32 = 22.;41
const STATUS_HEIGHT: f32 = 18.;42
const STRIP_HEIGHT: f32 = THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER;43
const WHEEL_LINE_HEIGHT: f32 = 20.;44
const BACKDROP: u32 = 0x080809fc;45
const DISABLED_OPACITY: f32 = 0.35;46
const NOTICE_DURATION: Duration = Duration::from_secs(2);47
48
pub enum ImageViewerEvent {49
Close,50
}51
52
struct RotatedImage {53
url: String,54
quarter_turns: u8,55
render: Arc<RenderImage>,56
}57
58
#[derive(Clone, Copy)]59
struct Layout {60
stage: Pair,61
source: Pair,62
fit: f32,63
scale: f32,64
pan: Pair,65
}66
67
pub struct ImageViewer {68
app: Entity<AppState>,69
conversation_id: String,70
conversation_title: String,71
items: Vec<GalleryItem>,72
index: usize,73
scale: Option<f32>,74
pan: Pair,75
quarter_turns: u8,76
rotated: Option<RotatedImage>,77
entered_fullscreen: bool,78
drag_from: Option<Point<Pixels>>,79
notice: Option<String>,80
notice_serial: u64,81
focus_handle: FocusHandle,82
_observation: Subscription,83
}84
85
impl EventEmitter<ImageViewerEvent> for ImageViewer {}86
87
fn decode(path: &Path) -> Option<image::DynamicImage> {88
ImageReader::open(path)89
.ok()?90
.with_guessed_format()91
.ok()?92
.decode()93
.ok()94
}95
96
fn rotate_decoded(decoded: image::DynamicImage, quarter_turns: u8) -> image::DynamicImage {97
match quarter_turns {98
1 => decoded.rotate90(),99
2 => decoded.rotate180(),100
3 => decoded.rotate270(),101
_ => decoded,102
}103
}104
105
fn rotated_render(path: &Path, quarter_turns: u8) -> Option<RenderImage> {106
let mut pixels = rotate_decoded(decode(path)?, quarter_turns).to_rgba8();107
for pixel in pixels.chunks_exact_mut(4) {108
pixel.swap(0, 2);109
}110
Some(RenderImage::new(vec![Frame::new(pixels)]))111
}112
113
fn rotated_png(path: &Path, quarter_turns: u8) -> Option<Vec<u8>> {114
let rotated = rotate_decoded(decode(path)?, quarter_turns);115
let mut bytes = Vec::new();116
rotated117
.write_to(&mut Cursor::new(&mut bytes), image::ImageFormat::Png)118
.ok()?;119
Some(bytes)120
}121
122
fn clipboard_format(bytes: &[u8]) -> Option<ImageFormat> {123
match image::guess_format(bytes).ok()? {124
image::ImageFormat::Png => Some(ImageFormat::Png),125
image::ImageFormat::Jpeg => Some(ImageFormat::Jpeg),126
image::ImageFormat::Gif => Some(ImageFormat::Gif),127
image::ImageFormat::WebP => Some(ImageFormat::Webp),128
image::ImageFormat::Bmp => Some(ImageFormat::Bmp),129
_ => None,130
}131
}132
133
fn clipboard_item(path: &Path, quarter_turns: u8) -> Option<ClipboardItem> {134
if quarter_turns != 0 {135
let bytes = rotated_png(path, quarter_turns)?;136
return Some(ClipboardItem::new_image(&Image::from_bytes(ImageFormat::Png, bytes)));137
}138
let bytes = std::fs::read(path).ok()?;139
let format = clipboard_format(&bytes)?;140
Some(ClipboardItem::new_image(&Image::from_bytes(format, bytes)))141
}142
143
fn suggested_name(path: &Path, rotated: bool) -> String {144
let name = path145
.file_name()146
.map(|name| name.to_string_lossy().into_owned())147
.unwrap_or_else(|| "image".to_owned());148
if rotated {149
return Path::new(&name).with_extension("png").to_string_lossy().into_owned();150
}151
if path.extension().is_some() {152
return name;153
}154
let extension = std::fs::read(path)155
.ok()156
.and_then(|bytes| image::guess_format(&bytes).ok())157
.and_then(|format| format.extensions_str().first().copied())158
.unwrap_or("png");159
format!("{name}.{extension}")160
}161
162
fn write_image(source: &Path, target: &Path, quarter_turns: u8) -> std::io::Result<()> {163
if quarter_turns == 0 {164
return std::fs::copy(source, target).map(|_| ());165
}166
let bytes = rotated_png(source, quarter_turns)167
.ok_or_else(|| std::io::Error::other("rotation failed"))?;168
std::fs::write(target, bytes)169
}170
171
fn control_button(172
id: &'static str,173
glyph: &'static str,174
tooltip: &'static str,175
enabled: bool,176
on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,177
) -> Stateful<Div> {178
div()179
.id(id)180
.size(px(BUTTON_SIZE))181
.flex_none()182
.flex()183
.items_center()184
.justify_center()185
.rounded(px(BUTTON_RADIUS))186
.text_color(white())187
.when(enabled, |button| {188
button189
.cursor_pointer()190
.hover(|button| button.bg(white().opacity(0.12)))191
})192
.when(!enabled, |button| button.opacity(DISABLED_OPACITY))193
.tooltip(move |window, cx| Tooltip::new(tooltip).build(window, cx))194
.child(symbol(glyph, BUTTON_ICON_SIZE, white()))195
.on_click(move |event, window, cx| {196
cx.stop_propagation();197
if enabled {198
on_click(event, window, cx);199
}200
})201
}202
203
impl ImageViewer {204
pub fn new(205
app: Entity<AppState>,206
request: ViewerRequest,207
window: &mut Window,208
cx: &mut Context<Self>,209
) -> Self {210
let focus_handle = cx.focus_handle();211
window.focus(&focus_handle, cx);212
let observation = cx.observe(&app, |_, _, cx| cx.notify());213
let mut viewer = ImageViewer {214
app,215
conversation_id: request.conversation_id,216
conversation_title: request.conversation_title,217
index: request.index.min(request.items.len().saturating_sub(1)),218
items: request.items,219
scale: None,220
pan: (0., 0.),221
quarter_turns: 0,222
rotated: None,223
entered_fullscreen: false,224
drag_from: None,225
notice: None,226
notice_serial: 0,227
focus_handle,228
_observation: observation,229
};230
cx.on_release_in(window, |this, window, _| {231
this.release_rotated(window);232
if this.entered_fullscreen && window.is_fullscreen() {233
window.toggle_fullscreen();234
}235
})236
.detach();237
viewer.preload(window, cx);238
viewer239
}240
241
pub fn focus_handle(&self) -> FocusHandle {242
self.focus_handle.clone()243
}244
245
fn preload(&mut self, window: &Window, cx: &mut Context<Self>) {246
let last_index = self.items.len().saturating_sub(1);247
let visible = thumbnail_window(248
self.index,249
self.items.len(),250
Self::thumbnail_capacity(window),251
);252
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));254
let directory = &self.app.read(cx).directory;255
let missing: Vec<_> = self256
.items257
.get(first..=last)258
.unwrap_or_default()259
.iter()260
.map(|item| item.image.clone())261
.filter(|image| directory.image(&image.url).is_none())262
.collect();263
if !missing.is_empty() {264
self.app265
.update(cx, |state, cx| state.request_images(missing, cx));266
}267
}268
269
fn thumbnail_capacity(window: &Window) -> usize {270
let width = f32::from(window.viewport_size().width);271
((width - 2. * SIDE_PADDING) / (THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER + THUMBNAIL_GAP))272
.floor()273
.max(1.) as usize274
}275
276
fn release_rotated(&mut self, window: &mut Window) {277
if let Some(rotated) = self.rotated.take() {278
window.drop_image(rotated.render).ok();279
}280
}281
282
fn toggle_fullscreen(&mut self, window: &mut Window) {283
self.entered_fullscreen = !window.is_fullscreen();284
window.toggle_fullscreen();285
}286
287
fn current(&self) -> Option<&GalleryItem> {288
self.items.get(self.index)289
}290
291
fn current_failed(&self, cx: &App) -> bool {292
self.current()293
.is_some_and(|item| self.app.read(cx).directory.image_failed(&item.image.url))294
}295
296
fn current_path(&self, cx: &App) -> Option<PathBuf> {297
let item = self.current()?;298
let entry = self.app.read(cx).directory.image(&item.image.url)?;299
Some(entry.path.clone())300
}301
302
fn stage_size(window: &Window) -> Pair {303
let viewport = window.viewport_size();304
(305
f32::from(viewport.width).max(1.),306
(f32::from(viewport.height) - HEADER_HEIGHT - FOOTER_HEIGHT).max(1.),307
)308
}309
310
fn layout(&self, window: &Window, cx: &App) -> Option<Layout> {311
let item = self.current()?;312
let entry = self.app.read(cx).directory.image(&item.image.url)?;313
let stage = Self::stage_size(window);314
let declared = item.image.width.zip(item.image.height);315
let source = entry316
.size317
.or(declared)318
.map_or(stage, |(width, height)| (width as f32, height as f32));319
let source = rotated_size(source, self.quarter_turns);320
let fit = fit_scale(source, stage);321
let scale = self.scale.map_or(fit, |scale| clamp_scale(scale, fit));322
let pan = clamp_pan(self.pan, display_size(source, scale), stage);323
Some(Layout {324
stage,325
source,326
fit,327
scale,328
pan,329
})330
}331
332
fn anchor_of(position: Point<Pixels>, window: &Window) -> Pair {333
let stage = Self::stage_size(window);334
(335
f32::from(position.x) - stage.0 / 2.,336
f32::from(position.y) - HEADER_HEIGHT - stage.1 / 2.,337
)338
}339
340
fn zoom_to(&mut self, wanted: f32, anchor: Pair, window: &Window, cx: &mut Context<Self>) {341
let Some(layout) = self.layout(window, cx) else {342
return;343
};344
let view = zoom_at(345
View {346
scale: layout.scale,347
pan: layout.pan,348
},349
wanted,350
anchor,351
layout.source,352
layout.stage,353
);354
self.scale = (view.scale > layout.fit).then_some(view.scale);355
self.pan = view.pan;356
cx.notify();357
}358
359
fn zoom_step(&mut self, direction: i32, window: &Window, cx: &mut Context<Self>) {360
let Some(layout) = self.layout(window, cx) else {361
return;362
};363
self.zoom_to(step_scale(layout.scale, direction), (0., 0.), window, cx);364
}365
366
fn zoom_fit(&mut self, cx: &mut Context<Self>) {367
self.scale = None;368
self.pan = (0., 0.);369
cx.notify();370
}371
372
fn toggle_zoom(&mut self, position: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {373
let Some(layout) = self.layout(window, cx) else {374
return;375
};376
let target = toggle_target(layout.scale, layout.fit);377
self.zoom_to(target, Self::anchor_of(position, window), window, cx);378
}379
380
fn on_wheel(&mut self, event: &ScrollWheelEvent, window: &mut Window, cx: &mut Context<Self>) {381
let Some(layout) = self.layout(window, cx) else {382
return;383
};384
let top = f32::from(event.position.y);385
if top < HEADER_HEIGHT || top > HEADER_HEIGHT + layout.stage.1 {386
return;387
}388
let delta = event.delta.pixel_delta(px(WHEEL_LINE_HEIGHT)).y.into();389
let anchor = Self::anchor_of(event.position, window);390
self.zoom_to(wheel_scale(layout.scale, delta), anchor, window, cx);391
cx.stop_propagation();392
}393
394
fn on_mouse_move(395
&mut self,396
event: &MouseMoveEvent,397
window: &mut Window,398
cx: &mut Context<Self>,399
) {400
let Some(last) = self.drag_from else {401
return;402
};403
if event.pressed_button != Some(MouseButton::Left) {404
self.drag_from = None;405
return;406
}407
let Some(layout) = self.layout(window, cx) else {408
return;409
};410
let moved = (411
layout.pan.0 + f32::from(event.position.x - last.x),412
layout.pan.1 + f32::from(event.position.y - last.y),413
);414
self.pan = clamp_pan(moved, display_size(layout.source, layout.scale), layout.stage);415
self.drag_from = Some(event.position);416
cx.notify();417
}418
419
fn end_drag(&mut self, cx: &mut Context<Self>) {420
if self.drag_from.take().is_some() {421
cx.notify();422
}423
}424
425
fn jump(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {426
if index == self.index || index >= self.items.len() {427
return;428
}429
self.index = index;430
self.scale = None;431
self.pan = (0., 0.);432
self.quarter_turns = 0;433
self.release_rotated(window);434
self.drag_from = None;435
self.preload(window, cx);436
cx.notify();437
}438
439
fn go(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {440
self.jump(step_index(self.index, self.items.len(), delta), window, cx);441
}442
443
fn rotate(&mut self, window: &mut Window, cx: &mut Context<Self>) {444
let (Some(path), Some(item)) = (self.current_path(cx), self.current()) else {445
return;446
};447
let url = item.image.url.clone();448
self.quarter_turns = next_rotation(self.quarter_turns);449
self.scale = None;450
self.pan = (0., 0.);451
self.release_rotated(window);452
let quarter_turns = self.quarter_turns;453
if quarter_turns != 0 {454
cx.spawn_in(window, async move |this, cx| {455
let rotated = cx456
.background_spawn(async move { rotated_render(&path, quarter_turns) })457
.await;458
this.update_in(cx, |this, window, cx| {459
let still_current = this.quarter_turns == quarter_turns460
&& this.current().is_some_and(|item| item.image.url == url);461
if !still_current {462
return;463
}464
match rotated {465
Some(render) => {466
this.release_rotated(window);467
this.rotated = Some(RotatedImage {468
url,469
quarter_turns,470
render: Arc::new(render),471
});472
}473
None => {474
this.quarter_turns = 0;475
this.show_notice("Could not rotate", cx);476
}477
}478
cx.notify();479
})480
.ok();481
})482
.detach();483
}484
cx.notify();485
}486
487
fn show_notice(&mut self, text: impl Into<String>, cx: &mut Context<Self>) {488
self.notice_serial += 1;489
let serial = self.notice_serial;490
self.notice = Some(text.into());491
cx.spawn(async move |this, cx| {492
cx.background_executor().timer(NOTICE_DURATION).await;493
this.update(cx, |this, cx| {494
if this.notice_serial == serial {495
this.notice = None;496
cx.notify();497
}498
})499
.ok();500
})501
.detach();502
cx.notify();503
}504
505
fn rotated_render(&self) -> Option<&Arc<RenderImage>> {506
let url = &self.current()?.image.url;507
self.rotated508
.as_ref()509
.filter(|rotated| rotated.url == *url && rotated.quarter_turns == self.quarter_turns)510
.map(|rotated| &rotated.render)511
}512
513
fn rotation_pending(&self) -> bool {514
self.quarter_turns != 0 && self.rotated_render().is_none()515
}516
517
fn copy_image(&mut self, cx: &mut Context<Self>) {518
let Some(path) = self.current_path(cx) else {519
return;520
};521
if self.rotation_pending() {522
self.show_notice("Rotating", cx);523
return;524
}525
let quarter_turns = self.quarter_turns;526
cx.spawn(async move |this, cx| {527
let fallback = path.clone();528
let item = cx529
.background_spawn(async move { clipboard_item(&path, quarter_turns) })530
.await;531
this.update(cx, |this, cx| match item {532
Some(item) => {533
cx.write_to_clipboard(item);534
this.show_notice("Image copied", cx);535
}536
None => {537
cx.write_to_clipboard(ClipboardItem::new_string(fallback.display().to_string()));538
this.show_notice("Copied file path", cx);539
}540
})541
.ok();542
})543
.detach();544
}545
546
fn save_as(&mut self, cx: &mut Context<Self>) {547
let Some(source) = self.current_path(cx) else {548
return;549
};550
if self.rotation_pending() {551
self.show_notice("Rotating", cx);552
return;553
}554
let quarter_turns = self.quarter_turns;555
cx.spawn(async move |this, cx| {556
let name_source = source.clone();557
let name = cx558
.background_spawn(async move { suggested_name(&name_source, quarter_turns != 0) })559
.await;560
let Ok(receiver) = this.update(cx, |_, cx| {561
cx.prompt_for_new_path(&downloads::downloads_directory(), Some(&name))562
}) else {563
return;564
};565
let Ok(Ok(Some(target))) = receiver.await else {566
return;567
};568
let written = cx569
.background_spawn(async move {570
write_image(&source, &target, quarter_turns).map(|_| target)571
})572
.await;573
this.update(cx, |this, cx| match written {574
Ok(target) => {575
let name = target576
.file_name()577
.map(|name| name.to_string_lossy().into_owned())578
.unwrap_or_default();579
this.show_notice(format!("Saved {name}"), cx)580
}581
Err(_) => this.show_notice("Could not save the image", cx),582
})583
.ok();584
})585
.detach();586
}587
588
fn forward(&mut self, cx: &mut Context<Self>) {589
let Some(item) = self.current() else {590
return;591
};592
let message_key = item.message_key.clone();593
if self.app.read(cx).mode.read_only {594
self.show_notice("Read-only mode: message not forwarded", cx);595
return;596
}597
let conversation_id = self.conversation_id.clone();598
self.app.update(cx, |state, cx| {599
state.request_forward(&conversation_id, &message_key, cx)600
});601
}602
603
fn open_externally(&mut self, cx: &mut Context<Self>) {604
if let Some(path) = self.current_path(cx) {605
cx.open_with_system(&path);606
}607
}608
609
fn on_key_down(&mut self, event: &KeyDownEvent, window: &mut Window, cx: &mut Context<Self>) {610
let command = event.keystroke.modifiers.secondary();611
match (event.keystroke.key.as_str(), command) {612
("escape", _) => cx.emit(ImageViewerEvent::Close),613
("left", false) => self.go(-1, window, cx),614
("right", false) => self.go(1, window, cx),615
("r", false) => self.rotate(window, cx),616
("f11", _) => self.toggle_fullscreen(window),617
("=" | "+", true) => self.zoom_step(1, window, cx),618
("-", true) => self.zoom_step(-1, window, cx),619
("0", true) => self.zoom_fit(cx),620
("c", true) => self.copy_image(cx),621
("s", true) => self.save_as(cx),622
_ => {}623
}624
cx.stop_propagation();625
}626
627
fn header(&self, layout: Option<Layout>, cx: &mut Context<Self>) -> Stateful<Div> {628
let item = self.current();629
let author = item.map(|item| item.author.clone()).unwrap_or_default();630
let subtitle = item631
.map(|item| format!("{} \u{b7} {}", item.time, self.conversation_title))632
.unwrap_or_default();633
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);635
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();637
let loaded = layout.is_some();638
h_flex()639
.id("viewer-header")640
.absolute()641
.top_0()642
.left_0()643
.w_full()644
.h(px(HEADER_HEIGHT))645
.px(px(SIDE_PADDING))646
.gap(px(12.))647
.items_center()648
.child(649
h_flex()650
.flex_1()651
.min_w_0()652
.gap(px(10.))653
.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
)665
.child(666
v_flex()667
.flex_1()668
.min_w_0()669
.child(670
div()671
.truncate()672
.text_size(px(14.))673
.font_weight(FontWeight::SEMIBOLD)674
.text_color(white())675
.child(author),676
)677
.child(678
div()679
.truncate()680
.text_size(px(12.))681
.text_color(white().opacity(0.6))682
.child(subtitle),683
),684
),685
)686
.child(687
h_flex()688
.flex_none()689
.gap(px(2.))690
.items_center()691
.child(control_button(692
"viewer-zoom-out",693
"zoom_out",694
"Zoom out (Ctrl -)",695
can_zoom_out,696
cx.listener(|this, _, window, cx| this.zoom_step(-1, window, cx)),697
))698
.child(699
div()700
.w(px(ZOOM_LABEL_WIDTH))701
.flex_none()702
.text_center()703
.text_size(px(12.))704
.text_color(white().opacity(0.8))705
.child(zoom_label),706
)707
.child(control_button(708
"viewer-zoom-in",709
"zoom_in",710
"Zoom in (Ctrl +)",711
can_zoom_in,712
cx.listener(|this, _, window, cx| this.zoom_step(1, window, cx)),713
))714
.child(control_button(715
"viewer-rotate",716
"rotate_right",717
"Rotate (R)",718
loaded,719
cx.listener(|this, _, window, cx| this.rotate(window, cx)),720
))721
.child(control_button(722
"viewer-copy",723
"content_copy",724
"Copy image (Ctrl C)",725
loaded,726
cx.listener(|this, _, _, cx| this.copy_image(cx)),727
))728
.child(control_button(729
"viewer-save",730
"download",731
"Save as (Ctrl S)",732
loaded,733
cx.listener(|this, _, _, cx| this.save_as(cx)),734
))735
.child(control_button(736
"viewer-forward",737
"forward",738
"Forward",739
true,740
cx.listener(|this, _, _, cx| this.forward(cx)),741
))742
.child(control_button(743
"viewer-fullscreen",744
"fullscreen",745
"Full screen (F11)",746
true,747
cx.listener(|this, _, window, _| this.toggle_fullscreen(window)),748
))749
.child(control_button(750
"viewer-open",751
"open_in_new",752
"Open in Photos",753
loaded,754
cx.listener(|this, _, _, cx| this.open_externally(cx)),755
))756
.child(control_button(757
"viewer-close",758
"close",759
"Close (Esc)",760
true,761
cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)),762
)),763
)764
.on_click(|_, _, cx| cx.stop_propagation())765
}766
767
fn nav_button(768
&self,769
id: &'static str,770
glyph: &'static str,771
left: bool,772
stage: Pair,773
cx: &mut Context<Self>,774
delta: isize,775
) -> Stateful<Div> {776
let top = ((stage.1 - NAV_SIZE) / 2.).max(0.);777
div()778
.id(id)779
.absolute()780
.top(px(top))781
.when(left, |button| button.left(px(NAV_MARGIN)))782
.when(!left, |button| button.right(px(NAV_MARGIN)))783
.size(px(NAV_SIZE))784
.flex()785
.items_center()786
.justify_center()787
.rounded_full()788
.bg(white().opacity(0.1))789
.cursor_pointer()790
.hover(|button| button.bg(white().opacity(0.2)))791
.child(symbol(glyph, NAV_ICON_SIZE, white()))792
.on_click(cx.listener(move |this, _, window, cx| {793
cx.stop_propagation();794
this.go(delta, window, cx);795
}))796
}797
798
fn picture(&self, layout: Layout, cx: &mut Context<Self>) -> AnyElement {799
let display = display_size(layout.source, layout.scale);800
let origin = image_origin(display, layout.stage, layout.pan);801
let Some(item) = self.current() else {802
return div().into_any_element();803
};804
let source: Option<ImageSource> = if self.quarter_turns == 0 {805
self.app806
.read(cx)807
.directory808
.image(&item.image.url)809
.map(|entry| entry.path.clone().into())810
} else {811
self.rotated_render().map(|render| ImageSource::Render(render.clone()))812
};813
let Some(source) = source else {814
return loading_placeholder();815
};816
div()817
.id("viewer-picture")818
.absolute()819
.left(px(origin.0))820
.top(px(origin.1))821
.w(px(display.0))822
.h(px(display.1))823
.child(img(source).size_full().object_fit(ObjectFit::Fill))824
.on_mouse_down(825
MouseButton::Left,826
cx.listener(|this, event: &MouseDownEvent, _, cx| {827
cx.stop_propagation();828
this.drag_from = Some(event.position);829
}),830
)831
.on_click(cx.listener(|this, event: &ClickEvent, window, cx| {832
cx.stop_propagation();833
if event.click_count() == 2 {834
this.toggle_zoom(event.position(), window, cx);835
}836
}))837
.into_any_element()838
}839
840
fn thumbnail(&self, index: usize, cx: &mut Context<Self>) -> Stateful<Div> {841
let item = &self.items[index];842
let current = index == self.index;843
let path = self844
.app845
.read(cx)846
.directory847
.image(&item.image.url)848
.map(|entry| entry.path.clone());849
div()850
.id(ElementId::Name(format!("viewer-thumbnail-{index}").into()))851
.size(px(THUMBNAIL_SIZE + 2. * THUMBNAIL_BORDER))852
.flex_none()853
.flex()854
.items_center()855
.justify_center()856
.rounded(px(THUMBNAIL_RADIUS + THUMBNAIL_BORDER))857
.border_2()858
.border_color(if current {859
theme::accent()860
} else {861
transparent_black()862
})863
.cursor_pointer()864
.child(865
div()866
.size(px(THUMBNAIL_SIZE))867
.flex_none()868
.flex()869
.items_center()870
.justify_center()871
.overflow_hidden()872
.rounded(px(THUMBNAIL_RADIUS))873
.bg(white().opacity(0.08))874
.when(!current, |frame| frame.opacity(0.7))875
.map(|frame| match path {876
Some(path) => frame.child(877
img(path)878
.size_full()879
.object_fit(ObjectFit::Cover),880
),881
None => frame.child(symbol("image", 18., white().opacity(0.5))),882
}),883
)884
.on_click(cx.listener(move |this, _, window, cx| {885
cx.stop_propagation();886
this.jump(index, window, cx);887
}))888
}889
890
fn footer(&self, window: &Window, cx: &mut Context<Self>) -> Stateful<Div> {891
let width = f32::from(window.viewport_size().width);892
let range = thumbnail_window(893
self.index,894
self.items.len(),895
Self::thumbnail_capacity(window),896
);897
let caption = self898
.current()899
.map(|item| item.caption.clone())900
.unwrap_or_default();901
let status = self902
.notice903
.clone()904
.unwrap_or_else(|| counter_label(self.index, self.items.len()));905
v_flex()906
.id("viewer-footer")907
.absolute()908
.bottom_0()909
.left_0()910
.w_full()911
.h(px(FOOTER_HEIGHT))912
.pb(px(12.))913
.gap(px(4.))914
.items_center()915
.justify_end()916
.child(917
div()918
.w(px((width - 2. * SIDE_PADDING).clamp(0., CAPTION_MAX_WIDTH)))919
.h(px(CAPTION_HEIGHT))920
.flex_none()921
.truncate()922
.text_center()923
.text_size(px(13.))924
.text_color(white().opacity(0.9))925
.child(caption),926
)927
.child(928
div()929
.h(px(STATUS_HEIGHT))930
.flex_none()931
.text_size(px(12.))932
.text_color(white().opacity(0.6))933
.child(status),934
)935
.child(936
h_flex()937
.h(px(STRIP_HEIGHT))938
.flex_none()939
.gap(px(THUMBNAIL_GAP))940
.items_center()941
.children(range.map(|index| self.thumbnail(index, cx))),942
)943
.on_click(|_, _, cx| cx.stop_propagation())944
}945
}946
947
fn status_placeholder(text: &'static str) -> AnyElement {948
v_flex()949
.size_full()950
.gap(px(6.))951
.items_center()952
.justify_center()953
.child(symbol("image", 28., white().opacity(0.5)))954
.child(955
div()956
.text_size(px(12.))957
.text_color(white().opacity(0.6))958
.child(text),959
)960
.into_any_element()961
}962
963
fn loading_placeholder() -> AnyElement {964
status_placeholder("Loading image")965
}966
967
impl Render for ImageViewer {968
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {969
let layout = self.layout(window, cx);970
let stage = Self::stage_size(window);971
let has_previous = self.index > 0;972
let has_next = self.index + 1 < self.items.len();973
let picture = match layout {974
Some(layout) => self.picture(layout, cx),975
None if self.current_failed(cx) => status_placeholder("Image unavailable"),976
None => loading_placeholder(),977
};978
let header = self.header(layout, cx);979
let footer = self.footer(window, cx);980
div()981
.id("image-viewer")982
.key_context("ImageViewer")983
.track_focus(&self.focus_handle)984
.absolute()985
.top_0()986
.left_0()987
.size_full()988
.bg(rgba(BACKDROP))989
.occlude()990
.on_key_down(cx.listener(Self::on_key_down))991
.on_scroll_wheel(cx.listener(Self::on_wheel))992
.on_mouse_move(cx.listener(Self::on_mouse_move))993
.on_mouse_up(994
MouseButton::Left,995
cx.listener(|this, _, _, cx| this.end_drag(cx)),996
)997
.on_mouse_up_out(998
MouseButton::Left,999
cx.listener(|this, _, _, cx| this.end_drag(cx)),1000
)1001
.on_click(cx.listener(|_, _, _, cx| cx.emit(ImageViewerEvent::Close)))1002
.child(1003
div()1004
.absolute()1005
.top(px(HEADER_HEIGHT))1006
.left_0()1007
.w(px(stage.0))1008
.h(px(stage.1))1009
.overflow_hidden()1010
.child(picture)1011
.when(has_previous, |stage_element| {1012
stage_element.child(self.nav_button(1013
"viewer-previous",1014
"chevron_left",1015
true,1016
stage,1017
cx,1018
-1,1019
))1020
})1021
.when(has_next, |stage_element| {1022
stage_element.child(self.nav_button(1023
"viewer-next",1024
"chevron_right",1025
false,1026
stage,1027
cx,1028
1,1029
))1030
}),1031
)1032
.child(header)1033
.child(footer)1034
}1035
}@@ -17,7 +17,7 @@ const THUMB_WIDTH_COMPACT: f32 = 72.;
17
17
const THUMB_MIN_HEIGHT: f32 = 48.;
18
18
const THUMB_MAX_HEIGHT: f32 = 112.;
19
19
const THUMB_RADIUS: f32 = 6.;
20
const CLOSE_SIZE: f32 = 22.;
20
const CLOSE_SIZE: f32 = 28.;
21
21
const JOIN_CHIP_HEIGHT: f32 = 24.;
22
22
23
23
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
@@ -97,16 +97,16 @@ pub fn link_preview_card(
97
97
div()
98
98
.id(ElementId::Name(format!("{id}-close").into()))
99
99
.absolute()
100
.top(px(4.))
101
.right(px(4.))
100
.top(px(8.))
101
.right(px(8.))
102
102
.size(px(CLOSE_SIZE))
103
103
.flex()
104
104
.items_center()
105
105
.justify_center()
106
.rounded(px(6.))
106
.rounded(px(7.))
107
107
.cursor_pointer()
108
.hover(|button| button.bg(theme::row_hover()))
109
.child(icon(IconName::Close, 12., theme::text_muted()))
108
.hover(|button| button.bg(theme::popup_hover()))
109
.child(icon(IconName::Close, 14., theme::text_muted()))
110
110
.on_click(move |_, window, cx| {
111
111
cx.stop_propagation();
112
112
close(window, cx);
@@ -119,10 +119,10 @@ pub fn link_preview_card(
119
119
.when(compact, |card| card.w_full())
120
120
.when(!compact, |card| card.w(px(CARD_WIDTH)))
121
121
.max_w(relative(1.))
122
.gap(px(10.))
122
.gap(px(12.))
123
123
.p(px(8.))
124
124
.items_start()
125
.rounded(px(9.))
125
.rounded(px(10.))
126
126
.bg(theme::surface())
127
127
.cursor_pointer()
128
128
.hover(|card| card.bg(theme::row_hover()))
@@ -167,8 +167,8 @@ pub fn meeting_join_chip(id: String, url: String) -> AnyElement {
167
167
.flex_none()
168
168
.self_start()
169
169
.h(px(JOIN_CHIP_HEIGHT))
170
.px(px(10.))
171
.gap(px(5.))
170
.px(px(12.))
171
.gap(px(4.))
172
172
.items_center()
173
173
.rounded_full()
174
174
.bg(theme::accent())
@@ -17,7 +17,7 @@ const THUMB_WIDTH_COMPACT: f32 = 72.;17
const THUMB_MIN_HEIGHT: f32 = 48.;17
const THUMB_MIN_HEIGHT: f32 = 48.;18
const THUMB_MAX_HEIGHT: f32 = 112.;18
const THUMB_MAX_HEIGHT: f32 = 112.;19
const THUMB_RADIUS: f32 = 6.;19
const THUMB_RADIUS: f32 = 6.;20
const CLOSE_SIZE: f32 = 22.;20
const CLOSE_SIZE: f32 = 28.;21
const JOIN_CHIP_HEIGHT: f32 = 24.;21
const JOIN_CHIP_HEIGHT: f32 = 24.;22
22
23
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;23
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;@@ -97,16 +97,16 @@ pub fn link_preview_card(97
div()97
div()98
.id(ElementId::Name(format!("{id}-close").into()))98
.id(ElementId::Name(format!("{id}-close").into()))99
.absolute()99
.absolute()100
.top(px(4.))100
.top(px(8.))101
.right(px(4.))101
.right(px(8.))102
.size(px(CLOSE_SIZE))102
.size(px(CLOSE_SIZE))103
.flex()103
.flex()104
.items_center()104
.items_center()105
.justify_center()105
.justify_center()106
.rounded(px(6.))106
.rounded(px(7.))107
.cursor_pointer()107
.cursor_pointer()108
.hover(|button| button.bg(theme::row_hover()))108
.hover(|button| button.bg(theme::popup_hover()))109
.child(icon(IconName::Close, 12., theme::text_muted()))109
.child(icon(IconName::Close, 14., theme::text_muted()))110
.on_click(move |_, window, cx| {110
.on_click(move |_, window, cx| {111
cx.stop_propagation();111
cx.stop_propagation();112
close(window, cx);112
close(window, cx);@@ -119,10 +119,10 @@ pub fn link_preview_card(119
.when(compact, |card| card.w_full())119
.when(compact, |card| card.w_full())120
.when(!compact, |card| card.w(px(CARD_WIDTH)))120
.when(!compact, |card| card.w(px(CARD_WIDTH)))121
.max_w(relative(1.))121
.max_w(relative(1.))122
.gap(px(10.))122
.gap(px(12.))123
.p(px(8.))123
.p(px(8.))124
.items_start()124
.items_start()125
.rounded(px(9.))125
.rounded(px(10.))126
.bg(theme::surface())126
.bg(theme::surface())127
.cursor_pointer()127
.cursor_pointer()128
.hover(|card| card.bg(theme::row_hover()))128
.hover(|card| card.bg(theme::row_hover()))@@ -167,8 +167,8 @@ pub fn meeting_join_chip(id: String, url: String) -> AnyElement {167
.flex_none()167
.flex_none()168
.self_start()168
.self_start()169
.h(px(JOIN_CHIP_HEIGHT))169
.h(px(JOIN_CHIP_HEIGHT))170
.px(px(10.))170
.px(px(12.))171
.gap(px(5.))171
.gap(px(4.))172
.items_center()172
.items_center()173
.rounded_full()173
.rounded_full()174
.bg(theme::accent())174
.bg(theme::accent())@@ -5,7 +5,7 @@ use gpui_kit::*;
5
5
use std::time::Duration;
6
6
7
7
use super::adaptive_card::cards_view;
8
use super::attachments::{FileActions, attachments_view, message_body};
8
use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};
9
9
use super::avatar::{bot_avatar, person_avatar};
10
10
use super::link_preview::{link_preview_card, meeting_join_chip};
11
11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
@@ -24,8 +24,8 @@ use crate::theme;
24
24
25
25
pub type RowAction = Option<Box<dyn Fn(&mut App)>>;
26
26
27
const AVATAR_SIZE: f32 = 28.;
28
const AVATAR_GAP: f32 = 8.;
27
pub(super) const AVATAR_SIZE: f32 = 28.;
28
pub(super) const AVATAR_GAP: f32 = 8.;
29
29
const SERIES_START_GAP: f32 = 8.;
30
30
pub(super) const BODY_SIZE: f32 = 13.5;
31
31
const MAX_WIDTH_RATIO: f32 = 0.7;
@@ -54,6 +54,7 @@ pub struct RowActions {
54
54
pub react: Option<PickHandler>,
55
55
pub reaction_controls: Option<ReactionControls>,
56
56
pub files: Option<FileActions>,
57
pub open_image: Option<ImageOpen>,
57
58
pub highlighted: bool,
58
59
pub saved: bool,
59
60
pub translation: Option<TranslationActions>,
@@ -62,13 +63,13 @@ pub struct RowActions {
62
63
const TOOLBAR_LIFT: f32 = 22.;
63
64
64
65
fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {
65
h_flex().w_full().justify_center().mt(px(14.)).mb(px(6.)).child(
66
h_flex().w_full().justify_center().mt(px(12.)).mb(px(6.)).child(
66
67
div()
67
.h(px(22.))
68
.px(px(10.))
68
.h(px(24.))
69
.px(px(8.))
69
70
.flex()
70
71
.items_center()
71
.rounded(px(11.))
72
.rounded(px(12.))
72
73
.bg(fill)
73
74
.text_size(px(11.))
74
75
.text_color(text_color)
@@ -103,8 +104,8 @@ fn bubble(
103
104
.rounded_tr(px(corners.top_right))
104
105
.rounded_br(px(corners.bottom_right))
105
106
.rounded_bl(px(corners.bottom_left))
106
.px(px(11.))
107
.py(px(7.))
107
.px(px(12.))
108
.py(px(8.))
108
109
.text_size(px(BODY_SIZE))
109
110
.line_height(relative(1.45));
110
111
if row.deleted {
@@ -161,6 +162,7 @@ fn bubble(
161
162
&format!("message-{index}"),
162
163
own,
163
164
directory,
165
extras.open_image.as_ref(),
164
166
cx,
165
167
));
166
168
}
@@ -172,6 +174,7 @@ fn bubble(
172
174
&format!("message-{index}"),
173
175
directory,
174
176
extras.files.as_ref(),
177
extras.open_image.as_ref(),
175
178
));
176
179
content = content.children(
177
180
row.meeting_link
@@ -225,8 +228,8 @@ fn bubble(
225
228
element = element.child(
226
229
div()
227
230
.absolute()
228
.right(px(9.))
229
.bottom(px(5.))
231
.right(px(8.))
232
.bottom(px(4.))
230
233
.child(bubble_meta(row, own, saved)),
231
234
);
232
235
}
@@ -259,6 +262,7 @@ struct BubbleExtras {
259
262
react: Option<PickHandler>,
260
263
controls: Option<ReactionControls>,
261
264
files: Option<FileActions>,
265
open_image: Option<ImageOpen>,
262
266
saved: bool,
263
267
translation: Option<TranslationActions>,
264
268
}
@@ -369,7 +373,7 @@ pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {
369
373
div()
370
374
.id(ElementId::Name(format!("row-{index}").into()))
371
375
.w_full()
372
.px(px(24.))
376
.px(px(20.))
373
377
.pt(px(SERIES_START_GAP))
374
378
.child(pulse("skeleton", line))
375
379
.into_any_element()
@@ -560,6 +564,7 @@ pub fn render_message_row(
560
564
react,
561
565
reaction_controls,
562
566
files,
567
open_image,
563
568
highlighted,
564
569
saved,
565
570
translation,
@@ -571,6 +576,7 @@ pub fn render_message_row(
571
576
react,
572
577
controls: reaction_controls,
573
578
files,
579
open_image,
574
580
saved,
575
581
translation,
576
582
};
@@ -580,7 +586,7 @@ pub fn render_message_row(
580
586
} else {
581
587
px(SERIES_START_GAP)
582
588
};
583
let mut container = v_flex().w_full().px(px(24.));
589
let mut container = v_flex().w_full().px(px(20.));
584
590
if let Some(day) = &row.day_header {
585
591
container = container.child(day_separator(day));
586
592
}
@@ -5,7 +5,7 @@ use gpui_kit::*;5
use std::time::Duration;5
use std::time::Duration;6
6
7
use super::adaptive_card::cards_view;7
use super::adaptive_card::cards_view;8
use super::attachments::{FileActions, attachments_view, message_body};8
use super::attachments::{FileActions, ImageOpen, attachments_view, message_body};9
use super::avatar::{bot_avatar, person_avatar};9
use super::avatar::{bot_avatar, person_avatar};10
use super::link_preview::{link_preview_card, meeting_join_chip};10
use super::link_preview::{link_preview_card, meeting_join_chip};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};@@ -24,8 +24,8 @@ use crate::theme;24
24
25
pub type RowAction = Option<Box<dyn Fn(&mut App)>>;25
pub type RowAction = Option<Box<dyn Fn(&mut App)>>;26
26
27
const AVATAR_SIZE: f32 = 28.;27
pub(super) const AVATAR_SIZE: f32 = 28.;28
const AVATAR_GAP: f32 = 8.;28
pub(super) const AVATAR_GAP: f32 = 8.;29
const SERIES_START_GAP: f32 = 8.;29
const SERIES_START_GAP: f32 = 8.;30
pub(super) const BODY_SIZE: f32 = 13.5;30
pub(super) const BODY_SIZE: f32 = 13.5;31
const MAX_WIDTH_RATIO: f32 = 0.7;31
const MAX_WIDTH_RATIO: f32 = 0.7;@@ -54,6 +54,7 @@ pub struct RowActions {54
pub react: Option<PickHandler>,54
pub react: Option<PickHandler>,55
pub reaction_controls: Option<ReactionControls>,55
pub reaction_controls: Option<ReactionControls>,56
pub files: Option<FileActions>,56
pub files: Option<FileActions>,57
pub open_image: Option<ImageOpen>,57
pub highlighted: bool,58
pub highlighted: bool,58
pub saved: bool,59
pub saved: bool,59
pub translation: Option<TranslationActions>,60
pub translation: Option<TranslationActions>,@@ -62,13 +63,13 @@ pub struct RowActions {62
const TOOLBAR_LIFT: f32 = 22.;63
const TOOLBAR_LIFT: f32 = 22.;63
64
64
fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {65
fn separator_pill(label: &str, fill: Hsla, text_color: Hsla) -> Div {65
h_flex().w_full().justify_center().mt(px(14.)).mb(px(6.)).child(66
h_flex().w_full().justify_center().mt(px(12.)).mb(px(6.)).child(66
div()67
div()67
.h(px(22.))68
.h(px(24.))68
.px(px(10.))69
.px(px(8.))69
.flex()70
.flex()70
.items_center()71
.items_center()71
.rounded(px(11.))72
.rounded(px(12.))72
.bg(fill)73
.bg(fill)73
.text_size(px(11.))74
.text_size(px(11.))74
.text_color(text_color)75
.text_color(text_color)@@ -103,8 +104,8 @@ fn bubble(103
.rounded_tr(px(corners.top_right))104
.rounded_tr(px(corners.top_right))104
.rounded_br(px(corners.bottom_right))105
.rounded_br(px(corners.bottom_right))105
.rounded_bl(px(corners.bottom_left))106
.rounded_bl(px(corners.bottom_left))106
.px(px(11.))107
.px(px(12.))107
.py(px(7.))108
.py(px(8.))108
.text_size(px(BODY_SIZE))109
.text_size(px(BODY_SIZE))109
.line_height(relative(1.45));110
.line_height(relative(1.45));110
if row.deleted {111
if row.deleted {@@ -161,6 +162,7 @@ fn bubble(161
&format!("message-{index}"),162
&format!("message-{index}"),162
own,163
own,163
directory,164
directory,165
extras.open_image.as_ref(),164
cx,166
cx,165
));167
));166
}168
}@@ -172,6 +174,7 @@ fn bubble(172
&format!("message-{index}"),174
&format!("message-{index}"),173
directory,175
directory,174
extras.files.as_ref(),176
extras.files.as_ref(),177
extras.open_image.as_ref(),175
));178
));176
content = content.children(179
content = content.children(177
row.meeting_link180
row.meeting_link@@ -225,8 +228,8 @@ fn bubble(225
element = element.child(228
element = element.child(226
div()229
div()227
.absolute()230
.absolute()228
.right(px(9.))231
.right(px(8.))229
.bottom(px(5.))232
.bottom(px(4.))230
.child(bubble_meta(row, own, saved)),233
.child(bubble_meta(row, own, saved)),231
);234
);232
}235
}@@ -259,6 +262,7 @@ struct BubbleExtras {259
react: Option<PickHandler>,262
react: Option<PickHandler>,260
controls: Option<ReactionControls>,263
controls: Option<ReactionControls>,261
files: Option<FileActions>,264
files: Option<FileActions>,265
open_image: Option<ImageOpen>,262
saved: bool,266
saved: bool,263
translation: Option<TranslationActions>,267
translation: Option<TranslationActions>,264
}268
}@@ -369,7 +373,7 @@ pub fn render_skeleton_row(skeleton: &Skeleton, index: usize) -> AnyElement {369
div()373
div()370
.id(ElementId::Name(format!("row-{index}").into()))374
.id(ElementId::Name(format!("row-{index}").into()))371
.w_full()375
.w_full()372
.px(px(24.))376
.px(px(20.))373
.pt(px(SERIES_START_GAP))377
.pt(px(SERIES_START_GAP))374
.child(pulse("skeleton", line))378
.child(pulse("skeleton", line))375
.into_any_element()379
.into_any_element()@@ -560,6 +564,7 @@ pub fn render_message_row(560
react,564
react,561
reaction_controls,565
reaction_controls,562
files,566
files,567
open_image,563
highlighted,568
highlighted,564
saved,569
saved,565
translation,570
translation,@@ -571,6 +576,7 @@ pub fn render_message_row(571
react,576
react,572
controls: reaction_controls,577
controls: reaction_controls,573
files,578
files,579
open_image,574
saved,580
saved,575
translation,581
translation,576
};582
};@@ -580,7 +586,7 @@ pub fn render_message_row(580
} else {586
} else {581
px(SERIES_START_GAP)587
px(SERIES_START_GAP)582
};588
};583
let mut container = v_flex().w_full().px(px(24.));589
let mut container = v_flex().w_full().px(px(20.));584
if let Some(day) = &row.day_header {590
if let Some(day) = &row.day_header {585
container = container.child(day_separator(day));591
container = container.child(day_separator(day));586
}592
}@@ -27,6 +27,7 @@ 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 image_viewer;
30
31
pub mod join_dialog;
31
32
pub mod link_preview;
32
33
pub mod fun_picker;
@@ -27,6 +27,7 @@ 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 image_viewer;30
pub mod join_dialog;31
pub mod join_dialog;31
pub mod link_preview;32
pub mod link_preview;32
pub mod fun_picker;33
pub mod fun_picker;@@ -435,7 +435,7 @@ impl NewChatDraft {
435
435
.id(ElementId::Name(format!("new-chat-chip-{index}").into()))
436
436
.h(px(26.))
437
437
.pl(px(3.))
438
.pr(px(6.))
438
.pr(px(4.))
439
439
.gap(px(6.))
440
440
.items_center()
441
441
.rounded(px(13.))
@@ -459,7 +459,7 @@ impl NewChatDraft {
459
459
.id(ElementId::Name(
460
460
format!("new-chat-chip-remove-{index}").into(),
461
461
))
462
.size(px(16.))
462
.size(px(18.))
463
463
.flex()
464
464
.items_center()
465
465
.justify_center()
@@ -490,7 +490,7 @@ impl NewChatDraft {
490
490
.id(ElementId::Name(format!("new-chat-result-{index}").into()))
491
491
.px(px(6.))
492
492
.h(px(POPUP_ROW_HEIGHT))
493
.gap(px(10.))
493
.gap(px(8.))
494
494
.items_center()
495
495
.rounded(px(6.))
496
496
.cursor_pointer()
@@ -628,10 +628,8 @@ impl NewChatDraft {
628
628
.flex_none()
629
629
.px(px(20.))
630
630
.py(px(8.))
631
.gap(px(10.))
631
.gap(px(8.))
632
632
.items_center()
633
.border_b_1()
634
.border_color(theme::border())
635
633
.child(
636
634
div()
637
635
.text_size(px(14.))
@@ -642,16 +640,16 @@ impl NewChatDraft {
642
640
div()
643
641
.flex_1()
644
642
.h(px(32.))
645
.px(px(10.))
643
.px(px(12.))
646
644
.flex()
647
645
.items_center()
648
646
.rounded(px(8.))
649
.bg(theme::surface())
647
.bg(theme::surface_raised())
650
648
.border_1()
651
649
.border_color(if focused {
652
650
theme::accent()
653
651
} else {
654
theme::border_strong()
652
transparent_black()
655
653
})
656
654
.child(
657
655
div()
@@ -435,7 +435,7 @@ impl NewChatDraft {435
.id(ElementId::Name(format!("new-chat-chip-{index}").into()))435
.id(ElementId::Name(format!("new-chat-chip-{index}").into()))436
.h(px(26.))436
.h(px(26.))437
.pl(px(3.))437
.pl(px(3.))438
.pr(px(6.))438
.pr(px(4.))439
.gap(px(6.))439
.gap(px(6.))440
.items_center()440
.items_center()441
.rounded(px(13.))441
.rounded(px(13.))@@ -459,7 +459,7 @@ impl NewChatDraft {459
.id(ElementId::Name(459
.id(ElementId::Name(460
format!("new-chat-chip-remove-{index}").into(),460
format!("new-chat-chip-remove-{index}").into(),461
))461
))462
.size(px(16.))462
.size(px(18.))463
.flex()463
.flex()464
.items_center()464
.items_center()465
.justify_center()465
.justify_center()@@ -490,7 +490,7 @@ impl NewChatDraft {490
.id(ElementId::Name(format!("new-chat-result-{index}").into()))490
.id(ElementId::Name(format!("new-chat-result-{index}").into()))491
.px(px(6.))491
.px(px(6.))492
.h(px(POPUP_ROW_HEIGHT))492
.h(px(POPUP_ROW_HEIGHT))493
.gap(px(10.))493
.gap(px(8.))494
.items_center()494
.items_center()495
.rounded(px(6.))495
.rounded(px(6.))496
.cursor_pointer()496
.cursor_pointer()@@ -628,10 +628,8 @@ impl NewChatDraft {628
.flex_none()628
.flex_none()629
.px(px(20.))629
.px(px(20.))630
.py(px(8.))630
.py(px(8.))631
.gap(px(10.))631
.gap(px(8.))632
.items_center()632
.items_center()633
.border_b_1()634
.border_color(theme::border())635
.child(633
.child(636
div()634
div()637
.text_size(px(14.))635
.text_size(px(14.))@@ -642,16 +640,16 @@ impl NewChatDraft {642
div()640
div()643
.flex_1()641
.flex_1()644
.h(px(32.))642
.h(px(32.))645
.px(px(10.))643
.px(px(12.))646
.flex()644
.flex()647
.items_center()645
.items_center()648
.rounded(px(8.))646
.rounded(px(8.))649
.bg(theme::surface())647
.bg(theme::surface_raised())650
.border_1()648
.border_1()651
.border_color(if focused {649
.border_color(if focused {652
theme::accent()650
theme::accent()653
} else {651
} else {654
theme::border_strong()652
transparent_black()655
})653
})656
.child(654
.child(657
div()655
div()@@ -7,9 +7,9 @@ use super::message_actions::Action;
7
7
use super::widgets::icon;
8
8
use crate::theme;
9
9
10
const BANNER_HEIGHT: f32 = 36.;
10
const BANNER_HEIGHT: f32 = 40.;
11
11
const BANNER_PADDING: f32 = 12.;
12
const BUTTON_SIZE: f32 = 24.;
12
const BUTTON_SIZE: f32 = 28.;
13
13
const FALLBACK_PREVIEW: &str = "Pinned message";
14
14
15
15
pub struct PinBannerData {
@@ -45,7 +45,7 @@ fn icon_button(id: &'static str, glyph: IconName, action: Action) -> Stateful<Di
45
45
.flex_none()
46
46
.items_center()
47
47
.justify_center()
48
.rounded(px(6.))
48
.rounded(px(7.))
49
49
.cursor_pointer()
50
50
.hover(|button| button.bg(theme::popup_hover()))
51
51
.child(icon(glyph, 14., theme::text_muted()))
@@ -73,9 +73,10 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE
73
73
.group("pin-banner")
74
74
.h(px(BANNER_HEIGHT))
75
75
.flex_none()
76
.mx(px(16.))
77
.mb(px(4.))
78
.px(px(BANNER_PADDING))
76
.mx(px(20.))
77
.mb(px(8.))
78
.pl(px(BANNER_PADDING))
79
.pr(px(6.))
79
80
.gap(px(8.))
80
81
.items_center()
81
82
.rounded(px(8.))
@@ -7,9 +7,9 @@ use super::message_actions::Action;7
use super::widgets::icon;7
use super::widgets::icon;8
use crate::theme;8
use crate::theme;9
9
10
const BANNER_HEIGHT: f32 = 36.;10
const BANNER_HEIGHT: f32 = 40.;11
const BANNER_PADDING: f32 = 12.;11
const BANNER_PADDING: f32 = 12.;12
const BUTTON_SIZE: f32 = 24.;12
const BUTTON_SIZE: f32 = 28.;13
const FALLBACK_PREVIEW: &str = "Pinned message";13
const FALLBACK_PREVIEW: &str = "Pinned message";14
14
15
pub struct PinBannerData {15
pub struct PinBannerData {@@ -45,7 +45,7 @@ fn icon_button(id: &'static str, glyph: IconName, action: Action) -> Stateful<Di45
.flex_none()45
.flex_none()46
.items_center()46
.items_center()47
.justify_center()47
.justify_center()48
.rounded(px(6.))48
.rounded(px(7.))49
.cursor_pointer()49
.cursor_pointer()50
.hover(|button| button.bg(theme::popup_hover()))50
.hover(|button| button.bg(theme::popup_hover()))51
.child(icon(glyph, 14., theme::text_muted()))51
.child(icon(glyph, 14., theme::text_muted()))@@ -73,9 +73,10 @@ pub fn render_pin_banner(data: PinBannerData, actions: PinBannerActions) -> AnyE73
.group("pin-banner")73
.group("pin-banner")74
.h(px(BANNER_HEIGHT))74
.h(px(BANNER_HEIGHT))75
.flex_none()75
.flex_none()76
.mx(px(16.))76
.mx(px(20.))77
.mb(px(4.))77
.mb(px(8.))78
.px(px(BANNER_PADDING))78
.pl(px(BANNER_PADDING))79
.pr(px(6.))79
.gap(px(8.))80
.gap(px(8.))80
.items_center()81
.items_center()81
.rounded(px(8.))82
.rounded(px(8.))@@ -91,6 +91,7 @@ fn message_content(
91
91
&format!("message-{index}"),
92
92
false,
93
93
directory,
94
actions.open_image.as_ref(),
94
95
cx,
95
96
)),
96
97
);
@@ -103,6 +104,7 @@ fn message_content(
103
104
&format!("message-{index}"),
104
105
directory,
105
106
actions.files.as_ref(),
107
actions.open_image.as_ref(),
106
108
));
107
109
content = content.children(
108
110
row.meeting_link
@@ -385,7 +387,7 @@ pub fn render_post(
385
387
card = card.children(reply_footer(index, open_reply, reply_editor));
386
388
div()
387
389
.w_full()
388
.px(px(24.))
390
.px(px(20.))
389
391
.pt(px(CARD_GAP))
390
392
.child(card)
391
393
.into_any_element()
@@ -91,6 +91,7 @@ fn message_content(91
&format!("message-{index}"),91
&format!("message-{index}"),92
false,92
false,93
directory,93
directory,94
actions.open_image.as_ref(),94
cx,95
cx,95
)),96
)),96
);97
);@@ -103,6 +104,7 @@ fn message_content(103
&format!("message-{index}"),104
&format!("message-{index}"),104
directory,105
directory,105
actions.files.as_ref(),106
actions.files.as_ref(),107
actions.open_image.as_ref(),106
));108
));107
content = content.children(109
content = content.children(108
row.meeting_link110
row.meeting_link@@ -385,7 +387,7 @@ pub fn render_post(385
card = card.children(reply_footer(index, open_reply, reply_editor));387
card = card.children(reply_footer(index, open_reply, reply_editor));386
div()388
div()387
.w_full()389
.w_full()388
.px(px(24.))390
.px(px(20.))389
.pt(px(CARD_GAP))391
.pt(px(CARD_GAP))390
.child(card)392
.child(card)391
.into_any_element()393
.into_any_element()@@ -3,6 +3,7 @@ use gpui_kit::component::{tooltip::Tooltip, v_flex};
3
3
use gpui_kit::prelude::FluentBuilder as _;
4
4
use gpui_kit::*;
5
5
6
use super::shell::ISLAND_GAP;
6
7
use super::shortcuts::keys_for_label;
7
8
use super::sidebar::{SidebarTab, SidebarView};
8
9
use super::widgets::icon;
@@ -12,9 +13,9 @@ use crate::format;
12
13
use crate::sidebar_model::{any_unread_channel, unread_chat_count};
13
14
use crate::theme;
14
15
15
pub const RAIL_WIDTH: f32 = 56.;
16
const ITEM_WIDTH: f32 = 44.;
17
const ITEM_HEIGHT: f32 = 48.;
16
pub const RAIL_WIDTH: f32 = ITEM_WIDTH + 2. * ISLAND_GAP;
17
const ITEM_WIDTH: f32 = 48.;
18
const ITEM_HEIGHT: f32 = 52.;
18
19
const ICON_SIZE: f32 = 20.;
19
20
20
21
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -137,8 +138,8 @@ impl RailView {
137
138
.flex_none()
138
139
.items_center()
139
140
.justify_center()
140
.gap(px(3.))
141
.rounded(px(8.))
141
.gap(px(4.))
142
.rounded(px(10.))
142
143
.cursor_pointer()
143
144
.when(active, |button| button.bg(theme::surface_raised()))
144
145
.when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))
@@ -164,15 +165,15 @@ fn badge(badge: RailBadge) -> Div {
164
165
RailBadge::None => div(),
165
166
RailBadge::Dot => div()
166
167
.absolute()
167
.top(px(6.))
168
.right(px(9.))
168
.top(px(8.))
169
.left(px(31.))
169
170
.size(px(7.))
170
171
.rounded_full()
171
172
.bg(theme::accent()),
172
173
RailBadge::Count(count) => div()
173
174
.absolute()
174
.top(px(3.))
175
.right(px(5.))
175
.top(px(5.))
176
.left(px(28.))
176
177
.min_w(px(16.))
177
178
.h(px(16.))
178
179
.px(px(4.))
@@ -205,9 +206,8 @@ impl Render for RailView {
205
206
.h_full()
206
207
.flex_none()
207
208
.items_center()
208
.gap(px(4.))
209
.pt(px(2.))
210
.mr(px(-6.))
209
.gap(px(2.))
210
.pt(px(0.))
211
211
.children(
212
212
rail_items(activity_unread, unread_chats as usize, channel_dot)
213
213
.iter()
@@ -3,6 +3,7 @@ use gpui_kit::component::{tooltip::Tooltip, v_flex};3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;4
use gpui_kit::*;5
5
6
use super::shell::ISLAND_GAP;6
use super::shortcuts::keys_for_label;7
use super::shortcuts::keys_for_label;7
use super::sidebar::{SidebarTab, SidebarView};8
use super::sidebar::{SidebarTab, SidebarView};8
use super::widgets::icon;9
use super::widgets::icon;@@ -12,9 +13,9 @@ use crate::format;12
use crate::sidebar_model::{any_unread_channel, unread_chat_count};13
use crate::sidebar_model::{any_unread_channel, unread_chat_count};13
use crate::theme;14
use crate::theme;14
15
15
pub const RAIL_WIDTH: f32 = 56.;16
pub const RAIL_WIDTH: f32 = ITEM_WIDTH + 2. * ISLAND_GAP;16
const ITEM_WIDTH: f32 = 44.;17
const ITEM_WIDTH: f32 = 48.;17
const ITEM_HEIGHT: f32 = 48.;18
const ITEM_HEIGHT: f32 = 52.;18
const ICON_SIZE: f32 = 20.;19
const ICON_SIZE: f32 = 20.;19
20
20
#[derive(Debug, Clone, Copy, PartialEq, Eq)]21
#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -137,8 +138,8 @@ impl RailView {137
.flex_none()138
.flex_none()138
.items_center()139
.items_center()139
.justify_center()140
.justify_center()140
.gap(px(3.))141
.gap(px(4.))141
.rounded(px(8.))142
.rounded(px(10.))142
.cursor_pointer()143
.cursor_pointer()143
.when(active, |button| button.bg(theme::surface_raised()))144
.when(active, |button| button.bg(theme::surface_raised()))144
.when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))145
.when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))@@ -164,15 +165,15 @@ fn badge(badge: RailBadge) -> Div {164
RailBadge::None => div(),165
RailBadge::None => div(),165
RailBadge::Dot => div()166
RailBadge::Dot => div()166
.absolute()167
.absolute()167
.top(px(6.))168
.top(px(8.))168
.right(px(9.))169
.left(px(31.))169
.size(px(7.))170
.size(px(7.))170
.rounded_full()171
.rounded_full()171
.bg(theme::accent()),172
.bg(theme::accent()),172
RailBadge::Count(count) => div()173
RailBadge::Count(count) => div()173
.absolute()174
.absolute()174
.top(px(3.))175
.top(px(5.))175
.right(px(5.))176
.left(px(28.))176
.min_w(px(16.))177
.min_w(px(16.))177
.h(px(16.))178
.h(px(16.))178
.px(px(4.))179
.px(px(4.))@@ -205,9 +206,8 @@ impl Render for RailView {205
.h_full()206
.h_full()206
.flex_none()207
.flex_none()207
.items_center()208
.items_center()208
.gap(px(4.))209
.gap(px(2.))209
.pt(px(2.))210
.pt(px(0.))210
.mr(px(-6.))211
.children(211
.children(212
rail_items(activity_unread, unread_chats as usize, channel_dot)212
rail_items(activity_unread, unread_chats as usize, channel_dot)213
.iter()213
.iter()@@ -173,7 +173,7 @@ fn tab_button(tab: &ReactionTab, active: bool, select_tab: SelectTab) -> Statefu
173
173
format!("reaction-tab-{}", glyph.as_deref().unwrap_or("all")).into(),
174
174
))
175
175
.h(px(TAB_HEIGHT))
176
.px(px(10.))
176
.px(px(12.))
177
177
.gap(px(4.))
178
178
.items_center()
179
179
.rounded(px(7.))
@@ -198,7 +198,7 @@ fn entry_row(entry: &ReactionEntry, directory: &Directory) -> Div {
198
198
h_flex()
199
199
.h(px(ENTRY_HEIGHT))
200
200
.px(px(8.))
201
.gap(px(10.))
201
.gap(px(8.))
202
202
.items_center()
203
203
.child(person_avatar(
204
204
directory,
@@ -173,7 +173,7 @@ fn tab_button(tab: &ReactionTab, active: bool, select_tab: SelectTab) -> Statefu173
format!("reaction-tab-{}", glyph.as_deref().unwrap_or("all")).into(),173
format!("reaction-tab-{}", glyph.as_deref().unwrap_or("all")).into(),174
))174
))175
.h(px(TAB_HEIGHT))175
.h(px(TAB_HEIGHT))176
.px(px(10.))176
.px(px(12.))177
.gap(px(4.))177
.gap(px(4.))178
.items_center()178
.items_center()179
.rounded(px(7.))179
.rounded(px(7.))@@ -198,7 +198,7 @@ fn entry_row(entry: &ReactionEntry, directory: &Directory) -> Div {198
h_flex()198
h_flex()199
.h(px(ENTRY_HEIGHT))199
.h(px(ENTRY_HEIGHT))200
.px(px(8.))200
.px(px(8.))201
.gap(px(10.))201
.gap(px(8.))202
.items_center()202
.items_center()203
.child(person_avatar(203
.child(person_avatar(204
directory,204
directory,@@ -54,7 +54,7 @@ impl SavedPanel {
54
54
.h(px(52.))
55
55
.flex_none()
56
56
.pl(px(16.))
57
.pr(px(10.))
57
.pr(px(12.))
58
58
.gap(px(8.))
59
59
.items_center()
60
60
.child(
@@ -93,7 +93,7 @@ impl SavedPanel {
93
93
.relative()
94
94
.mx(px(6.))
95
95
.p(px(10.))
96
.gap(px(10.))
96
.gap(px(12.))
97
97
.items_start()
98
98
.rounded(px(8.))
99
99
.cursor_pointer()
@@ -108,7 +108,7 @@ impl SavedPanel {
108
108
v_flex()
109
109
.flex_1()
110
110
.min_w_0()
111
.gap(px(3.))
111
.gap(px(4.))
112
112
.child(
113
113
h_flex()
114
114
.gap(px(6.))
@@ -54,7 +54,7 @@ impl SavedPanel {54
.h(px(52.))54
.h(px(52.))55
.flex_none()55
.flex_none()56
.pl(px(16.))56
.pl(px(16.))57
.pr(px(10.))57
.pr(px(12.))58
.gap(px(8.))58
.gap(px(8.))59
.items_center()59
.items_center()60
.child(60
.child(@@ -93,7 +93,7 @@ impl SavedPanel {93
.relative()93
.relative()94
.mx(px(6.))94
.mx(px(6.))95
.p(px(10.))95
.p(px(10.))96
.gap(px(10.))96
.gap(px(12.))97
.items_start()97
.items_start()98
.rounded(px(8.))98
.rounded(px(8.))99
.cursor_pointer()99
.cursor_pointer()@@ -108,7 +108,7 @@ impl SavedPanel {108
v_flex()108
v_flex()109
.flex_1()109
.flex_1()110
.min_w_0()110
.min_w_0()111
.gap(px(3.))111
.gap(px(4.))112
.child(112
.child(113
h_flex()113
h_flex()114
.gap(px(6.))114
.gap(px(6.))@@ -1,3 +1,5 @@
1
use std::sync::Arc;
2
1
3
use gpui_kit::component::{h_flex, v_flex};
2
4
use gpui_kit::*;
3
5
@@ -8,6 +10,7 @@ use super::call_view::render_call_view;
8
10
use super::conversation::{ConversationView, ReplyToHovered};
9
11
use super::dialog_overlay::render_task_dialog;
10
12
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
13
use super::image_viewer::{ImageViewer, ImageViewerEvent};
11
14
use super::profile_card::{ProfileCard, ProfileCardEvent};
12
15
use super::rail::RailView;
13
16
use super::saved_panel::{SavedPanel, SavedPanelEvent};
@@ -28,6 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
28
31
use crate::call::{CallMedia, CallWindows};
29
32
use crate::embedded_web::{Overlays, RootFocus};
30
33
use crate::notice::NoticeAction;
34
use crate::user_activity::{self, UserInput};
31
35
use crate::notify::{NotificationCenter, selection_for};
32
36
use crate::sidebar_model::Step;
33
37
use crate::theme;
@@ -55,6 +59,10 @@ pub struct Startup {
55
59
56
60
pub const ISLAND_GAP: f32 = 6.;
57
61
62
pub struct UserInputHandle(pub Arc<UserInput>);
63
64
impl Global for UserInputHandle {}
65
58
66
pub struct AppShell {
59
67
state: Entity<AppState>,
60
68
rail: Entity<RailView>,
@@ -65,12 +73,14 @@ pub struct AppShell {
65
73
notifications: Entity<NotificationCenter>,
66
74
_call_windows: Entity<CallWindows>,
67
75
forward_dialog: Option<Entity<ForwardDialog>>,
76
image_viewer: Option<Entity<ImageViewer>>,
68
77
status_dialog: Option<Entity<StatusMessageDialog>>,
69
78
shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
70
79
profile_card: Option<Entity<ProfileCard>>,
71
80
focus_handle: FocusHandle,
72
81
open_target: Option<OpenTarget>,
73
82
update: UpdateStatus,
83
user_input: Arc<UserInput>,
74
84
_subscription: Subscription,
75
85
_call_media_observation: Subscription,
76
86
_panel_subscriptions: [Subscription; 2],
@@ -134,6 +144,9 @@ impl AppShell {
134
144
if matches!(event, AppEvent::Forward) {
135
145
this.open_forward_dialog(window, cx);
136
146
}
147
if matches!(event, AppEvent::ImageViewer) {
148
this.open_image_viewer(window, cx);
149
}
137
150
if matches!(event, AppEvent::StatusMessage) {
138
151
this.open_status_dialog(window, cx);
139
152
}
@@ -151,7 +164,9 @@ impl AppShell {
151
164
cx.set_global(RootFocus(focus_handle.clone()));
152
165
let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));
153
166
let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));
167
let user_input = cx.global::<UserInputHandle>().0.clone();
154
168
let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {
169
this.user_input.touch();
155
170
if event.keystroke.key == "escape" {
156
171
this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));
157
172
}
@@ -173,12 +188,14 @@ impl AppShell {
173
188
notifications,
174
189
_call_windows: call_windows,
175
190
forward_dialog: None,
191
image_viewer: None,
176
192
status_dialog: None,
177
193
shortcuts_dialog: None,
178
194
profile_card: None,
179
195
focus_handle,
180
196
open_target,
181
197
update: UpdateStatus::UpToDate,
198
user_input,
182
199
_subscription: subscription,
183
200
_call_media_observation: call_media_observation,
184
201
_panel_subscriptions: panel_subscriptions,
@@ -306,10 +323,11 @@ impl AppShell {
306
323
cx: &mut Context<Self>,
307
324
) {
308
325
if self.switcher.take().is_some() {
309
window.focus(&self.focus_handle, cx);
326
self.restore_focus(window, cx);
310
327
cx.notify();
311
328
return;
312
329
}
330
self.close_image_viewer(window, cx);
313
331
let candidates = candidates_from(self.state.read(cx));
314
332
let app = self.state.clone();
315
333
let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));
@@ -335,7 +353,7 @@ impl AppShell {
335
353
SwitcherEvent::Close => {}
336
354
}
337
355
this.switcher = None;
338
window.focus(&this.focus_handle, cx);
356
this.restore_focus(window, cx);
339
357
cx.notify();
340
358
},
341
359
)
@@ -365,6 +383,7 @@ impl AppShell {
365
383
{
366
384
return;
367
385
}
386
self.close_image_viewer(window, cx);
368
387
self.switcher = None;
369
388
let app = self.state.clone();
370
389
let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));
@@ -373,7 +392,7 @@ impl AppShell {
373
392
window,
374
393
|this, _, _: &StatusMessageDialogEvent, window, cx| {
375
394
this.status_dialog = None;
376
window.focus(&this.focus_handle, cx);
395
this.restore_focus(window, cx);
377
396
cx.notify();
378
397
},
379
398
)
@@ -384,10 +403,11 @@ impl AppShell {
384
403
385
404
fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
386
405
if self.shortcuts_dialog.take().is_some() {
387
window.focus(&self.focus_handle, cx);
406
self.restore_focus(window, cx);
388
407
cx.notify();
389
408
return;
390
409
}
410
self.close_image_viewer(window, cx);
391
411
self.switcher = None;
392
412
let dialog = cx.new(|cx| ShortcutsDialog::new(window, cx));
393
413
cx.subscribe_in(
@@ -395,7 +415,7 @@ impl AppShell {
395
415
window,
396
416
|this, _, _: &ShortcutsDialogEvent, window, cx| {
397
417
this.shortcuts_dialog = None;
398
window.focus(&this.focus_handle, cx);
418
this.restore_focus(window, cx);
399
419
cx.notify();
400
420
},
401
421
)
@@ -411,6 +431,7 @@ impl AppShell {
411
431
else {
412
432
return;
413
433
};
434
self.close_image_viewer(window, cx);
414
435
if let Some(card) = &self.profile_card {
415
436
card.update(cx, |card, cx| {
416
437
card.move_to(request.user_id, request.anchor, cx)
@@ -424,7 +445,7 @@ impl AppShell {
424
445
window,
425
446
|this, _, _: &ProfileCardEvent, window, cx| {
426
447
this.profile_card = None;
427
window.focus(&this.focus_handle, cx);
448
this.restore_focus(window, cx);
428
449
cx.notify();
429
450
},
430
451
)
@@ -433,6 +454,47 @@ impl AppShell {
433
454
cx.notify();
434
455
}
435
456
457
fn open_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
458
let Some(request) = self
459
.state
460
.update(cx, |state, _| state.take_image_viewer_request())
461
else {
462
return;
463
};
464
self.switcher = None;
465
let app = self.state.clone();
466
let viewer = cx.new(|cx| ImageViewer::new(app, request, window, cx));
467
cx.subscribe_in(
468
&viewer,
469
window,
470
|this, _, _: &ImageViewerEvent, window, cx| {
471
this.image_viewer = None;
472
window.focus(&this.focus_handle, cx);
473
cx.notify();
474
},
475
)
476
.detach();
477
self.image_viewer = Some(viewer);
478
cx.notify();
479
}
480
481
fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {
482
if self.image_viewer.take().is_some() {
483
window.focus(&self.focus_handle, cx);
484
cx.notify();
485
}
486
}
487
488
fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {
489
match &self.image_viewer {
490
Some(viewer) => {
491
let handle = viewer.read(cx).focus_handle();
492
window.focus(&handle, cx)
493
}
494
None => window.focus(&self.focus_handle, cx),
495
}
496
}
497
436
498
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
437
499
let Some(source) = self
438
500
.state
@@ -449,7 +511,7 @@ impl AppShell {
449
511
window,
450
512
|this, _, event: &ForwardDialogEvent, window, cx| {
451
513
this.forward_dialog = None;
452
window.focus(&this.focus_handle, cx);
514
this.restore_focus(window, cx);
453
515
if let ForwardDialogEvent::Sent { target, title } = event {
454
516
let target = target.clone();
455
517
let open = NoticeAction::new("Open", move |state, cx| {
@@ -476,22 +538,20 @@ impl AppShell {
476
538
.w_full()
477
539
.gap(px(ISLAND_GAP))
478
540
.pr(px(ISLAND_GAP))
479
.child(self.rail.clone())
541
.py(px(ISLAND_GAP))
480
542
.child(
481
self.sidebar
482
.clone()
483
.cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()),
543
h_flex()
544
.h_full()
545
.flex_none()
546
.child(self.rail.clone())
547
.child(
548
self.sidebar
549
.clone()
550
.cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()),
551
),
484
552
)
485
553
.child(match call_view {
486
Some(call_view) => h_flex()
487
.flex_1()
488
.min_w_0()
489
.h_full()
490
.rounded(px(10.))
491
.bg(theme::surface())
492
.overflow_hidden()
493
.child(call_view)
494
.into_any_element(),
554
Some(call_view) => call_view,
495
555
None => self
496
556
.conversation
497
557
.clone()
@@ -533,6 +593,7 @@ impl Render for AppShell {
533
593
}
534
594
let panels = self.switcher.is_some()
535
595
|| self.forward_dialog.is_some()
596
|| self.image_viewer.is_some()
536
597
|| self.status_dialog.is_some()
537
598
|| self.shortcuts_dialog.is_some()
538
599
|| self.profile_card.is_some()
@@ -568,7 +629,8 @@ impl Render for AppShell {
568
629
.on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {
569
630
this.toggle_switcher("", window, cx);
570
631
}))
571
.on_action(cx.listener(|this, _: &NewChat, _, cx| {
632
.on_action(cx.listener(|this, _: &NewChat, window, cx| {
633
this.close_image_viewer(window, cx);
572
634
this.state.update(cx, |state, cx| state.start_new_chat(cx));
573
635
}))
574
636
.on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {
@@ -577,26 +639,33 @@ impl Render for AppShell {
577
639
.on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {
578
640
this.toggle_shortcuts_dialog(window, cx);
579
641
}))
580
.on_action(cx.listener(|this, _: &OpenActivity, _, cx| {
642
.on_action(cx.listener(|this, _: &OpenActivity, window, cx| {
643
this.close_image_viewer(window, cx);
581
644
this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));
582
645
}))
583
.on_action(cx.listener(|this, _: &OpenSaved, _, cx| {
646
.on_action(cx.listener(|this, _: &OpenSaved, window, cx| {
647
this.close_image_viewer(window, cx);
584
648
this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));
585
649
}))
586
.on_action(cx.listener(|this, _: &OpenChatsTab, _, cx| {
650
.on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {
651
this.close_image_viewer(window, cx);
587
652
this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));
588
653
}))
589
.on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {
654
.on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {
655
this.close_image_viewer(window, cx);
590
656
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));
591
657
}))
592
.on_action(cx.listener(|this, _: &OpenCallsTab, _, cx| {
658
.on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {
659
this.close_image_viewer(window, cx);
593
660
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));
594
661
}))
595
.on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {
662
.on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {
663
this.close_image_viewer(window, cx);
596
664
this.sidebar
597
665
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));
598
666
}))
599
.on_action(cx.listener(|this, _: &NextConversation, _, cx| {
667
.on_action(cx.listener(|this, _: &NextConversation, window, cx| {
668
this.close_image_viewer(window, cx);
600
669
this.sidebar
601
670
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));
602
671
}))
@@ -616,6 +685,7 @@ impl Render for AppShell {
616
685
this.state.update(cx, |state, cx| state.toggle_call_share(cx));
617
686
}))
618
687
.on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {
688
this.close_image_viewer(window, cx);
619
689
this.conversation.update(cx, |conversation, cx| {
620
690
conversation.reply_to_hovered(window, cx)
621
691
});
@@ -626,6 +696,7 @@ impl Render for AppShell {
626
696
.text_color(theme::text())
627
697
.text_size(px(14.))
628
698
.child(crate::frame_log::probe("first"))
699
.child(user_activity::input_probe(self.user_input.clone()))
629
700
.child(
630
701
v_flex()
631
702
.size_full()
@@ -635,6 +706,7 @@ impl Render for AppShell {
635
706
)
636
707
.children(call_mini)
637
708
.children(stage_overlay)
709
.children(self.image_viewer.clone())
638
710
.children(self.switcher.clone())
639
711
.children(render_task_dialog(self.state.read(cx), cx))
640
712
.children(self.forward_dialog.clone())
@@ -1,3 +1,5 @@1
use std::sync::Arc;2
1
use gpui_kit::component::{h_flex, v_flex};3
use gpui_kit::component::{h_flex, v_flex};2
use gpui_kit::*;4
use gpui_kit::*;3
5
@@ -8,6 +10,7 @@ use super::call_view::render_call_view;8
use super::conversation::{ConversationView, ReplyToHovered};10
use super::conversation::{ConversationView, ReplyToHovered};9
use super::dialog_overlay::render_task_dialog;11
use super::dialog_overlay::render_task_dialog;10
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};12
use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};13
use super::image_viewer::{ImageViewer, ImageViewerEvent};11
use super::profile_card::{ProfileCard, ProfileCardEvent};14
use super::profile_card::{ProfileCard, ProfileCardEvent};12
use super::rail::RailView;15
use super::rail::RailView;13
use super::saved_panel::{SavedPanel, SavedPanelEvent};16
use super::saved_panel::{SavedPanel, SavedPanelEvent};@@ -28,6 +31,7 @@ use crate::app_state::{AppEvent, AppState, Selection};28
use crate::call::{CallMedia, CallWindows};31
use crate::call::{CallMedia, CallWindows};29
use crate::embedded_web::{Overlays, RootFocus};32
use crate::embedded_web::{Overlays, RootFocus};30
use crate::notice::NoticeAction;33
use crate::notice::NoticeAction;34
use crate::user_activity::{self, UserInput};31
use crate::notify::{NotificationCenter, selection_for};35
use crate::notify::{NotificationCenter, selection_for};32
use crate::sidebar_model::Step;36
use crate::sidebar_model::Step;33
use crate::theme;37
use crate::theme;@@ -55,6 +59,10 @@ pub struct Startup {55
59
56
pub const ISLAND_GAP: f32 = 6.;60
pub const ISLAND_GAP: f32 = 6.;57
61
62
pub struct UserInputHandle(pub Arc<UserInput>);63
64
impl Global for UserInputHandle {}65
58
pub struct AppShell {66
pub struct AppShell {59
state: Entity<AppState>,67
state: Entity<AppState>,60
rail: Entity<RailView>,68
rail: Entity<RailView>,@@ -65,12 +73,14 @@ pub struct AppShell {65
notifications: Entity<NotificationCenter>,73
notifications: Entity<NotificationCenter>,66
_call_windows: Entity<CallWindows>,74
_call_windows: Entity<CallWindows>,67
forward_dialog: Option<Entity<ForwardDialog>>,75
forward_dialog: Option<Entity<ForwardDialog>>,76
image_viewer: Option<Entity<ImageViewer>>,68
status_dialog: Option<Entity<StatusMessageDialog>>,77
status_dialog: Option<Entity<StatusMessageDialog>>,69
shortcuts_dialog: Option<Entity<ShortcutsDialog>>,78
shortcuts_dialog: Option<Entity<ShortcutsDialog>>,70
profile_card: Option<Entity<ProfileCard>>,79
profile_card: Option<Entity<ProfileCard>>,71
focus_handle: FocusHandle,80
focus_handle: FocusHandle,72
open_target: Option<OpenTarget>,81
open_target: Option<OpenTarget>,73
update: UpdateStatus,82
update: UpdateStatus,83
user_input: Arc<UserInput>,74
_subscription: Subscription,84
_subscription: Subscription,75
_call_media_observation: Subscription,85
_call_media_observation: Subscription,76
_panel_subscriptions: [Subscription; 2],86
_panel_subscriptions: [Subscription; 2],@@ -134,6 +144,9 @@ impl AppShell {134
if matches!(event, AppEvent::Forward) {144
if matches!(event, AppEvent::Forward) {135
this.open_forward_dialog(window, cx);145
this.open_forward_dialog(window, cx);136
}146
}147
if matches!(event, AppEvent::ImageViewer) {148
this.open_image_viewer(window, cx);149
}137
if matches!(event, AppEvent::StatusMessage) {150
if matches!(event, AppEvent::StatusMessage) {138
this.open_status_dialog(window, cx);151
this.open_status_dialog(window, cx);139
}152
}@@ -151,7 +164,9 @@ impl AppShell {151
cx.set_global(RootFocus(focus_handle.clone()));164
cx.set_global(RootFocus(focus_handle.clone()));152
let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));165
let notifications = cx.new(|cx| NotificationCenter::new(state.clone(), window, cx));153
let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));166
let call_windows = cx.new(|cx| CallWindows::new(state.clone(), window, cx));167
let user_input = cx.global::<UserInputHandle>().0.clone();154
let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {168
let escape_observation = cx.observe_keystrokes(|this, event, _, cx| {169
this.user_input.touch();155
if event.keystroke.key == "escape" {170
if event.keystroke.key == "escape" {156
this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));171
this.state.update(cx, |state, cx| state.leave_stage_fullscreen(cx));157
}172
}@@ -173,12 +188,14 @@ impl AppShell {173
notifications,188
notifications,174
_call_windows: call_windows,189
_call_windows: call_windows,175
forward_dialog: None,190
forward_dialog: None,191
image_viewer: None,176
status_dialog: None,192
status_dialog: None,177
shortcuts_dialog: None,193
shortcuts_dialog: None,178
profile_card: None,194
profile_card: None,179
focus_handle,195
focus_handle,180
open_target,196
open_target,181
update: UpdateStatus::UpToDate,197
update: UpdateStatus::UpToDate,198
user_input,182
_subscription: subscription,199
_subscription: subscription,183
_call_media_observation: call_media_observation,200
_call_media_observation: call_media_observation,184
_panel_subscriptions: panel_subscriptions,201
_panel_subscriptions: panel_subscriptions,@@ -306,10 +323,11 @@ impl AppShell {306
cx: &mut Context<Self>,323
cx: &mut Context<Self>,307
) {324
) {308
if self.switcher.take().is_some() {325
if self.switcher.take().is_some() {309
window.focus(&self.focus_handle, cx);326
self.restore_focus(window, cx);310
cx.notify();327
cx.notify();311
return;328
return;312
}329
}330
self.close_image_viewer(window, cx);313
let candidates = candidates_from(self.state.read(cx));331
let candidates = candidates_from(self.state.read(cx));314
let app = self.state.clone();332
let app = self.state.clone();315
let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));333
let switcher = cx.new(|cx| Switcher::new(app, candidates, initial_query, window, cx));@@ -335,7 +353,7 @@ impl AppShell {335
SwitcherEvent::Close => {}353
SwitcherEvent::Close => {}336
}354
}337
this.switcher = None;355
this.switcher = None;338
window.focus(&this.focus_handle, cx);356
this.restore_focus(window, cx);339
cx.notify();357
cx.notify();340
},358
},341
)359
)@@ -365,6 +383,7 @@ impl AppShell {365
{383
{366
return;384
return;367
}385
}386
self.close_image_viewer(window, cx);368
self.switcher = None;387
self.switcher = None;369
let app = self.state.clone();388
let app = self.state.clone();370
let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));389
let dialog = cx.new(|cx| StatusMessageDialog::new(app, window, cx));@@ -373,7 +392,7 @@ impl AppShell {373
window,392
window,374
|this, _, _: &StatusMessageDialogEvent, window, cx| {393
|this, _, _: &StatusMessageDialogEvent, window, cx| {375
this.status_dialog = None;394
this.status_dialog = None;376
window.focus(&this.focus_handle, cx);395
this.restore_focus(window, cx);377
cx.notify();396
cx.notify();378
},397
},379
)398
)@@ -384,10 +403,11 @@ impl AppShell {384
403
385
fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {404
fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {386
if self.shortcuts_dialog.take().is_some() {405
if self.shortcuts_dialog.take().is_some() {387
window.focus(&self.focus_handle, cx);406
self.restore_focus(window, cx);388
cx.notify();407
cx.notify();389
return;408
return;390
}409
}410
self.close_image_viewer(window, cx);391
self.switcher = None;411
self.switcher = None;392
let dialog = cx.new(|cx| ShortcutsDialog::new(window, cx));412
let dialog = cx.new(|cx| ShortcutsDialog::new(window, cx));393
cx.subscribe_in(413
cx.subscribe_in(@@ -395,7 +415,7 @@ impl AppShell {395
window,415
window,396
|this, _, _: &ShortcutsDialogEvent, window, cx| {416
|this, _, _: &ShortcutsDialogEvent, window, cx| {397
this.shortcuts_dialog = None;417
this.shortcuts_dialog = None;398
window.focus(&this.focus_handle, cx);418
this.restore_focus(window, cx);399
cx.notify();419
cx.notify();400
},420
},401
)421
)@@ -411,6 +431,7 @@ impl AppShell {411
else {431
else {412
return;432
return;413
};433
};434
self.close_image_viewer(window, cx);414
if let Some(card) = &self.profile_card {435
if let Some(card) = &self.profile_card {415
card.update(cx, |card, cx| {436
card.update(cx, |card, cx| {416
card.move_to(request.user_id, request.anchor, cx)437
card.move_to(request.user_id, request.anchor, cx)@@ -424,7 +445,7 @@ impl AppShell {424
window,445
window,425
|this, _, _: &ProfileCardEvent, window, cx| {446
|this, _, _: &ProfileCardEvent, window, cx| {426
this.profile_card = None;447
this.profile_card = None;427
window.focus(&this.focus_handle, cx);448
this.restore_focus(window, cx);428
cx.notify();449
cx.notify();429
},450
},430
)451
)@@ -433,6 +454,47 @@ impl AppShell {433
cx.notify();454
cx.notify();434
}455
}435
456
457
fn open_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {458
let Some(request) = self459
.state460
.update(cx, |state, _| state.take_image_viewer_request())461
else {462
return;463
};464
self.switcher = None;465
let app = self.state.clone();466
let viewer = cx.new(|cx| ImageViewer::new(app, request, window, cx));467
cx.subscribe_in(468
&viewer,469
window,470
|this, _, _: &ImageViewerEvent, window, cx| {471
this.image_viewer = None;472
window.focus(&this.focus_handle, cx);473
cx.notify();474
},475
)476
.detach();477
self.image_viewer = Some(viewer);478
cx.notify();479
}480
481
fn close_image_viewer(&mut self, window: &mut Window, cx: &mut Context<Self>) {482
if self.image_viewer.take().is_some() {483
window.focus(&self.focus_handle, cx);484
cx.notify();485
}486
}487
488
fn restore_focus(&self, window: &mut Window, cx: &mut Context<Self>) {489
match &self.image_viewer {490
Some(viewer) => {491
let handle = viewer.read(cx).focus_handle();492
window.focus(&handle, cx)493
}494
None => window.focus(&self.focus_handle, cx),495
}496
}497
436
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {498
fn open_forward_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {437
let Some(source) = self499
let Some(source) = self438
.state500
.state@@ -449,7 +511,7 @@ impl AppShell {449
window,511
window,450
|this, _, event: &ForwardDialogEvent, window, cx| {512
|this, _, event: &ForwardDialogEvent, window, cx| {451
this.forward_dialog = None;513
this.forward_dialog = None;452
window.focus(&this.focus_handle, cx);514
this.restore_focus(window, cx);453
if let ForwardDialogEvent::Sent { target, title } = event {515
if let ForwardDialogEvent::Sent { target, title } = event {454
let target = target.clone();516
let target = target.clone();455
let open = NoticeAction::new("Open", move |state, cx| {517
let open = NoticeAction::new("Open", move |state, cx| {@@ -476,22 +538,20 @@ impl AppShell {476
.w_full()538
.w_full()477
.gap(px(ISLAND_GAP))539
.gap(px(ISLAND_GAP))478
.pr(px(ISLAND_GAP))540
.pr(px(ISLAND_GAP))479
.child(self.rail.clone())541
.py(px(ISLAND_GAP))480
.child(542
.child(481
self.sidebar543
h_flex()482
.clone()544
.h_full()483
.cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()),545
.flex_none()546
.child(self.rail.clone())547
.child(548
self.sidebar549
.clone()550
.cached(StyleRefinement::default().w(px(SIDEBAR_WIDTH)).h_full().flex_none()),551
),484
)552
)485
.child(match call_view {553
.child(match call_view {486
Some(call_view) => h_flex()554
Some(call_view) => call_view,487
.flex_1()488
.min_w_0()489
.h_full()490
.rounded(px(10.))491
.bg(theme::surface())492
.overflow_hidden()493
.child(call_view)494
.into_any_element(),495
None => self555
None => self496
.conversation556
.conversation497
.clone()557
.clone()@@ -533,6 +593,7 @@ impl Render for AppShell {533
}593
}534
let panels = self.switcher.is_some()594
let panels = self.switcher.is_some()535
|| self.forward_dialog.is_some()595
|| self.forward_dialog.is_some()596
|| self.image_viewer.is_some()536
|| self.status_dialog.is_some()597
|| self.status_dialog.is_some()537
|| self.shortcuts_dialog.is_some()598
|| self.shortcuts_dialog.is_some()538
|| self.profile_card.is_some()599
|| self.profile_card.is_some()@@ -568,7 +629,8 @@ impl Render for AppShell {568
.on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {629
.on_action(cx.listener(|this, _: &OpenSwitcher, window, cx| {569
this.toggle_switcher("", window, cx);630
this.toggle_switcher("", window, cx);570
}))631
}))571
.on_action(cx.listener(|this, _: &NewChat, _, cx| {632
.on_action(cx.listener(|this, _: &NewChat, window, cx| {633
this.close_image_viewer(window, cx);572
this.state.update(cx, |state, cx| state.start_new_chat(cx));634
this.state.update(cx, |state, cx| state.start_new_chat(cx));573
}))635
}))574
.on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {636
.on_action(cx.listener(|this, _: &ToggleCallMute, _, cx| {@@ -577,26 +639,33 @@ impl Render for AppShell {577
.on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {639
.on_action(cx.listener(|this, _: &ShowShortcuts, window, cx| {578
this.toggle_shortcuts_dialog(window, cx);640
this.toggle_shortcuts_dialog(window, cx);579
}))641
}))580
.on_action(cx.listener(|this, _: &OpenActivity, _, cx| {642
.on_action(cx.listener(|this, _: &OpenActivity, window, cx| {643
this.close_image_viewer(window, cx);581
this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));644
this.sidebar.update(cx, |sidebar, cx| sidebar.show_activity(cx));582
}))645
}))583
.on_action(cx.listener(|this, _: &OpenSaved, _, cx| {646
.on_action(cx.listener(|this, _: &OpenSaved, window, cx| {647
this.close_image_viewer(window, cx);584
this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));648
this.sidebar.update(cx, |sidebar, cx| sidebar.show_saved(cx));585
}))649
}))586
.on_action(cx.listener(|this, _: &OpenChatsTab, _, cx| {650
.on_action(cx.listener(|this, _: &OpenChatsTab, window, cx| {651
this.close_image_viewer(window, cx);587
this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));652
this.sidebar.update(cx, |sidebar, cx| sidebar.show_chats(cx));588
}))653
}))589
.on_action(cx.listener(|this, _: &OpenChannelsTab, _, cx| {654
.on_action(cx.listener(|this, _: &OpenChannelsTab, window, cx| {655
this.close_image_viewer(window, cx);590
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));656
this.sidebar.update(cx, |sidebar, cx| sidebar.show_channels(cx));591
}))657
}))592
.on_action(cx.listener(|this, _: &OpenCallsTab, _, cx| {658
.on_action(cx.listener(|this, _: &OpenCallsTab, window, cx| {659
this.close_image_viewer(window, cx);593
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));660
this.sidebar.update(cx, |sidebar, cx| sidebar.show_calls(cx));594
}))661
}))595
.on_action(cx.listener(|this, _: &PreviousConversation, _, cx| {662
.on_action(cx.listener(|this, _: &PreviousConversation, window, cx| {663
this.close_image_viewer(window, cx);596
this.sidebar664
this.sidebar597
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));665
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Previous, cx));598
}))666
}))599
.on_action(cx.listener(|this, _: &NextConversation, _, cx| {667
.on_action(cx.listener(|this, _: &NextConversation, window, cx| {668
this.close_image_viewer(window, cx);600
this.sidebar669
this.sidebar601
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));670
.update(cx, |sidebar, cx| sidebar.select_adjacent(Step::Next, cx));602
}))671
}))@@ -616,6 +685,7 @@ impl Render for AppShell {616
this.state.update(cx, |state, cx| state.toggle_call_share(cx));685
this.state.update(cx, |state, cx| state.toggle_call_share(cx));617
}))686
}))618
.on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {687
.on_action(cx.listener(|this, _: &ReplyToHovered, window, cx| {688
this.close_image_viewer(window, cx);619
this.conversation.update(cx, |conversation, cx| {689
this.conversation.update(cx, |conversation, cx| {620
conversation.reply_to_hovered(window, cx)690
conversation.reply_to_hovered(window, cx)621
});691
});@@ -626,6 +696,7 @@ impl Render for AppShell {626
.text_color(theme::text())696
.text_color(theme::text())627
.text_size(px(14.))697
.text_size(px(14.))628
.child(crate::frame_log::probe("first"))698
.child(crate::frame_log::probe("first"))699
.child(user_activity::input_probe(self.user_input.clone()))629
.child(700
.child(630
v_flex()701
v_flex()631
.size_full()702
.size_full()@@ -635,6 +706,7 @@ impl Render for AppShell {635
)706
)636
.children(call_mini)707
.children(call_mini)637
.children(stage_overlay)708
.children(stage_overlay)709
.children(self.image_viewer.clone())638
.children(self.switcher.clone())710
.children(self.switcher.clone())639
.children(render_task_dialog(self.state.read(cx), cx))711
.children(render_task_dialog(self.state.read(cx), cx))640
.children(self.forward_dialog.clone())712
.children(self.forward_dialog.clone())@@ -49,7 +49,7 @@ const TEAMS_LABEL: &str = "Teams";
49
49
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
50
50
const TEAM_ROW_HEIGHT: f32 = 40.;
51
51
const REVEAL_ROW_HEIGHT: f32 = 32.;
52
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;
52
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
53
53
const MENU_ICON_SIZE: f32 = 15.;
54
54
const MUTED_ICON_SIZE: f32 = 13.;
55
55
const NOTIFICATION_ICON_SIZE: f32 = 13.;
@@ -530,7 +530,7 @@ impl SidebarView {
530
530
.mx(px(6.))
531
531
.h(px(ROW_HEIGHT))
532
532
.px(px(10.))
533
.gap(px(10.))
533
.gap(px(12.))
534
534
.items_center()
535
535
.rounded(px(8.))
536
536
.bg(theme::surface_raised())
@@ -575,9 +575,8 @@ impl SidebarView {
575
575
.id(SharedString::from(format!("section-{}", section.id)))
576
576
.h(px(SECTION_HEIGHT))
577
577
.mt(px(SECTION_GAP))
578
.mx(px(4.))
579
.pl(px(8.))
580
.pr(px(10.))
578
.mx(px(6.))
579
.px(px(10.))
581
580
.gap(px(6.))
582
581
.items_center()
583
582
.rounded(px(6.))
@@ -641,7 +640,7 @@ impl SidebarView {
641
640
div()
642
641
.id(SharedString::from(format!("see-more-{}", section.id)))
643
642
.mx(px(6.))
644
.pl(px(56.))
643
.pl(px(10. + AVATAR_SIZE + 12.))
645
644
.h(px(SEE_MORE_HEIGHT))
646
645
.flex()
647
646
.items_center()
@@ -799,7 +798,7 @@ impl SidebarView {
799
798
.mx(px(6.))
800
799
.h(px(ROW_HEIGHT))
801
800
.px(px(10.))
802
.gap(px(10.))
801
.gap(px(12.))
803
802
.items_center()
804
803
.rounded(px(8.))
805
804
.cursor_pointer()
@@ -917,8 +916,8 @@ impl SidebarView {
917
916
list = with_spacer(list, &mut skipped_height);
918
917
list = list.child(
919
918
div()
920
.ml(px(44.))
921
.mr(px(20.))
919
.ml(px(16.))
920
.mr(px(16.))
922
921
.h(px(HINT_HEIGHT))
923
922
.flex()
924
923
.items_center()
@@ -986,7 +985,7 @@ impl SidebarView {
986
985
.mx(px(6.))
987
986
.h(px(PINNED_CHANNEL_HEIGHT))
988
987
.px(px(10.))
989
.gap(px(10.))
988
.gap(px(12.))
990
989
.items_center()
991
990
.rounded(px(8.))
992
991
.cursor_pointer()
@@ -1066,7 +1065,7 @@ impl SidebarView {
1066
1065
div()
1067
1066
.h(px(SECTION_HEIGHT))
1068
1067
.mt(px(SECTION_GAP))
1069
.px(px(12.))
1068
.px(px(16.))
1070
1069
.flex()
1071
1070
.items_center()
1072
1071
.text_size(px(12.))
@@ -49,7 +49,7 @@ const TEAMS_LABEL: &str = "Teams";49
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";49
const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";50
const TEAM_ROW_HEIGHT: f32 = 40.;50
const TEAM_ROW_HEIGHT: f32 = 40.;51
const REVEAL_ROW_HEIGHT: f32 = 32.;51
const REVEAL_ROW_HEIGHT: f32 = 32.;52
const NEW_CHAT_BUTTON_SIZE: f32 = 34.;52
const NEW_CHAT_BUTTON_SIZE: f32 = 32.;53
const MENU_ICON_SIZE: f32 = 15.;53
const MENU_ICON_SIZE: f32 = 15.;54
const MUTED_ICON_SIZE: f32 = 13.;54
const MUTED_ICON_SIZE: f32 = 13.;55
const NOTIFICATION_ICON_SIZE: f32 = 13.;55
const NOTIFICATION_ICON_SIZE: f32 = 13.;@@ -530,7 +530,7 @@ impl SidebarView {530
.mx(px(6.))530
.mx(px(6.))531
.h(px(ROW_HEIGHT))531
.h(px(ROW_HEIGHT))532
.px(px(10.))532
.px(px(10.))533
.gap(px(10.))533
.gap(px(12.))534
.items_center()534
.items_center()535
.rounded(px(8.))535
.rounded(px(8.))536
.bg(theme::surface_raised())536
.bg(theme::surface_raised())@@ -575,9 +575,8 @@ impl SidebarView {575
.id(SharedString::from(format!("section-{}", section.id)))575
.id(SharedString::from(format!("section-{}", section.id)))576
.h(px(SECTION_HEIGHT))576
.h(px(SECTION_HEIGHT))577
.mt(px(SECTION_GAP))577
.mt(px(SECTION_GAP))578
.mx(px(4.))578
.mx(px(6.))579
.pl(px(8.))579
.px(px(10.))580
.pr(px(10.))581
.gap(px(6.))580
.gap(px(6.))582
.items_center()581
.items_center()583
.rounded(px(6.))582
.rounded(px(6.))@@ -641,7 +640,7 @@ impl SidebarView {641
div()640
div()642
.id(SharedString::from(format!("see-more-{}", section.id)))641
.id(SharedString::from(format!("see-more-{}", section.id)))643
.mx(px(6.))642
.mx(px(6.))644
.pl(px(56.))643
.pl(px(10. + AVATAR_SIZE + 12.))645
.h(px(SEE_MORE_HEIGHT))644
.h(px(SEE_MORE_HEIGHT))646
.flex()645
.flex()647
.items_center()646
.items_center()@@ -799,7 +798,7 @@ impl SidebarView {799
.mx(px(6.))798
.mx(px(6.))800
.h(px(ROW_HEIGHT))799
.h(px(ROW_HEIGHT))801
.px(px(10.))800
.px(px(10.))802
.gap(px(10.))801
.gap(px(12.))803
.items_center()802
.items_center()804
.rounded(px(8.))803
.rounded(px(8.))805
.cursor_pointer()804
.cursor_pointer()@@ -917,8 +916,8 @@ impl SidebarView {917
list = with_spacer(list, &mut skipped_height);916
list = with_spacer(list, &mut skipped_height);918
list = list.child(917
list = list.child(919
div()918
div()920
.ml(px(44.))919
.ml(px(16.))921
.mr(px(20.))920
.mr(px(16.))922
.h(px(HINT_HEIGHT))921
.h(px(HINT_HEIGHT))923
.flex()922
.flex()924
.items_center()923
.items_center()@@ -986,7 +985,7 @@ impl SidebarView {986
.mx(px(6.))985
.mx(px(6.))987
.h(px(PINNED_CHANNEL_HEIGHT))986
.h(px(PINNED_CHANNEL_HEIGHT))988
.px(px(10.))987
.px(px(10.))989
.gap(px(10.))988
.gap(px(12.))990
.items_center()989
.items_center()991
.rounded(px(8.))990
.rounded(px(8.))992
.cursor_pointer()991
.cursor_pointer()@@ -1066,7 +1065,7 @@ impl SidebarView {1066
div()1065
div()1067
.h(px(SECTION_HEIGHT))1066
.h(px(SECTION_HEIGHT))1068
.mt(px(SECTION_GAP))1067
.mt(px(SECTION_GAP))1069
.px(px(12.))1068
.px(px(16.))1070
.flex()1069
.flex()1071
.items_center()1070
.items_center()1072
.text_size(px(12.))1071
.text_size(px(12.))@@ -48,7 +48,7 @@ pub fn page_header(title: &str) -> Div {
48
48
.items_center()
49
49
.gap(px(6.))
50
50
.pl(px(16.))
51
.pr(px(10.))
51
.pr(px(12.))
52
52
.child(
53
53
div()
54
54
.flex_1()
@@ -48,7 +48,7 @@ pub fn page_header(title: &str) -> Div {48
.items_center()48
.items_center()49
.gap(px(6.))49
.gap(px(6.))50
.pl(px(16.))50
.pl(px(16.))51
.pr(px(10.))51
.pr(px(12.))52
.child(52
.child(53
div()53
div()54
.flex_1()54
.flex_1()@@ -1,5 +1,5 @@
1
1
(() => {
2
const VERSION = 5;
2
const VERSION = 6;
3
3
const GLOBAL_NAME = '__chatsvcTrouter';
4
4
const BINDING_NAME = '__chatsvcRealtime';
5
5
const EPID_KEY = '__chatsvcEpid';
@@ -12,6 +12,8 @@
12
12
const REREGISTER_MS = 40 * 60 * 1000;
13
13
const CONNECT_TIMEOUT_MS = 20000;
14
14
const MAX_BACKOFF_MS = 30000;
15
const ACTIVITY_DEBOUNCE_MS = 1000;
16
const ACTIVITY_ACK_TIMEOUT_MS = 10000;
15
17
const MAX_QUEUE = 200;
16
18
const MAX_PRESENCE_ENTRIES = 1000;
17
19
const MAX_PRESENCE_FIELD = 128;
@@ -40,7 +42,7 @@
40
42
41
43
const state = {
42
44
token: null, host: null, epid: loadEpid(), socket: null, ready: false,
43
closed: false, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
45
closed: false, activity: 'inactive', sentActivity: null, activityAckId: 0, activityTimer: null, activityResendTimer: null, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],
44
46
};
45
47
46
48
const flush = () => {
@@ -142,7 +144,25 @@
142
144
};
143
145
const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };
144
146
const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));
145
const activity = () => sendEvent('user.activity', [{state: 'active', cv: crypto.randomUUID()}]);
147
const transmitActivity = (resend) => {
148
clearTimeout(state.activityTimer);
149
clearTimeout(state.activityResendTimer);
150
if (!state.ready) return;
151
sendEvent('user.activity', [{state: state.activity, cv: crypto.randomUUID()}]);
152
state.sentActivity = state.activity;
153
state.activityAckId = state.ackCounter;
154
if (!resend) state.activityResendTimer = setTimeout(() => transmitActivity(true), ACTIVITY_ACK_TIMEOUT_MS);
155
};
156
const setActivity = (next) => {
157
if (next !== 'active' && next !== 'inactive') return;
158
state.activity = next;
159
clearTimeout(state.activityTimer);
160
if (!state.ready || next === state.sentActivity) return;
161
state.activityTimer = setTimeout(() => transmitActivity(false), ACTIVITY_DEBOUNCE_MS);
162
};
163
const acknowledgeActivity = (data) => {
164
if (Number.parseInt(data, 10) === state.activityAckId) clearTimeout(state.activityResendTimer);
165
};
146
166
147
167
const register = async (surl) => {
148
168
state.surl = surl || state.surl;
@@ -192,8 +212,8 @@
192
212
if (event.name === 'trouter.connected') {
193
213
try {
194
214
await register(event.args[0].surl);
195
activity();
196
215
state.ready = true;
216
transmitActivity(false);
197
217
state.retry = 0;
198
218
announceEndpoint();
199
219
status('connected');
@@ -206,6 +226,8 @@
206
226
const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];
207
227
status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));
208
228
}
229
} else if (packet.type === '6') {
230
acknowledgeActivity(packet.data);
209
231
} else if (packet.type === '3') {
210
232
let request;
211
233
try { request = JSON.parse(packet.data); } catch (error) { return; }
@@ -240,6 +262,8 @@
240
262
const wasReady = state.ready;
241
263
state.socket = null;
242
264
state.ready = false;
265
clearTimeout(state.activityTimer);
266
clearTimeout(state.activityResendTimer);
243
267
if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');
244
268
scheduleReconnect();
245
269
};
@@ -249,7 +273,6 @@
249
273
if (!state.socket || state.socket.readyState !== 1) return;
250
274
if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }
251
275
sendEvent('ping', []);
252
activity();
253
276
if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {
254
277
register().catch((error) => status('error', registerDetail(error)));
255
278
}
@@ -259,6 +282,8 @@
259
282
state.closed = true;
260
283
clearInterval(maintain);
261
284
clearTimeout(state.reconnectTimer);
285
clearTimeout(state.activityTimer);
286
clearTimeout(state.activityResendTimer);
262
287
for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer);
263
288
state.pendingReplies.clear();
264
289
if (state.socket) state.socket.close();
@@ -270,6 +295,7 @@
270
295
ensure: (config) => {
271
296
state.token = config.token;
272
297
state.host = config.host;
298
setActivity(config.activity);
273
299
connect();
274
300
if (state.ready) {
275
301
announceEndpoint();
@@ -279,6 +305,8 @@
279
305
return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';
280
306
},
281
307
shutdown,
308
setActivity,
309
resendActivity: () => transmitActivity(false),
282
310
reply: (id, status, body) => answer(id, status, body),
283
311
stop: async () => {
284
312
let unregistered = null;
@@ -1,5 +1,5 @@1
(() => {1
(() => {2
const VERSION = 5;2
const VERSION = 6;3
const GLOBAL_NAME = '__chatsvcTrouter';3
const GLOBAL_NAME = '__chatsvcTrouter';4
const BINDING_NAME = '__chatsvcRealtime';4
const BINDING_NAME = '__chatsvcRealtime';5
const EPID_KEY = '__chatsvcEpid';5
const EPID_KEY = '__chatsvcEpid';@@ -12,6 +12,8 @@12
const REREGISTER_MS = 40 * 60 * 1000;12
const REREGISTER_MS = 40 * 60 * 1000;13
const CONNECT_TIMEOUT_MS = 20000;13
const CONNECT_TIMEOUT_MS = 20000;14
const MAX_BACKOFF_MS = 30000;14
const MAX_BACKOFF_MS = 30000;15
const ACTIVITY_DEBOUNCE_MS = 1000;16
const ACTIVITY_ACK_TIMEOUT_MS = 10000;15
const MAX_QUEUE = 200;17
const MAX_QUEUE = 200;16
const MAX_PRESENCE_ENTRIES = 1000;18
const MAX_PRESENCE_ENTRIES = 1000;17
const MAX_PRESENCE_FIELD = 128;19
const MAX_PRESENCE_FIELD = 128;@@ -40,7 +42,7 @@40
42
41
const state = {43
const state = {42
token: null, host: null, epid: loadEpid(), socket: null, ready: false,44
token: null, host: null, epid: loadEpid(), socket: null, ready: false,43
closed: false, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],45
closed: false, activity: 'inactive', sentActivity: null, activityAckId: 0, activityTimer: null, activityResendTimer: null, pendingReplies: new Map(), ackCounter: 0, lastFrameAt: 0, registeredAt: 0, retry: 0, reconnectTimer: null, queue: [],44
};46
};45
47
46
const flush = () => {48
const flush = () => {@@ -142,7 +144,25 @@142
};144
};143
const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };145
const send = (text) => { if (state.socket && state.socket.readyState === 1) state.socket.send(text); };144
const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));146
const sendEvent = (name, args) => send(`5:${++state.ackCounter}+::` + JSON.stringify({name, args}));145
const activity = () => sendEvent('user.activity', [{state: 'active', cv: crypto.randomUUID()}]);147
const transmitActivity = (resend) => {148
clearTimeout(state.activityTimer);149
clearTimeout(state.activityResendTimer);150
if (!state.ready) return;151
sendEvent('user.activity', [{state: state.activity, cv: crypto.randomUUID()}]);152
state.sentActivity = state.activity;153
state.activityAckId = state.ackCounter;154
if (!resend) state.activityResendTimer = setTimeout(() => transmitActivity(true), ACTIVITY_ACK_TIMEOUT_MS);155
};156
const setActivity = (next) => {157
if (next !== 'active' && next !== 'inactive') return;158
state.activity = next;159
clearTimeout(state.activityTimer);160
if (!state.ready || next === state.sentActivity) return;161
state.activityTimer = setTimeout(() => transmitActivity(false), ACTIVITY_DEBOUNCE_MS);162
};163
const acknowledgeActivity = (data) => {164
if (Number.parseInt(data, 10) === state.activityAckId) clearTimeout(state.activityResendTimer);165
};146
166
147
const register = async (surl) => {167
const register = async (surl) => {148
state.surl = surl || state.surl;168
state.surl = surl || state.surl;@@ -192,8 +212,8 @@192
if (event.name === 'trouter.connected') {212
if (event.name === 'trouter.connected') {193
try {213
try {194
await register(event.args[0].surl);214
await register(event.args[0].surl);195
activity();196
state.ready = true;215
state.ready = true;216
transmitActivity(false);197
state.retry = 0;217
state.retry = 0;198
announceEndpoint();218
announceEndpoint();199
status('connected');219
status('connected');@@ -206,6 +226,8 @@206
const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];226
const dropped = (event.args && event.args[0] && event.args[0].droppedIndicators) || [];207
status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));227
status('message_loss', dropped.map((indicator) => String(indicator.tag)).join(',').slice(0, 200));208
}228
}229
} else if (packet.type === '6') {230
acknowledgeActivity(packet.data);209
} else if (packet.type === '3') {231
} else if (packet.type === '3') {210
let request;232
let request;211
try { request = JSON.parse(packet.data); } catch (error) { return; }233
try { request = JSON.parse(packet.data); } catch (error) { return; }@@ -240,6 +262,8 @@240
const wasReady = state.ready;262
const wasReady = state.ready;241
state.socket = null;263
state.socket = null;242
state.ready = false;264
state.ready = false;265
clearTimeout(state.activityTimer);266
clearTimeout(state.activityResendTimer);243
if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');267
if (!state.closed) status('disconnected', wasReady ? 'closed' : 'connect_failed');244
scheduleReconnect();268
scheduleReconnect();245
};269
};@@ -249,7 +273,6 @@249
if (!state.socket || state.socket.readyState !== 1) return;273
if (!state.socket || state.socket.readyState !== 1) return;250
if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }274
if (Date.now() - state.lastFrameAt > SILENCE_LIMIT_MS) { state.socket.close(); return; }251
sendEvent('ping', []);275
sendEvent('ping', []);252
activity();253
if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {276
if (state.ready && Date.now() - state.registeredAt > REREGISTER_MS) {254
register().catch((error) => status('error', registerDetail(error)));277
register().catch((error) => status('error', registerDetail(error)));255
}278
}@@ -259,6 +282,8 @@259
state.closed = true;282
state.closed = true;260
clearInterval(maintain);283
clearInterval(maintain);261
clearTimeout(state.reconnectTimer);284
clearTimeout(state.reconnectTimer);285
clearTimeout(state.activityTimer);286
clearTimeout(state.activityResendTimer);262
for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer);287
for (const pending of state.pendingReplies.values()) clearTimeout(pending.timer);263
state.pendingReplies.clear();288
state.pendingReplies.clear();264
if (state.socket) state.socket.close();289
if (state.socket) state.socket.close();@@ -270,6 +295,7 @@270
ensure: (config) => {295
ensure: (config) => {271
state.token = config.token;296
state.token = config.token;272
state.host = config.host;297
state.host = config.host;298
setActivity(config.activity);273
connect();299
connect();274
if (state.ready) {300
if (state.ready) {275
announceEndpoint();301
announceEndpoint();@@ -279,6 +305,8 @@279
return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';305
return state.ready ? 'ready' : state.socket ? 'connecting' : 'waiting';280
},306
},281
shutdown,307
shutdown,308
setActivity,309
resendActivity: () => transmitActivity(false),282
reply: (id, status, body) => answer(id, status, body),310
reply: (id, status, body) => answer(id, status, body),283
stop: async () => {311
stop: async () => {284
let unregistered = null;312
let unregistered = null;@@ -0,0 +1,87 @@
1
use std::time::Duration;
2
3
use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};
4
use session::{DEFAULT_ENDPOINT, Session};
5
6
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);
7
const SETTLE: Duration = Duration::from_secs(10);
8
9
#[tokio::main]
10
async fn main() {
11
let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");
12
let inactive_wait = std::env::args()
13
.nth(2)
14
.and_then(|value| value.parse().ok())
15
.map_or(SETTLE, Duration::from_secs);
16
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());
17
let session = Session::connect(&endpoint).await.expect("browser");
18
let presence = PresenceService::new(&session);
19
20
let config = RealtimeConfig {
21
initially_active: true,
22
..RealtimeConfig::default()
23
};
24
let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");
25
let endpoint_id = wait_for_endpoint(&mut realtime).await;
26
println!("# trouter connected");
27
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));
29
realtime.resend_activity();
30
println!("# sent active");
31
tokio::time::sleep(SETTLE).await;
32
print_own_presence(&presence, &user_id).await;
33
34
realtime.set_activity(false);
35
println!("# sent inactive");
36
tokio::time::sleep(inactive_wait).await;
37
print_own_presence(&presence, &user_id).await;
38
39
println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));
40
println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));
41
realtime.stop().await;
42
println!("# stopped");
43
}
44
45
async fn wait_for_endpoint(realtime: &mut Realtime) -> String {
46
let wait = async {
47
let mut endpoint_id = None;
48
let mut connected = false;
49
while let Some(event) = realtime.recv().await {
50
match event {
51
RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),
52
RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,
53
_ => {}
54
}
55
if connected && let Some(endpoint_id) = endpoint_id.take() {
56
return endpoint_id;
57
}
58
}
59
panic!("realtime closed before connecting");
60
};
61
tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")
62
}
63
64
async fn print_own_presence(presence: &PresenceService, user_id: &str) {
65
match presence.status(user_id).await {
66
Ok(status) => println!(
67
"own presence: availability={} activity={}",
68
status.availability,
69
status.activity.as_deref().unwrap_or("-")
70
),
71
Err(error) => println!("own presence: failed {}", status_of(&error)),
72
}
73
}
74
75
fn outcome(result: chatsvc::Result<()>) -> String {
76
match result {
77
Ok(()) => "ok".to_owned(),
78
Err(error) => format!("failed {}", status_of(&error)),
79
}
80
}
81
82
fn status_of(error: &chatsvc::Error) -> String {
83
match error {
84
chatsvc::Error::Session(session::Error::Api { status, .. }) => format!("http {status}"),
85
_ => "no http status".to_owned(),
86
}
87
}
@@ -0,0 +1,87 @@1
use std::time::Duration;2
3
use chatsvc::{ActivityReporting, PresenceService, Realtime, RealtimeConfig, RealtimeEvent, StatusKind};4
use session::{DEFAULT_ENDPOINT, Session};5
6
const CONNECT_TIMEOUT: Duration = Duration::from_secs(60);7
const SETTLE: Duration = Duration::from_secs(10);8
9
#[tokio::main]10
async fn main() {11
let user_id = std::env::args().nth(1).expect("usage: presence_endpoint_probe <own user id GUID> [inactive wait seconds]");12
let inactive_wait = std::env::args()13
.nth(2)14
.and_then(|value| value.parse().ok())15
.map_or(SETTLE, Duration::from_secs);16
let endpoint = std::env::var("CDP_ENDPOINT").unwrap_or_else(|_| DEFAULT_ENDPOINT.to_owned());17
let session = Session::connect(&endpoint).await.expect("browser");18
let presence = PresenceService::new(&session);19
20
let config = RealtimeConfig {21
initially_active: true,22
..RealtimeConfig::default()23
};24
let mut realtime = Realtime::start_with(&session, config).await.expect("realtime start");25
let endpoint_id = wait_for_endpoint(&mut realtime).await;26
println!("# trouter connected");27
28
println!("register: {}", outcome(presence.register_endpoint(&endpoint_id, ActivityReporting::Transport).await));29
realtime.resend_activity();30
println!("# sent active");31
tokio::time::sleep(SETTLE).await;32
print_own_presence(&presence, &user_id).await;33
34
realtime.set_activity(false);35
println!("# sent inactive");36
tokio::time::sleep(inactive_wait).await;37
print_own_presence(&presence, &user_id).await;38
39
println!("http report inactive: {}", outcome(presence.report_activity(&endpoint_id, false).await));40
println!("unregister: {}", outcome(presence.unregister_endpoint(&endpoint_id).await));41
realtime.stop().await;42
println!("# stopped");43
}44
45
async fn wait_for_endpoint(realtime: &mut Realtime) -> String {46
let wait = async {47
let mut endpoint_id = None;48
let mut connected = false;49
while let Some(event) = realtime.recv().await {50
match event {51
RealtimeEvent::Endpoint(endpoint) => endpoint_id = Some(endpoint.endpoint_id),52
RealtimeEvent::Status(status) if status.kind == StatusKind::Connected => connected = true,53
_ => {}54
}55
if connected && let Some(endpoint_id) = endpoint_id.take() {56
return endpoint_id;57
}58
}59
panic!("realtime closed before connecting");60
};61
tokio::time::timeout(CONNECT_TIMEOUT, wait).await.expect("trouter did not connect")62
}63
64
async fn print_own_presence(presence: &PresenceService, user_id: &str) {65
match presence.status(user_id).await {66
Ok(status) => println!(67
"own presence: availability={} activity={}",68
status.availability,69
status.activity.as_deref().unwrap_or("-")70
),71
Err(error) => println!("own presence: failed {}", status_of(&error)),72
}73
}74
75
fn outcome(result: chatsvc::Result<()>) -> String {76
match result {77
Ok(()) => "ok".to_owned(),78
Err(error) => format!("failed {}", status_of(&error)),79
}80
}81
82
fn status_of(error: &chatsvc::Error) -> String {83
match error {84
chatsvc::Error::Session(session::Error::Api { status, .. }) => format!("http {status}"),85
_ => "no http status".to_owned(),86
}87
}@@ -44,8 +44,8 @@ pub use pins::{
44
44
PinnedMessage, Pins, TeamLayout,
45
45
};
46
46
pub use presence::{
47
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
48
WorkLocationKind, WorkLocationSource,
47
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,
48
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,
49
49
};
50
50
pub use reactions::{emotion_key, emotion_keys};
51
51
pub use realtime::{
@@ -44,8 +44,8 @@ pub use pins::{44
PinnedMessage, Pins, TeamLayout,44
PinnedMessage, Pins, TeamLayout,45
};45
};46
pub use presence::{46
pub use presence::{47
ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,47
ActivityReporting, ForcedAvailability, ForcedKind, PresenceService, PresenceStatus, StatusNote, WorkLocation,48
WorkLocationKind, WorkLocationSource,48
WorkLocationKind, WorkLocationSource, error_status, is_endpoint_missing,49
};49
};50
pub use reactions::{emotion_key, emotion_keys};50
pub use reactions::{emotion_key, emotion_keys};51
pub use realtime::{51
pub use realtime::{@@ -14,6 +14,9 @@ const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>";
14
14
const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";
15
15
const NEVER_YEAR: i32 = 9999;
16
16
const OFFLINE_ACTIVITY: &str = "OffWork";
17
const DESKTOP_USER_AGENT: &str = "Teams-V2-Desktop";
18
const WEB_USER_AGENT: &str = "Teams-V2-Web";
19
const ENDPOINT_ID_HEADER: &str = "x-ms-endpoint-id";
17
20
18
21
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
22
pub enum ForcedKind {
@@ -50,6 +53,21 @@ impl ForcedKind {
50
53
}
51
54
}
52
55
56
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57
pub enum ActivityReporting {
58
Transport,
59
Direct,
60
}
61
62
impl ActivityReporting {
63
fn code(self) -> &'static str {
64
match self {
65
ActivityReporting::Transport => "Transport",
66
ActivityReporting::Direct => "Direct",
67
}
68
}
69
}
70
53
71
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
54
72
pub struct ForcedAvailability {
55
73
pub kind: ForcedKind,
@@ -129,6 +147,31 @@ impl<T: CardTransport> PresenceService<T> {
129
147
self.send(request, &url).await.map(drop)
130
148
}
131
149
150
pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {
151
let url = format!("{BASE_URL}/me/endpoints/");
152
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));
153
request.headers = endpoint_headers(endpoint_id);
154
self.send(request, &url).await.map(drop)
155
}
156
157
pub async fn unregister_endpoint(&self, endpoint_id: &str) -> Result<()> {
158
let url = format!("{BASE_URL}/me/endpoints/{endpoint_id}");
159
let mut request = Request {
160
method: Method::Delete,
161
..Request::get(&url)
162
};
163
request.headers = endpoint_headers(endpoint_id);
164
self.send(request, &url).await.map(drop)
165
}
166
167
pub async fn report_activity(&self, endpoint_id: &str, active: bool) -> Result<()> {
168
let url = format!("{BASE_URL}/me/reportmyactivity/");
169
let body = json!({"endpointId": endpoint_id, "isActive": active});
170
let mut request = Request::with_body(Method::Post, &url, body);
171
request.headers = endpoint_headers(endpoint_id);
172
self.send(request, &url).await.map(drop)
173
}
174
132
175
pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {
133
176
let url = format!("{BASE_URL}/me/publishnote");
134
177
let body = note.map_or_else(|| json!({"message": ""}), note_body);
@@ -165,7 +208,9 @@ impl<T: CardTransport> PresenceService<T> {
165
208
}
166
209
167
210
async fn send(&self, mut request: Request, url: &str) -> Result<Value> {
168
request.headers = service_headers();
211
if request.headers.is_empty() {
212
request.headers = service_headers(WEB_USER_AGENT);
213
}
169
214
let answer = self
170
215
.transport
171
216
.send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))
@@ -181,9 +226,36 @@ impl<T: CardTransport> PresenceService<T> {
181
226
}
182
227
}
183
228
184
fn service_headers() -> Vec<(String, String)> {
229
pub fn error_status(error: &Error) -> Option<u16> {
230
match error {
231
Error::Session(session::Error::Api { status, .. }) => Some(*status),
232
_ => None,
233
}
234
}
235
236
pub fn is_endpoint_missing(error: &Error) -> bool {
237
error_status(error) == Some(404)
238
}
239
240
fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value {
241
json!({
242
"id": endpoint_id,
243
"availability": "Available",
244
"activity": "Available",
245
"activityReporting": reporting.code(),
246
"deviceType": "Desktop",
247
})
248
}
249
250
fn endpoint_headers(endpoint_id: &str) -> Vec<(String, String)> {
251
let mut headers = service_headers(DESKTOP_USER_AGENT);
252
headers.insert(1, (ENDPOINT_ID_HEADER.into(), endpoint_id.to_owned()));
253
headers
254
}
255
256
fn service_headers(user_agent: &str) -> Vec<(String, String)> {
185
257
vec![
186
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),
258
("x-ms-client-user-agent".into(), user_agent.into()),
187
259
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),
188
260
("x-ms-client-version".into(), CLIENT_VERSION.into()),
189
261
]
@@ -418,6 +490,95 @@ mod tests {
418
490
);
419
491
}
420
492
493
fn header_pairs(request: &Request) -> Vec<(&str, &str)> {
494
request
495
.headers
496
.iter()
497
.filter(|(name, _)| name != "x-ms-correlation-id")
498
.map(|(name, value)| (name.as_str(), value.as_str()))
499
.collect()
500
}
501
502
#[tokio::test]
503
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {
504
let service = service(200, Value::Null);
505
service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();
506
let (request, scope) = only_request(&service);
507
assert_eq!(request.method, Method::Put);
508
assert_eq!(
509
request.url,
510
"https://presence.teams.microsoft.com/v1/me/endpoints/"
511
);
512
assert_eq!(
513
request.body,
514
Some(json!({
515
"id": "epid-1",
516
"availability": "Available",
517
"activity": "Available",
518
"activityReporting": "Transport",
519
"deviceType": "Desktop",
520
}))
521
);
522
assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));
523
assert_eq!(
524
header_pairs(&request),
525
[
526
("x-ms-client-user-agent", "Teams-V2-Desktop"),
527
("x-ms-endpoint-id", "epid-1"),
528
("x-ms-client-version", CLIENT_VERSION),
529
]
530
);
531
}
532
533
#[tokio::test]
534
async fn register_endpoint_can_switch_to_direct_reporting() {
535
let service = service(200, Value::Null);
536
service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();
537
let (request, _) = only_request(&service);
538
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");
539
}
540
541
#[tokio::test]
542
async fn unregister_endpoint_deletes_by_id_without_body() {
543
let service = service(200, Value::Null);
544
service.unregister_endpoint("epid-1").await.unwrap();
545
let (request, _) = only_request(&service);
546
assert_eq!(request.method, Method::Delete);
547
assert_eq!(
548
request.url,
549
"https://presence.teams.microsoft.com/v1/me/endpoints/epid-1"
550
);
551
assert_eq!(request.body, None);
552
assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));
553
}
554
555
#[tokio::test]
556
async fn report_activity_posts_the_state_for_the_endpoint() {
557
let service = service(200, Value::Null);
558
service.report_activity("epid-1", false).await.unwrap();
559
let (request, _) = only_request(&service);
560
assert_eq!(request.method, Method::Post);
561
assert_eq!(
562
request.url,
563
"https://presence.teams.microsoft.com/v1/me/reportmyactivity/"
564
);
565
assert_eq!(
566
request.body,
567
Some(json!({"endpointId": "epid-1", "isActive": false}))
568
);
569
assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));
570
}
571
572
#[tokio::test]
573
async fn not_found_marks_the_endpoint_as_missing() {
574
let service = service(404, Value::Null);
575
let error = service.report_activity("epid-1", true).await.unwrap_err();
576
assert!(is_endpoint_missing(&error));
577
let service = self::service(500, Value::Null);
578
let error = service.report_activity("epid-1", true).await.unwrap_err();
579
assert!(!is_endpoint_missing(&error));
580
}
581
421
582
#[tokio::test]
422
583
async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {
423
584
let service = service(200, Value::Null);
@@ -14,6 +14,9 @@ const PINNED_NOTE_SUFFIX: &str = "<pinnednote></pinnednote>";14
const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";14
const NEVER_EXPIRES: &str = "9999-12-31T23:59:59.999Z";15
const NEVER_YEAR: i32 = 9999;15
const NEVER_YEAR: i32 = 9999;16
const OFFLINE_ACTIVITY: &str = "OffWork";16
const OFFLINE_ACTIVITY: &str = "OffWork";17
const DESKTOP_USER_AGENT: &str = "Teams-V2-Desktop";18
const WEB_USER_AGENT: &str = "Teams-V2-Web";19
const ENDPOINT_ID_HEADER: &str = "x-ms-endpoint-id";17
20
18
#[derive(Debug, Clone, Copy, PartialEq, Eq)]21
#[derive(Debug, Clone, Copy, PartialEq, Eq)]19
pub enum ForcedKind {22
pub enum ForcedKind {@@ -50,6 +53,21 @@ impl ForcedKind {50
}53
}51
}54
}52
55
56
#[derive(Debug, Clone, Copy, PartialEq, Eq)]57
pub enum ActivityReporting {58
Transport,59
Direct,60
}61
62
impl ActivityReporting {63
fn code(self) -> &'static str {64
match self {65
ActivityReporting::Transport => "Transport",66
ActivityReporting::Direct => "Direct",67
}68
}69
}70
53
#[derive(Debug, Clone, Copy, PartialEq, Eq)]71
#[derive(Debug, Clone, Copy, PartialEq, Eq)]54
pub struct ForcedAvailability {72
pub struct ForcedAvailability {55
pub kind: ForcedKind,73
pub kind: ForcedKind,@@ -129,6 +147,31 @@ impl<T: CardTransport> PresenceService<T> {129
self.send(request, &url).await.map(drop)147
self.send(request, &url).await.map(drop)130
}148
}131
149
150
pub async fn register_endpoint(&self, endpoint_id: &str, reporting: ActivityReporting) -> Result<()> {151
let url = format!("{BASE_URL}/me/endpoints/");152
let mut request = Request::with_body(Method::Put, &url, endpoint_body(endpoint_id, reporting));153
request.headers = endpoint_headers(endpoint_id);154
self.send(request, &url).await.map(drop)155
}156
157
pub async fn unregister_endpoint(&self, endpoint_id: &str) -> Result<()> {158
let url = format!("{BASE_URL}/me/endpoints/{endpoint_id}");159
let mut request = Request {160
method: Method::Delete,161
..Request::get(&url)162
};163
request.headers = endpoint_headers(endpoint_id);164
self.send(request, &url).await.map(drop)165
}166
167
pub async fn report_activity(&self, endpoint_id: &str, active: bool) -> Result<()> {168
let url = format!("{BASE_URL}/me/reportmyactivity/");169
let body = json!({"endpointId": endpoint_id, "isActive": active});170
let mut request = Request::with_body(Method::Post, &url, body);171
request.headers = endpoint_headers(endpoint_id);172
self.send(request, &url).await.map(drop)173
}174
132
pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {175
pub async fn set_note(&self, note: Option<&StatusNote>) -> Result<()> {133
let url = format!("{BASE_URL}/me/publishnote");176
let url = format!("{BASE_URL}/me/publishnote");134
let body = note.map_or_else(|| json!({"message": ""}), note_body);177
let body = note.map_or_else(|| json!({"message": ""}), note_body);@@ -165,7 +208,9 @@ impl<T: CardTransport> PresenceService<T> {165
}208
}166
209
167
async fn send(&self, mut request: Request, url: &str) -> Result<Value> {210
async fn send(&self, mut request: Request, url: &str) -> Result<Value> {168
request.headers = service_headers();211
if request.headers.is_empty() {212
request.headers = service_headers(WEB_USER_AGENT);213
}169
let answer = self214
let answer = self170
.transport215
.transport171
.send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))216
.send(request, Scope::new(PRESENCE, PRESENCE_SCOPE))@@ -181,9 +226,36 @@ impl<T: CardTransport> PresenceService<T> {181
}226
}182
}227
}183
228
184
fn service_headers() -> Vec<(String, String)> {229
pub fn error_status(error: &Error) -> Option<u16> {230
match error {231
Error::Session(session::Error::Api { status, .. }) => Some(*status),232
_ => None,233
}234
}235
236
pub fn is_endpoint_missing(error: &Error) -> bool {237
error_status(error) == Some(404)238
}239
240
fn endpoint_body(endpoint_id: &str, reporting: ActivityReporting) -> Value {241
json!({242
"id": endpoint_id,243
"availability": "Available",244
"activity": "Available",245
"activityReporting": reporting.code(),246
"deviceType": "Desktop",247
})248
}249
250
fn endpoint_headers(endpoint_id: &str) -> Vec<(String, String)> {251
let mut headers = service_headers(DESKTOP_USER_AGENT);252
headers.insert(1, (ENDPOINT_ID_HEADER.into(), endpoint_id.to_owned()));253
headers254
}255
256
fn service_headers(user_agent: &str) -> Vec<(String, String)> {185
vec![257
vec![186
("x-ms-client-user-agent".into(), "Teams-V2-Web".into()),258
("x-ms-client-user-agent".into(), user_agent.into()),187
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),259
("x-ms-correlation-id".into(), Uuid::new_v4().to_string()),188
("x-ms-client-version".into(), CLIENT_VERSION.into()),260
("x-ms-client-version".into(), CLIENT_VERSION.into()),189
]261
]@@ -418,6 +490,95 @@ mod tests {418
);490
);419
}491
}420
492
493
fn header_pairs(request: &Request) -> Vec<(&str, &str)> {494
request495
.headers496
.iter()497
.filter(|(name, _)| name != "x-ms-correlation-id")498
.map(|(name, value)| (name.as_str(), value.as_str()))499
.collect()500
}501
502
#[tokio::test]503
async fn register_endpoint_puts_the_transport_endpoint_as_desktop() {504
let service = service(200, Value::Null);505
service.register_endpoint("epid-1", ActivityReporting::Transport).await.unwrap();506
let (request, scope) = only_request(&service);507
assert_eq!(request.method, Method::Put);508
assert_eq!(509
request.url,510
"https://presence.teams.microsoft.com/v1/me/endpoints/"511
);512
assert_eq!(513
request.body,514
Some(json!({515
"id": "epid-1",516
"availability": "Available",517
"activity": "Available",518
"activityReporting": "Transport",519
"deviceType": "Desktop",520
}))521
);522
assert_eq!(scope, Scope::new(PRESENCE, "user_impersonation"));523
assert_eq!(524
header_pairs(&request),525
[526
("x-ms-client-user-agent", "Teams-V2-Desktop"),527
("x-ms-endpoint-id", "epid-1"),528
("x-ms-client-version", CLIENT_VERSION),529
]530
);531
}532
533
#[tokio::test]534
async fn register_endpoint_can_switch_to_direct_reporting() {535
let service = service(200, Value::Null);536
service.register_endpoint("epid-1", ActivityReporting::Direct).await.unwrap();537
let (request, _) = only_request(&service);538
assert_eq!(request.body.unwrap()["activityReporting"], "Direct");539
}540
541
#[tokio::test]542
async fn unregister_endpoint_deletes_by_id_without_body() {543
let service = service(200, Value::Null);544
service.unregister_endpoint("epid-1").await.unwrap();545
let (request, _) = only_request(&service);546
assert_eq!(request.method, Method::Delete);547
assert_eq!(548
request.url,549
"https://presence.teams.microsoft.com/v1/me/endpoints/epid-1"550
);551
assert_eq!(request.body, None);552
assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));553
}554
555
#[tokio::test]556
async fn report_activity_posts_the_state_for_the_endpoint() {557
let service = service(200, Value::Null);558
service.report_activity("epid-1", false).await.unwrap();559
let (request, _) = only_request(&service);560
assert_eq!(request.method, Method::Post);561
assert_eq!(562
request.url,563
"https://presence.teams.microsoft.com/v1/me/reportmyactivity/"564
);565
assert_eq!(566
request.body,567
Some(json!({"endpointId": "epid-1", "isActive": false}))568
);569
assert!(header_pairs(&request).contains(&("x-ms-endpoint-id", "epid-1")));570
}571
572
#[tokio::test]573
async fn not_found_marks_the_endpoint_as_missing() {574
let service = service(404, Value::Null);575
let error = service.report_activity("epid-1", true).await.unwrap_err();576
assert!(is_endpoint_missing(&error));577
let service = self::service(500, Value::Null);578
let error = service.report_activity("epid-1", true).await.unwrap_err();579
assert!(!is_endpoint_missing(&error));580
}581
421
#[tokio::test]582
#[tokio::test]422
async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {583
async fn offline_carries_the_off_work_activity_and_no_expiry_when_open() {423
let service = service(200, Value::Null);584
let service = service(200, Value::Null);@@ -4,12 +4,13 @@ mod host;
4
4
mod runner;
5
5
6
6
use std::pin::Pin;
7
use std::sync::Arc;
7
8
use std::task::{Context, Poll};
8
9
use std::time::Duration;
9
10
10
11
use futures_util::Stream;
11
12
use session::Session;
12
use tokio::sync::{mpsc, oneshot};
13
use tokio::sync::{Notify, mpsc, oneshot, watch};
13
14
use tokio::task::JoinHandle;
14
15
15
16
pub use event::{
@@ -35,6 +36,7 @@ pub struct RealtimeConfig {
35
36
pub instance: InstanceNames,
36
37
pub forward_callbacks: bool,
37
38
pub ringable: bool,
39
pub initially_active: bool,
38
40
}
39
41
40
42
/// Page globals of one Trouter client; a second client in the same tab needs its own names.
@@ -67,6 +69,7 @@ impl Default for RealtimeConfig {
67
69
instance: InstanceNames::default(),
68
70
forward_callbacks: false,
69
71
ringable: false,
72
initially_active: false,
70
73
}
71
74
}
72
75
}
@@ -76,6 +79,8 @@ pub struct Realtime {
76
79
events: mpsc::UnboundedReceiver<RealtimeEvent>,
77
80
callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
78
81
replier: CallbackReplier,
82
activity: watch::Sender<bool>,
83
resend: Arc<Notify>,
79
84
stop: Option<oneshot::Sender<oneshot::Sender<()>>>,
80
85
task: JoinHandle<()>,
81
86
}
@@ -94,6 +99,8 @@ impl Realtime {
94
99
let (output, events) = mpsc::unbounded_channel();
95
100
let (callback_output, callbacks) = mpsc::unbounded_channel();
96
101
let (reply_sender, replies) = mpsc::unbounded_channel();
102
let (activity, activity_receiver) = watch::channel(config.initially_active);
103
let resend = Arc::new(Notify::new());
97
104
let (stop, stop_receiver) = oneshot::channel();
98
105
let mut runner = Runner::new(
99
106
session,
@@ -105,6 +112,8 @@ impl Realtime {
105
112
output: callback_output,
106
113
replies,
107
114
},
115
activity_receiver,
116
resend.clone(),
108
117
);
109
118
if let Err(error) = runner.ensure().await {
110
119
attached.shutdown().await;
@@ -118,6 +127,8 @@ impl Realtime {
118
127
replier: CallbackReplier {
119
128
sender: reply_sender,
120
129
},
130
activity,
131
resend,
121
132
stop: Some(stop),
122
133
task,
123
134
})
@@ -140,6 +151,14 @@ impl Realtime {
140
151
self.replier.clone()
141
152
}
142
153
154
pub fn set_activity(&self, active: bool) {
155
self.activity.send_replace(active);
156
}
157
158
pub fn resend_activity(&self) {
159
self.resend.notify_one();
160
}
161
143
162
/// Deletes the registration and closes the page-side socket.
144
163
pub async fn stop(mut self) {
145
164
if let Some(stop) = self.stop.take() {
@@ -4,12 +4,13 @@ mod host;4
mod runner;4
mod runner;5
5
6
use std::pin::Pin;6
use std::pin::Pin;7
use std::sync::Arc;7
use std::task::{Context, Poll};8
use std::task::{Context, Poll};8
use std::time::Duration;9
use std::time::Duration;9
10
10
use futures_util::Stream;11
use futures_util::Stream;11
use session::Session;12
use session::Session;12
use tokio::sync::{mpsc, oneshot};13
use tokio::sync::{Notify, mpsc, oneshot, watch};13
use tokio::task::JoinHandle;14
use tokio::task::JoinHandle;14
15
15
pub use event::{16
pub use event::{@@ -35,6 +36,7 @@ pub struct RealtimeConfig {35
pub instance: InstanceNames,36
pub instance: InstanceNames,36
pub forward_callbacks: bool,37
pub forward_callbacks: bool,37
pub ringable: bool,38
pub ringable: bool,39
pub initially_active: bool,38
}40
}39
41
40
/// Page globals of one Trouter client; a second client in the same tab needs its own names.42
/// Page globals of one Trouter client; a second client in the same tab needs its own names.@@ -67,6 +69,7 @@ impl Default for RealtimeConfig {67
instance: InstanceNames::default(),69
instance: InstanceNames::default(),68
forward_callbacks: false,70
forward_callbacks: false,69
ringable: false,71
ringable: false,72
initially_active: false,70
}73
}71
}74
}72
}75
}@@ -76,6 +79,8 @@ pub struct Realtime {76
events: mpsc::UnboundedReceiver<RealtimeEvent>,79
events: mpsc::UnboundedReceiver<RealtimeEvent>,77
callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,80
callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,78
replier: CallbackReplier,81
replier: CallbackReplier,82
activity: watch::Sender<bool>,83
resend: Arc<Notify>,79
stop: Option<oneshot::Sender<oneshot::Sender<()>>>,84
stop: Option<oneshot::Sender<oneshot::Sender<()>>>,80
task: JoinHandle<()>,85
task: JoinHandle<()>,81
}86
}@@ -94,6 +99,8 @@ impl Realtime {94
let (output, events) = mpsc::unbounded_channel();99
let (output, events) = mpsc::unbounded_channel();95
let (callback_output, callbacks) = mpsc::unbounded_channel();100
let (callback_output, callbacks) = mpsc::unbounded_channel();96
let (reply_sender, replies) = mpsc::unbounded_channel();101
let (reply_sender, replies) = mpsc::unbounded_channel();102
let (activity, activity_receiver) = watch::channel(config.initially_active);103
let resend = Arc::new(Notify::new());97
let (stop, stop_receiver) = oneshot::channel();104
let (stop, stop_receiver) = oneshot::channel();98
let mut runner = Runner::new(105
let mut runner = Runner::new(99
session,106
session,@@ -105,6 +112,8 @@ impl Realtime {105
output: callback_output,112
output: callback_output,106
replies,113
replies,107
},114
},115
activity_receiver,116
resend.clone(),108
);117
);109
if let Err(error) = runner.ensure().await {118
if let Err(error) = runner.ensure().await {110
attached.shutdown().await;119
attached.shutdown().await;@@ -118,6 +127,8 @@ impl Realtime {118
replier: CallbackReplier {127
replier: CallbackReplier {119
sender: reply_sender,128
sender: reply_sender,120
},129
},130
activity,131
resend,121
stop: Some(stop),132
stop: Some(stop),122
task,133
task,123
})134
})@@ -140,6 +151,14 @@ impl Realtime {140
self.replier.clone()151
self.replier.clone()141
}152
}142
153
154
pub fn set_activity(&self, active: bool) {155
self.activity.send_replace(active);156
}157
158
pub fn resend_activity(&self) {159
self.resend.notify_one();160
}161
143
/// Deletes the registration and closes the page-side socket.162
/// Deletes the registration and closes the page-side socket.144
pub async fn stop(mut self) {163
pub async fn stop(mut self) {145
if let Some(stop) = self.stop.take() {164
if let Some(stop) = self.stop.take() {@@ -1,8 +1,9 @@
1
use std::sync::Arc;
1
2
use std::time::Duration;
2
3
3
4
use serde_json::{Value, json};
4
5
use session::{App, Session, TabControl, TabEvents};
5
use tokio::sync::{mpsc, oneshot};
6
use tokio::sync::{Notify, mpsc, oneshot, watch};
6
7
use tokio::time::{MissedTickBehavior, interval, sleep};
7
8
8
9
use super::RealtimeConfig;
@@ -49,11 +50,26 @@ impl PageScript {
49
50
50
51
fn ensure_body(&self) -> String {
51
52
format!(
52
"{}\nreturn window.{}.ensure({{token, host: args.host}});",
53
"{}\nreturn window.{}.ensure({{token, host: args.host, activity: args.activity}});",
53
54
self.worker_source, self.global_name
54
55
)
55
56
}
56
57
58
fn set_activity_expression(&self, active: bool) -> String {
59
format!(
60
"window.{name} ? window.{name}.setActivity('{state}') : null",
61
name = self.global_name,
62
state = activity_label(active)
63
)
64
}
65
66
fn resend_activity_expression(&self) -> String {
67
format!(
68
"window.{name} ? window.{name}.resendActivity() : null",
69
name = self.global_name
70
)
71
}
72
57
73
fn stop_expression(&self) -> String {
58
74
format!(
59
75
"window.{name} ? window.{name}.stop() : null",
@@ -114,6 +130,8 @@ pub(super) struct Runner {
114
130
callbacks: CallbackPipes,
115
131
host: String,
116
132
output: mpsc::UnboundedSender<RealtimeEvent>,
133
activity: watch::Receiver<bool>,
134
resend: Arc<Notify>,
117
135
force_refresh: bool,
118
136
last_error: Option<String>,
119
137
}
@@ -126,6 +144,8 @@ impl Runner {
126
144
host: String,
127
145
output: mpsc::UnboundedSender<RealtimeEvent>,
128
146
callbacks: CallbackPipes,
147
activity: watch::Receiver<bool>,
148
resend: Arc<Notify>,
129
149
) -> Self {
130
150
Runner {
131
151
session,
@@ -134,13 +154,15 @@ impl Runner {
134
154
callbacks,
135
155
host,
136
156
output,
157
activity,
158
resend,
137
159
force_refresh: false,
138
160
last_error: None,
139
161
}
140
162
}
141
163
142
164
pub(super) async fn ensure(&mut self) -> session::Result<Value> {
143
let args = json!({"host": self.host});
165
let args = json!({"host": self.host, "activity": activity_label(*self.activity.borrow())});
144
166
let outcome = self
145
167
.session
146
168
.run_with_token(
@@ -223,6 +245,16 @@ impl Runner {
223
245
}
224
246
}
225
247
_ = tick.tick() => self.ensure_and_report().await,
248
_ = self.resend.notified() => {
249
let expression = self.script.resend_activity_expression();
250
let _ = attached.control.evaluate(&expression).await;
251
}
252
changed = self.activity.changed() => {
253
if changed.is_ok() {
254
let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());
255
let _ = attached.control.evaluate(&expression).await;
256
}
257
}
226
258
Some(reply) = self.callbacks.replies.recv() => {
227
259
let expression = reply_expression(&self.script.global_name, &reply);
228
260
let _ = attached.control.evaluate(&expression).await;
@@ -279,6 +311,10 @@ impl Runner {
279
311
}
280
312
}
281
313
314
fn activity_label(active: bool) -> &'static str {
315
if active { "active" } else { "inactive" }
316
}
317
282
318
fn is_main_frame_navigation(method: &str, params: &Value) -> bool {
283
319
method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()
284
320
}
@@ -304,6 +340,33 @@ mod tests {
304
340
assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));
305
341
}
306
342
343
#[test]
344
fn activity_is_labelled_and_set_through_the_page_global() {
345
assert_eq!(activity_label(true), "active");
346
assert_eq!(activity_label(false), "inactive");
347
let script = PageScript::new(&RealtimeConfig::default());
348
assert_eq!(
349
script.set_activity_expression(false),
350
"window.__chatsvcTrouter ? window.__chatsvcTrouter.setActivity('inactive') : null"
351
);
352
}
353
354
#[test]
355
fn resend_goes_through_the_page_global() {
356
let script = PageScript::new(&RealtimeConfig::default());
357
assert_eq!(
358
script.resend_activity_expression(),
359
"window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"
360
);
361
}
362
363
#[test]
364
fn worker_reports_activity_on_change_only() {
365
let worker = PageScript::new(&RealtimeConfig::default()).worker_source;
366
assert!(!worker.contains("activity();"));
367
assert_eq!(worker.matches("'user.activity'").count(), 1);
368
}
369
307
370
#[test]
308
371
fn rejected_bearer_forces_token_refresh() {
309
372
assert!(is_auth_failure("registrar_http_401"));
@@ -318,7 +381,7 @@ mod tests {
318
381
assert!(
319
382
ensure_body
320
383
.trim_end()
321
.ends_with("window.__chatsvcTrouter.ensure({token, host: args.host});")
384
.ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")
322
385
);
323
386
assert_eq!(ensure_body.matches("const VERSION").count(), 1);
324
387
}
@@ -1,8 +1,9 @@1
use std::sync::Arc;1
use std::time::Duration;2
use std::time::Duration;2
3
3
use serde_json::{Value, json};4
use serde_json::{Value, json};4
use session::{App, Session, TabControl, TabEvents};5
use session::{App, Session, TabControl, TabEvents};5
use tokio::sync::{mpsc, oneshot};6
use tokio::sync::{Notify, mpsc, oneshot, watch};6
use tokio::time::{MissedTickBehavior, interval, sleep};7
use tokio::time::{MissedTickBehavior, interval, sleep};7
8
8
use super::RealtimeConfig;9
use super::RealtimeConfig;@@ -49,11 +50,26 @@ impl PageScript {49
50
50
fn ensure_body(&self) -> String {51
fn ensure_body(&self) -> String {51
format!(52
format!(52
"{}\nreturn window.{}.ensure({{token, host: args.host}});",53
"{}\nreturn window.{}.ensure({{token, host: args.host, activity: args.activity}});",53
self.worker_source, self.global_name54
self.worker_source, self.global_name54
)55
)55
}56
}56
57
58
fn set_activity_expression(&self, active: bool) -> String {59
format!(60
"window.{name} ? window.{name}.setActivity('{state}') : null",61
name = self.global_name,62
state = activity_label(active)63
)64
}65
66
fn resend_activity_expression(&self) -> String {67
format!(68
"window.{name} ? window.{name}.resendActivity() : null",69
name = self.global_name70
)71
}72
57
fn stop_expression(&self) -> String {73
fn stop_expression(&self) -> String {58
format!(74
format!(59
"window.{name} ? window.{name}.stop() : null",75
"window.{name} ? window.{name}.stop() : null",@@ -114,6 +130,8 @@ pub(super) struct Runner {114
callbacks: CallbackPipes,130
callbacks: CallbackPipes,115
host: String,131
host: String,116
output: mpsc::UnboundedSender<RealtimeEvent>,132
output: mpsc::UnboundedSender<RealtimeEvent>,133
activity: watch::Receiver<bool>,134
resend: Arc<Notify>,117
force_refresh: bool,135
force_refresh: bool,118
last_error: Option<String>,136
last_error: Option<String>,119
}137
}@@ -126,6 +144,8 @@ impl Runner {126
host: String,144
host: String,127
output: mpsc::UnboundedSender<RealtimeEvent>,145
output: mpsc::UnboundedSender<RealtimeEvent>,128
callbacks: CallbackPipes,146
callbacks: CallbackPipes,147
activity: watch::Receiver<bool>,148
resend: Arc<Notify>,129
) -> Self {149
) -> Self {130
Runner {150
Runner {131
session,151
session,@@ -134,13 +154,15 @@ impl Runner {134
callbacks,154
callbacks,135
host,155
host,136
output,156
output,157
activity,158
resend,137
force_refresh: false,159
force_refresh: false,138
last_error: None,160
last_error: None,139
}161
}140
}162
}141
163
142
pub(super) async fn ensure(&mut self) -> session::Result<Value> {164
pub(super) async fn ensure(&mut self) -> session::Result<Value> {143
let args = json!({"host": self.host});165
let args = json!({"host": self.host, "activity": activity_label(*self.activity.borrow())});144
let outcome = self166
let outcome = self145
.session167
.session146
.run_with_token(168
.run_with_token(@@ -223,6 +245,16 @@ impl Runner {223
}245
}224
}246
}225
_ = tick.tick() => self.ensure_and_report().await,247
_ = tick.tick() => self.ensure_and_report().await,248
_ = self.resend.notified() => {249
let expression = self.script.resend_activity_expression();250
let _ = attached.control.evaluate(&expression).await;251
}252
changed = self.activity.changed() => {253
if changed.is_ok() {254
let expression = self.script.set_activity_expression(*self.activity.borrow_and_update());255
let _ = attached.control.evaluate(&expression).await;256
}257
}226
Some(reply) = self.callbacks.replies.recv() => {258
Some(reply) = self.callbacks.replies.recv() => {227
let expression = reply_expression(&self.script.global_name, &reply);259
let expression = reply_expression(&self.script.global_name, &reply);228
let _ = attached.control.evaluate(&expression).await;260
let _ = attached.control.evaluate(&expression).await;@@ -279,6 +311,10 @@ impl Runner {279
}311
}280
}312
}281
313
314
fn activity_label(active: bool) -> &'static str {315
if active { "active" } else { "inactive" }316
}317
282
fn is_main_frame_navigation(method: &str, params: &Value) -> bool {318
fn is_main_frame_navigation(method: &str, params: &Value) -> bool {283
method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()319
method == "Page.frameNavigated" && params.pointer("/frame/parentId").is_none()284
}320
}@@ -304,6 +340,33 @@ mod tests {304
assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));340
assert!(!is_main_frame_navigation("Page.loadEventFired", &json!({})));305
}341
}306
342
343
#[test]344
fn activity_is_labelled_and_set_through_the_page_global() {345
assert_eq!(activity_label(true), "active");346
assert_eq!(activity_label(false), "inactive");347
let script = PageScript::new(&RealtimeConfig::default());348
assert_eq!(349
script.set_activity_expression(false),350
"window.__chatsvcTrouter ? window.__chatsvcTrouter.setActivity('inactive') : null"351
);352
}353
354
#[test]355
fn resend_goes_through_the_page_global() {356
let script = PageScript::new(&RealtimeConfig::default());357
assert_eq!(358
script.resend_activity_expression(),359
"window.__chatsvcTrouter ? window.__chatsvcTrouter.resendActivity() : null"360
);361
}362
363
#[test]364
fn worker_reports_activity_on_change_only() {365
let worker = PageScript::new(&RealtimeConfig::default()).worker_source;366
assert!(!worker.contains("activity();"));367
assert_eq!(worker.matches("'user.activity'").count(), 1);368
}369
307
#[test]370
#[test]308
fn rejected_bearer_forces_token_refresh() {371
fn rejected_bearer_forces_token_refresh() {309
assert!(is_auth_failure("registrar_http_401"));372
assert!(is_auth_failure("registrar_http_401"));@@ -318,7 +381,7 @@ mod tests {318
assert!(381
assert!(319
ensure_body382
ensure_body320
.trim_end()383
.trim_end()321
.ends_with("window.__chatsvcTrouter.ensure({token, host: args.host});")384
.ends_with("window.__chatsvcTrouter.ensure({token, host: args.host, activity: args.activity});")322
);385
);323
assert_eq!(ensure_body.matches("const VERSION").count(), 1);386
assert_eq!(ensure_body.matches("const VERSION").count(), 1);324
}387
}@@ -172,7 +172,7 @@ async fn start_injects_worker_and_ensures_with_default_host() {
172
172
let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();
173
173
assert_eq!(
174
174
arguments,
175
serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com"})
175
serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com", "activity": "inactive"})
176
176
);
177
177
realtime.stop().await;
178
178
}
@@ -172,7 +172,7 @@ async fn start_injects_worker_and_ensures_with_default_host() {172
let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();172
let arguments: serde_json::Value = serde_json::from_str(arguments_json).unwrap();173
assert_eq!(173
assert_eq!(174
arguments,174
arguments,175
serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com"})175
serde_json::json!({"host": "go-eu.trouter.teams.microsoft.com", "activity": "inactive"})176
);176
);177
realtime.stop().await;177
realtime.stop().await;178
}178
}