BlueGit

ict rusty-teams

merge: scheduling, RSVP, reminders and pre-join

- Don't use audio also stops the software mic path and ignores later mic settings
- Pre-join preview applies the camera effects

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
ebb531d757a86d2f5ebb2270ffdce5baeb5c8976
38 files changed +3059 −173
README.md +1 −1
@@ -56,7 +56,7 @@
56 56 - `:thumbsup:` and `:)` convert as you type, German aliases included
57 57 - Schedule send: right-click send or `Ctrl+Shift+Enter`
58 58 - Drafts and unsent messages survive a restart
59 - Keyboard like Teams: `Ctrl+1`..`4` panels and tabs, `Alt+Up` / `Alt+Down` next chat, call keys on `Ctrl+Shift+A/D/H/O/E/M`, `Ctrl+.` lists them all
59 - Keyboard like Teams: `Ctrl+1`..`4` panels and tabs, `Alt+Up` / `Alt+Down` next chat, call keys on `Ctrl+Shift+A/D/H/O/E/M/J`, `Ctrl+.` lists them all
60 60
61 61 **Calls**
62 62 - Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
@@ -56,7 +56,7 @@
56- `:thumbsup:` and `:)` convert as you type, German aliases included
56- `:thumbsup:` and `:)` convert as you type, German aliases included
57- Schedule send: right-click send or `Ctrl+Shift+Enter`
57- Schedule send: right-click send or `Ctrl+Shift+Enter`
58- Drafts and unsent messages survive a restart
58- Drafts and unsent messages survive a restart
59- Keyboard like Teams: `Ctrl+1`..`4` panels and tabs, `Alt+Up` / `Alt+Down` next chat, call keys on `Ctrl+Shift+A/D/H/O/E/M`, `Ctrl+.` lists them all
59- Keyboard like Teams: `Ctrl+1`..`4` panels and tabs, `Alt+Up` / `Alt+Down` next chat, call keys on `Ctrl+Shift+A/D/H/O/E/M/J`, `Ctrl+.` lists them all
60
60
61**Calls**
61**Calls**
62- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
62- Test call to the Teams Echo bot from the avatar menu: native WebRTC audio, mute (`Ctrl+Shift+M`), device switching, mini window while you read other chats
ROADMAP.md +7 −3
@@ -2,7 +2,7 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 89 %** (81 done, 15 partial, 4 missing of 100). Partial counts half.
5 **Parity: 87 %** (81 done, 18 partial, 4 missing of 103). Partial counts half.
6 6
7 7 ## By area
8 8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18 18 | [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19 19 | [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20 20 | [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21 | [Calls and meetings](#calls-and-meetings) | 61 % | 4 | 14 | 0 |
21 | [Calls and meetings](#calls-and-meetings) | 60 % | 4 | 17 | 0 |
22 22
23 23 ## Next
24 24
@@ -139,7 +139,7 @@ Feature parity with the Microsoft Teams desktop client.
139 139 | Full-text search over cached messages | Done | |
140 140 | Jump to a message from search | Done | |
141 141 | Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
142 | Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
142 | Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, J join from a meeting reminder, Space held with Ctrl to talk while muted, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
143 143
144 144 ## Presence and people
145 145
@@ -186,6 +186,10 @@ Feature parity with the Microsoft Teams desktop client.
186 186 | Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
187 187 | Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
188 188 | In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
189 | Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Graph `POST /me/events` with `isOnlineMeeting` and `teamsForBusiness`, times in UTC. Body building unit tested; never run against a real calendar |
190 | Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Graph `accept`, `tentativelyAccept`, `decline`, falls back to the iCalUId lookup when the Teams id is not a Graph id. Not run against a real invitation |
191 | Meeting start reminder | Partial | Toast 5 min before and at the start of an Upcoming meeting: title, time, Join, Dismiss; Ctrl+Shift+J joins from the latest. Quiet during Do not disturb and while in a call. Driven by the polled calendar; push event 128 not wired (the realtime layer does not receive it) |
192 | Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
189 193
190 194 ## Agents
191 195
@@ -2,7 +2,7 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 89 %** (81 done, 15 partial, 4 missing of 100). Partial counts half.
5**Parity: 87 %** (81 done, 18 partial, 4 missing of 103). Partial counts half.
6
6
7## By area
7## By area
8
8
@@ -18,7 +18,7 @@ Feature parity with the Microsoft Teams desktop client.
18| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
18| [Search and navigation](#search-and-navigation) | 100 % | 5 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
19| [Presence and people](#presence-and-people) | 100 % | 4 | 0 | 0 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
20| [Look and settings](#look-and-settings) | 50 % | 2 | 0 | 2 |
21| [Calls and meetings](#calls-and-meetings) | 61 % | 4 | 14 | 0 |
21| [Calls and meetings](#calls-and-meetings) | 60 % | 4 | 17 | 0 |
22
22
23## Next
23## Next
24
24
@@ -139,7 +139,7 @@ Feature parity with the Microsoft Teams desktop client.
139| Full-text search over cached messages | Done | |
139| Full-text search over cached messages | Done | |
140| Jump to a message from search | Done | |
140| Jump to a message from search | Done | |
141| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
141| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
142| Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
142| Keyboard shortcuts like Teams | Done | Ctrl+1 Activity, 2 Chats, 3 Channels, 4 Saved; Alt+Up/Down previous and next chat or channel in the visible list, also while typing; calls Ctrl+Shift+A accept, D decline, H hang up, O camera, E share menu, K raise hand, Y lobby, M mute, J join from a meeting reminder, Space held with Ctrl to talk while muted, F11 full screen, Alt+Shift+A / V start an audio / video call in the open chat; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
143
143
144## Presence and people
144## Presence and people
145
145
@@ -186,6 +186,10 @@ Feature parity with the Microsoft Teams desktop client.
186| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
186| Call history | Done | Calls tab (Ctrl+5) from the Teams call log: avatar, name, Missed call in red, Outgoing / Incoming / Meeting with duration, time like the chat list. Click calls back or opens the meeting chat; right-click Call back and Open chat. Refreshes on tab open and after a call ends. Read live (counts and shapes); no realtime update |
187| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
187| Join by link or meeting ID | Done | "Join with ID" dialog, "Paste a meeting link", Join chip next to Teams meeting links in the composer and messages. IDs and /meet/ links resolve through a roster-only conversation like Teams web; verified live with a self-created scheduled meeting (same meeting chat found) |
188| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
188| In a call shown in presence | Done | "In a call", "In a meeting", "Presenting" from Teams activity on profile cards and chat headers; no notification sounds during a native call |
189| Schedule a meeting | Partial | Calls tab "New meeting": title, people chips, date, start, end (next half hour, 30 min), Repeat (does not repeat, daily, weekdays, weekly), details, Teams meeting always on. Graph `POST /me/events` with `isOnlineMeeting` and `teamsForBusiness`, times in UTC. Body building unit tested; never run against a real calendar |
190| Answer meeting invitations | Partial | Upcoming rows of invited meetings show Accepted / Tentative / Declined / Respond as a menu with "Send a response" (default on); own meetings say Organizer. Graph `accept`, `tentativelyAccept`, `decline`, falls back to the iCalUId lookup when the Teams id is not a Graph id. Not run against a real invitation |
191| Meeting start reminder | Partial | Toast 5 min before and at the start of an Upcoming meeting: title, time, Join, Dismiss; Ctrl+Shift+J joins from the latest. Quiet during Do not disturb and while in a call. Driven by the polled calendar; push event 128 not wired (the realtime layer does not receive it) |
192| Pre-join screen | Partial | Join from Upcoming, chat, Join with ID, link or reminder opens a screen in the chat pane: camera preview, camera and mic switches, background menu, camera, microphone and speaker selects, "Computer audio" or "Don't use audio" (audio off in both directions), Join now, Cancel. Camera, mic and devices remembered. 1:1 calls and Meet now skip it. Checked in the demo only |
189
193
190## Agents
194## Agents
191
195
crates/app/src/app_state.rs +15 −0
@@ -68,6 +68,7 @@ pub enum AppEvent {
68 68 Ring,
69 69 LiveMeeting,
70 70 MissedCall(MissedCall),
71 MeetingReminder,
71 72 }
72 73
73 74 #[derive(Debug, Clone, Copy, Default)]
@@ -130,6 +131,12 @@ pub struct AppState {
130 131 pub call_mic: calling::MicSettings,
131 132 pub call_effects: calling::CameraEffects,
132 133 pub meet_now_pending: bool,
134 pub prejoin: Option<crate::call::PendingJoin>,
135 pub prejoin_count: u64,
136 pub join_options: crate::call::JoinOptions,
137 pub rsvp_send_response: bool,
138 pub meeting_toasts: crate::call::MeetingToasts,
139 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
133 140 pub call_backgrounds: crate::call::BackgroundLibrary,
134 141 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
135 142 pub rings: Rings,
@@ -230,6 +237,12 @@ impl AppState {
230 237 call_mic: calling::MicSettings::default(),
231 238 call_effects: calling::CameraEffects::default(),
232 239 meet_now_pending: false,
240 prejoin: None,
241 prejoin_count: 0,
242 join_options: crate::call::JoinOptions::default(),
243 rsvp_send_response: true,
244 meeting_toasts: crate::call::MeetingToasts::default(),
245 demo_meetings: Vec::new(),
233 246 call_backgrounds: if mode.demo {
234 247 crate::call::demo_library()
235 248 } else {
@@ -250,6 +263,7 @@ impl AppState {
250 263 state.call_camera = crate::call::load_camera(&state.store);
251 264 state.call_mic = crate::call::load_mic(&state.store);
252 265 state.call_effects = crate::call::load_camera_effects(&state.store);
266 state.join_options = crate::call::load_join_options(&state.store);
253 267 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
254 268 state.load_cached_translation_settings();
255 269 if !mode.demo {
@@ -665,6 +679,7 @@ impl AppState {
665 679
666 680 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
667 681 self.show_call(false, cx);
682 self.cancel_prejoin(cx);
668 683 let was_drafting = std::mem::take(&mut self.new_chat);
669 684 if !was_drafting && self.selection.as_ref() == Some(&selection) {
670 685 return;
@@ -68,6 +68,7 @@ pub enum AppEvent {
68 Ring,
68 Ring,
69 LiveMeeting,
69 LiveMeeting,
70 MissedCall(MissedCall),
70 MissedCall(MissedCall),
71 MeetingReminder,
71}
72}
72
73
73#[derive(Debug, Clone, Copy, Default)]
74#[derive(Debug, Clone, Copy, Default)]
@@ -130,6 +131,12 @@ pub struct AppState {
130 pub call_mic: calling::MicSettings,
131 pub call_mic: calling::MicSettings,
131 pub call_effects: calling::CameraEffects,
132 pub call_effects: calling::CameraEffects,
132 pub meet_now_pending: bool,
133 pub meet_now_pending: bool,
134 pub prejoin: Option<crate::call::PendingJoin>,
135 pub prejoin_count: u64,
136 pub join_options: crate::call::JoinOptions,
137 pub rsvp_send_response: bool,
138 pub meeting_toasts: crate::call::MeetingToasts,
139 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
133 pub call_backgrounds: crate::call::BackgroundLibrary,
140 pub call_backgrounds: crate::call::BackgroundLibrary,
134 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
141 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
135 pub rings: Rings,
142 pub rings: Rings,
@@ -230,6 +237,12 @@ impl AppState {
230 call_mic: calling::MicSettings::default(),
237 call_mic: calling::MicSettings::default(),
231 call_effects: calling::CameraEffects::default(),
238 call_effects: calling::CameraEffects::default(),
232 meet_now_pending: false,
239 meet_now_pending: false,
240 prejoin: None,
241 prejoin_count: 0,
242 join_options: crate::call::JoinOptions::default(),
243 rsvp_send_response: true,
244 meeting_toasts: crate::call::MeetingToasts::default(),
245 demo_meetings: Vec::new(),
233 call_backgrounds: if mode.demo {
246 call_backgrounds: if mode.demo {
234 crate::call::demo_library()
247 crate::call::demo_library()
235 } else {
248 } else {
@@ -250,6 +263,7 @@ impl AppState {
250 state.call_camera = crate::call::load_camera(&state.store);
263 state.call_camera = crate::call::load_camera(&state.store);
251 state.call_mic = crate::call::load_mic(&state.store);
264 state.call_mic = crate::call::load_mic(&state.store);
252 state.call_effects = crate::call::load_camera_effects(&state.store);
265 state.call_effects = crate::call::load_camera_effects(&state.store);
266 state.join_options = crate::call::load_join_options(&state.store);
253 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
267 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
254 state.load_cached_translation_settings();
268 state.load_cached_translation_settings();
255 if !mode.demo {
269 if !mode.demo {
@@ -665,6 +679,7 @@ impl AppState {
665
679
666 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
680 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
667 self.show_call(false, cx);
681 self.show_call(false, cx);
682 self.cancel_prejoin(cx);
668 let was_drafting = std::mem::take(&mut self.new_chat);
683 let was_drafting = std::mem::take(&mut self.new_chat);
669 if !was_drafting && self.selection.as_ref() == Some(&selection) {
684 if !was_drafting && self.selection.as_ref() == Some(&selection) {
670 return;
685 return;
crates/app/src/call/actions.rs +15 −16
@@ -18,6 +18,7 @@ use super::features::room_closed_move;
18 18 use super::media::CallMedia;
19 19 use super::mic::save_mic;
20 20 use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
21 use super::prejoin::{DemoMeeting, MeetingJoin};
21 22 use super::ring::{MissedCall, RingOutcome};
22 23 use super::target::{is_organizer, plan_for_chat};
23 24 use crate::app_state::{AppEvent, AppState, Selection, chat_title};
@@ -155,28 +156,26 @@ impl AppState {
155 156 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
156 157 return;
157 158 };
158 let guests = if conversation_id == DEMO_LOBBY_MEETING {
159 DEMO_SMALL_MEETING
160 } else {
161 DEMO_CROWD
162 };
163 let demo = DemoCall::Meeting {
164 guests: demo_guests(guests),
159 let demo = DemoMeeting {
160 guests: if conversation_id == DEMO_LOBBY_MEETING {
161 DEMO_SMALL_MEETING
162 } else {
163 DEMO_CROWD
164 },
165 165 lobby: conversation_id == DEMO_LOBBY_MEETING,
166 166 organizer: conversation_id != DEMO_LOBBY_MEETING,
167 167 };
168 let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, false, cx)
169 else {
170 return;
171 };
172 168 let title = selection_for(&self.sidebar, conversation_id)
173 169 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
174 170 .unwrap_or_else(|| "Meeting".to_owned());
175 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
176 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
177 if let Some(call) = self.call.as_mut() {
178 call.meeting_target = Some(target);
179 }
171 let join = MeetingJoin {
172 organizer: is_organizer(&meeting, self.directory.me.as_ref()),
173 conversation_id: Some(conversation_id.to_owned()),
174 target,
175 title,
176 demo,
177 };
178 self.stage_meeting_join(join, cx);
180 179 }
181 180
182 181 pub(super) fn place_call(
@@ -18,6 +18,7 @@ use super::features::room_closed_move;
18use super::media::CallMedia;
18use super::media::CallMedia;
19use super::mic::save_mic;
19use super::mic::save_mic;
20use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
20use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
21use super::prejoin::{DemoMeeting, MeetingJoin};
21use super::ring::{MissedCall, RingOutcome};
22use super::ring::{MissedCall, RingOutcome};
22use super::target::{is_organizer, plan_for_chat};
23use super::target::{is_organizer, plan_for_chat};
23use crate::app_state::{AppEvent, AppState, Selection, chat_title};
24use crate::app_state::{AppEvent, AppState, Selection, chat_title};
@@ -155,28 +156,26 @@ impl AppState {
155 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
156 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
156 return;
157 return;
157 };
158 };
158 let guests = if conversation_id == DEMO_LOBBY_MEETING {
159 let demo = DemoMeeting {
159 DEMO_SMALL_MEETING
160 guests: if conversation_id == DEMO_LOBBY_MEETING {
160 } else {
161 DEMO_SMALL_MEETING
161 DEMO_CROWD
162 } else {
162 };
163 DEMO_CROWD
163 let demo = DemoCall::Meeting {
164 },
164 guests: demo_guests(guests),
165 lobby: conversation_id == DEMO_LOBBY_MEETING,
165 lobby: conversation_id == DEMO_LOBBY_MEETING,
166 organizer: conversation_id != DEMO_LOBBY_MEETING,
166 organizer: conversation_id != DEMO_LOBBY_MEETING,
167 };
167 };
168 let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, false, cx)
169 else {
170 return;
171 };
172 let title = selection_for(&self.sidebar, conversation_id)
168 let title = selection_for(&self.sidebar, conversation_id)
173 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
169 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
174 .unwrap_or_else(|| "Meeting".to_owned());
170 .unwrap_or_else(|| "Meeting".to_owned());
175 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
171 let join = MeetingJoin {
176 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
172 organizer: is_organizer(&meeting, self.directory.me.as_ref()),
177 if let Some(call) = self.call.as_mut() {
173 conversation_id: Some(conversation_id.to_owned()),
178 call.meeting_target = Some(target);
174 target,
179 }
175 title,
176 demo,
177 };
178 self.stage_meeting_join(join, cx);
180 }
179 }
181
180
182 pub(super) fn place_call(
181 pub(super) fn place_call(
crates/app/src/call/agenda.rs +57 −22
@@ -11,6 +11,8 @@ pub struct AgendaRow {
11 11 pub time_label: String,
12 12 pub subject: String,
13 13 pub detail: String,
14 pub response: ResponseType,
15 pub can_respond: bool,
14 16 pub all_day: bool,
15 17 pub join_url: Option<String>,
16 18 pub thread_id: Option<String>,
@@ -43,12 +45,13 @@ pub fn join_available(
43 45 now >= row_start - Duration::minutes(JOIN_LEAD_MINUTES) && now < row_end
44 46 }
45 47
46 pub fn rsvp_label(response: ResponseType) -> Option<&'static str> {
48 pub fn response_label(response: ResponseType) -> &'static str {
47 49 match response {
48 ResponseType::Organizer | ResponseType::Accepted => None,
49 ResponseType::Tentative => Some("tentative"),
50 ResponseType::Declined => Some("declined"),
51 ResponseType::NotResponded => Some("not answered"),
50 ResponseType::Organizer => "Organizer",
51 ResponseType::Accepted => "Accepted",
52 ResponseType::Tentative => "Tentative",
53 ResponseType::Declined => "Declined",
54 ResponseType::NotResponded => "Respond",
52 55 }
53 56 }
54 57
@@ -63,13 +66,10 @@ pub fn day_heading(day: NaiveDate, today: NaiveDate) -> String {
63 66 }
64 67
65 68 fn detail_label(event: &CalendarEvent) -> String {
66 let rsvp = rsvp_label(event.response);
67 match (event.organizer_name.as_deref(), rsvp) {
68 (Some(organizer), Some(rsvp)) => format!("{organizer} \u{b7} {rsvp}"),
69 (Some(organizer), None) => organizer.to_owned(),
70 (None, Some(rsvp)) => rsvp.to_owned(),
71 (None, None) => String::new(),
69 if event.response == ResponseType::Organizer {
70 return response_label(event.response).to_owned();
72 71 }
72 event.organizer_name.clone().unwrap_or_default()
73 73 }
74 74
75 75 fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
@@ -102,6 +102,8 @@ fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {
102 102 event.subject.clone()
103 103 },
104 104 detail: detail_label(event),
105 response: event.response,
106 can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),
105 107 all_day: event.all_day,
106 108 join_url: event.join_url.clone().filter(|_| event.online),
107 109 thread_id: event.thread_id.clone(),
@@ -140,6 +142,12 @@ pub fn group_by_day(
140 142 days
141 143 }
142 144
145 pub fn demo_join_url(id: &str) -> String {
146 format!(
147 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_{id}%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-organizer%22%7d"
148 )
149 }
150
143 151 pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
144 152 let event = |id: &str,
145 153 subject: &str,
@@ -154,12 +162,11 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
154 162 all_day: false,
155 163 cancelled: false,
156 164 online: true,
157 join_url: Some(format!(
158 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_{id}%40thread.v2/0"
159 )),
165 join_url: Some(demo_join_url(id)),
160 166 thread_id: None,
161 167 organizer_name: Some(organizer.to_owned()),
162 168 organizer_address: None,
169 ical_uid: None,
163 170 response,
164 171 };
165 172 vec![
@@ -195,6 +202,14 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
195 202 "Mara Lindqvist",
196 203 ResponseType::Accepted,
197 204 ),
205 event(
206 "demo-event-5",
207 "Roadmap sync",
208 420,
209 45,
210 "You",
211 ResponseType::Organizer,
212 ),
198 213 ]
199 214 }
200 215
@@ -226,6 +241,7 @@ mod tests {
226 241 thread_id: None,
227 242 organizer_name: Some("Mara".into()),
228 243 organizer_address: None,
244 ical_uid: None,
229 245 response: ResponseType::Accepted,
230 246 }
231 247 }
@@ -241,12 +257,12 @@ mod tests {
241 257 }
242 258
243 259 #[test]
244 fn rsvp_labels_only_show_when_not_accepted() {
245 assert_eq!(rsvp_label(ResponseType::Accepted), None);
246 assert_eq!(rsvp_label(ResponseType::Organizer), None);
247 assert_eq!(rsvp_label(ResponseType::NotResponded), Some("not answered"));
248 assert_eq!(rsvp_label(ResponseType::Tentative), Some("tentative"));
249 assert_eq!(rsvp_label(ResponseType::Declined), Some("declined"));
260 fn response_labels_name_the_current_answer() {
261 assert_eq!(response_label(ResponseType::Accepted), "Accepted");
262 assert_eq!(response_label(ResponseType::Organizer), "Organizer");
263 assert_eq!(response_label(ResponseType::NotResponded), "Respond");
264 assert_eq!(response_label(ResponseType::Tentative), "Tentative");
265 assert_eq!(response_label(ResponseType::Declined), "Declined");
250 266 }
251 267
252 268 #[test]
@@ -321,7 +337,7 @@ mod tests {
321 337 }
322 338
323 339 #[test]
324 fn rows_carry_organizer_and_rsvp_and_only_online_join_urls() {
340 fn rows_carry_organizer_response_and_only_online_join_urls() {
325 341 let now = utc(12, 8, 0);
326 342 let open = CalendarEvent {
327 343 response: ResponseType::NotResponded,
@@ -332,11 +348,30 @@ mod tests {
332 348 ..event("offline", utc(12, 10, 0), 30)
333 349 };
334 350 let days = group_by_day(&[open, offline], now, zero());
335 assert_eq!(days[0].rows[0].detail, "Mara \u{b7} not answered");
351 assert_eq!(days[0].rows[0].detail, "Mara");
352 assert_eq!(days[0].rows[0].response, ResponseType::NotResponded);
353 assert!(days[0].rows[0].can_respond);
336 354 assert!(days[0].rows[0].join_url.is_some());
337 355 assert_eq!(days[0].rows[1].join_url, None);
338 356 }
339 357
358 #[test]
359 fn own_meetings_say_organizer_and_cannot_be_answered() {
360 let own = CalendarEvent {
361 response: ResponseType::Organizer,
362 ..event("own", utc(12, 9, 0), 30)
363 };
364 let personal = CalendarEvent {
365 organizer_name: None,
366 response: ResponseType::NotResponded,
367 ..event("personal", utc(12, 10, 0), 30)
368 };
369 let days = group_by_day(&[own, personal], utc(12, 8, 0), zero());
370 assert_eq!(days[0].rows[0].detail, "Organizer");
371 assert!(!days[0].rows[0].can_respond);
372 assert!(!days[0].rows[1].can_respond);
373 }
374
340 375 #[test]
341 376 fn the_fetch_window_is_seven_days_from_local_midnight() {
342 377 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
@@ -11,6 +11,8 @@ pub struct AgendaRow {
11 pub time_label: String,
11 pub time_label: String,
12 pub subject: String,
12 pub subject: String,
13 pub detail: String,
13 pub detail: String,
14 pub response: ResponseType,
15 pub can_respond: bool,
14 pub all_day: bool,
16 pub all_day: bool,
15 pub join_url: Option<String>,
17 pub join_url: Option<String>,
16 pub thread_id: Option<String>,
18 pub thread_id: Option<String>,
@@ -43,12 +45,13 @@ pub fn join_available(
43 now >= row_start - Duration::minutes(JOIN_LEAD_MINUTES) && now < row_end
45 now >= row_start - Duration::minutes(JOIN_LEAD_MINUTES) && now < row_end
44}
46}
45
47
46pub fn rsvp_label(response: ResponseType) -> Option<&'static str> {
48pub fn response_label(response: ResponseType) -> &'static str {
47 match response {
49 match response {
48 ResponseType::Organizer | ResponseType::Accepted => None,
50 ResponseType::Organizer => "Organizer",
49 ResponseType::Tentative => Some("tentative"),
51 ResponseType::Accepted => "Accepted",
50 ResponseType::Declined => Some("declined"),
52 ResponseType::Tentative => "Tentative",
51 ResponseType::NotResponded => Some("not answered"),
53 ResponseType::Declined => "Declined",
54 ResponseType::NotResponded => "Respond",
52 }
55 }
53}
56}
54
57
@@ -63,13 +66,10 @@ pub fn day_heading(day: NaiveDate, today: NaiveDate) -> String {
63}
66}
64
67
65fn detail_label(event: &CalendarEvent) -> String {
68fn detail_label(event: &CalendarEvent) -> String {
66 let rsvp = rsvp_label(event.response);
69 if event.response == ResponseType::Organizer {
67 match (event.organizer_name.as_deref(), rsvp) {
70 return response_label(event.response).to_owned();
68 (Some(organizer), Some(rsvp)) => format!("{organizer} \u{b7} {rsvp}"),
69 (Some(organizer), None) => organizer.to_owned(),
70 (None, Some(rsvp)) => rsvp.to_owned(),
71 (None, None) => String::new(),
72 }
71 }
72 event.organizer_name.clone().unwrap_or_default()
73}
73}
74
74
75fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
75fn time_label(event: &CalendarEvent, offset: FixedOffset) -> String {
@@ -102,6 +102,8 @@ fn agenda_row(event: &CalendarEvent, offset: FixedOffset) -> AgendaRow {
102 event.subject.clone()
102 event.subject.clone()
103 },
103 },
104 detail: detail_label(event),
104 detail: detail_label(event),
105 response: event.response,
106 can_respond: event.response != ResponseType::Organizer && event.organizer_name.is_some(),
105 all_day: event.all_day,
107 all_day: event.all_day,
106 join_url: event.join_url.clone().filter(|_| event.online),
108 join_url: event.join_url.clone().filter(|_| event.online),
107 thread_id: event.thread_id.clone(),
109 thread_id: event.thread_id.clone(),
@@ -140,6 +142,12 @@ pub fn group_by_day(
140 days
142 days
141}
143}
142
144
145pub fn demo_join_url(id: &str) -> String {
146 format!(
147 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_{id}%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-organizer%22%7d"
148 )
149}
150
143pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
151pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
144 let event = |id: &str,
152 let event = |id: &str,
145 subject: &str,
153 subject: &str,
@@ -154,12 +162,11 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
154 all_day: false,
162 all_day: false,
155 cancelled: false,
163 cancelled: false,
156 online: true,
164 online: true,
157 join_url: Some(format!(
165 join_url: Some(demo_join_url(id)),
158 "https://teams.microsoft.com/l/meetup-join/19%3ameeting_{id}%40thread.v2/0"
159 )),
160 thread_id: None,
166 thread_id: None,
161 organizer_name: Some(organizer.to_owned()),
167 organizer_name: Some(organizer.to_owned()),
162 organizer_address: None,
168 organizer_address: None,
169 ical_uid: None,
163 response,
170 response,
164 };
171 };
165 vec![
172 vec![
@@ -195,6 +202,14 @@ pub fn demo_events(now: DateTime<Utc>) -> Vec<CalendarEvent> {
195 "Mara Lindqvist",
202 "Mara Lindqvist",
196 ResponseType::Accepted,
203 ResponseType::Accepted,
197 ),
204 ),
205 event(
206 "demo-event-5",
207 "Roadmap sync",
208 420,
209 45,
210 "You",
211 ResponseType::Organizer,
212 ),
198 ]
213 ]
199}
214}
200
215
@@ -226,6 +241,7 @@ mod tests {
226 thread_id: None,
241 thread_id: None,
227 organizer_name: Some("Mara".into()),
242 organizer_name: Some("Mara".into()),
228 organizer_address: None,
243 organizer_address: None,
244 ical_uid: None,
229 response: ResponseType::Accepted,
245 response: ResponseType::Accepted,
230 }
246 }
231 }
247 }
@@ -241,12 +257,12 @@ mod tests {
241 }
257 }
242
258
243 #[test]
259 #[test]
244 fn rsvp_labels_only_show_when_not_accepted() {
260 fn response_labels_name_the_current_answer() {
245 assert_eq!(rsvp_label(ResponseType::Accepted), None);
261 assert_eq!(response_label(ResponseType::Accepted), "Accepted");
246 assert_eq!(rsvp_label(ResponseType::Organizer), None);
262 assert_eq!(response_label(ResponseType::Organizer), "Organizer");
247 assert_eq!(rsvp_label(ResponseType::NotResponded), Some("not answered"));
263 assert_eq!(response_label(ResponseType::NotResponded), "Respond");
248 assert_eq!(rsvp_label(ResponseType::Tentative), Some("tentative"));
264 assert_eq!(response_label(ResponseType::Tentative), "Tentative");
249 assert_eq!(rsvp_label(ResponseType::Declined), Some("declined"));
265 assert_eq!(response_label(ResponseType::Declined), "Declined");
250 }
266 }
251
267
252 #[test]
268 #[test]
@@ -321,7 +337,7 @@ mod tests {
321 }
337 }
322
338
323 #[test]
339 #[test]
324 fn rows_carry_organizer_and_rsvp_and_only_online_join_urls() {
340 fn rows_carry_organizer_response_and_only_online_join_urls() {
325 let now = utc(12, 8, 0);
341 let now = utc(12, 8, 0);
326 let open = CalendarEvent {
342 let open = CalendarEvent {
327 response: ResponseType::NotResponded,
343 response: ResponseType::NotResponded,
@@ -332,11 +348,30 @@ mod tests {
332 ..event("offline", utc(12, 10, 0), 30)
348 ..event("offline", utc(12, 10, 0), 30)
333 };
349 };
334 let days = group_by_day(&[open, offline], now, zero());
350 let days = group_by_day(&[open, offline], now, zero());
335 assert_eq!(days[0].rows[0].detail, "Mara \u{b7} not answered");
351 assert_eq!(days[0].rows[0].detail, "Mara");
352 assert_eq!(days[0].rows[0].response, ResponseType::NotResponded);
353 assert!(days[0].rows[0].can_respond);
336 assert!(days[0].rows[0].join_url.is_some());
354 assert!(days[0].rows[0].join_url.is_some());
337 assert_eq!(days[0].rows[1].join_url, None);
355 assert_eq!(days[0].rows[1].join_url, None);
338 }
356 }
339
357
358 #[test]
359 fn own_meetings_say_organizer_and_cannot_be_answered() {
360 let own = CalendarEvent {
361 response: ResponseType::Organizer,
362 ..event("own", utc(12, 9, 0), 30)
363 };
364 let personal = CalendarEvent {
365 organizer_name: None,
366 response: ResponseType::NotResponded,
367 ..event("personal", utc(12, 10, 0), 30)
368 };
369 let days = group_by_day(&[own, personal], utc(12, 8, 0), zero());
370 assert_eq!(days[0].rows[0].detail, "Organizer");
371 assert!(!days[0].rows[0].can_respond);
372 assert!(!days[0].rows[1].can_respond);
373 }
374
340 #[test]
375 #[test]
341 fn the_fetch_window_is_seven_days_from_local_midnight() {
376 fn the_fetch_window_is_seven_days_from_local_midnight() {
342 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
377 let plus_two = FixedOffset::east_opt(2 * 3600).unwrap();
crates/app/src/call/calendar.rs +11 −2
@@ -1,5 +1,7 @@
1 use std::sync::OnceLock;
2
1 3 use chatsvc::CalendarEvent;
2 use chrono::{Local, Offset, Utc};
4 use chrono::{DateTime, Local, Offset, Utc};
3 5 use gpui_kit::Context;
4 6
5 7 use super::agenda::{AgendaRow, demo_events};
@@ -7,6 +9,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
7 9 use crate::notify::selection_for;
8 10
9 11 const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
12 static DEMO_ANCHOR: OnceLock<DateTime<Utc>> = OnceLock::new();
10 13
11 14 impl AppState {
12 15 pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
@@ -18,7 +21,10 @@ impl AppState {
18 21
19 22 pub fn refresh_calendar(&mut self, cx: &mut Context<Self>) {
20 23 if self.mode.demo {
21 self.apply_calendar(demo_events(Utc::now()), cx);
24 let mut events = demo_events(*DEMO_ANCHOR.get_or_init(Utc::now));
25 events.extend(self.demo_meetings.iter().cloned());
26 events.sort_by_key(|event| (event.start, event.end));
27 self.apply_calendar(events, cx);
22 28 return;
23 29 }
24 30 if let Some(nudge) = &self.calendar_nudge {
@@ -43,6 +49,9 @@ impl AppState {
43 49 pub fn join_agenda_row(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
44 50 if let Some(url) = &row.join_url {
45 51 self.join_meeting_link(url, cx);
52 if let Some(pending) = self.prejoin.as_mut() {
53 pending.join.title = row.subject.clone();
54 }
46 55 }
47 56 }
48 57
@@ -1,5 +1,7 @@
1use std::sync::OnceLock;
2
1use chatsvc::CalendarEvent;
3use chatsvc::CalendarEvent;
2use chrono::{Local, Offset, Utc};
4use chrono::{DateTime, Local, Offset, Utc};
3use gpui_kit::Context;
5use gpui_kit::Context;
4
6
5use super::agenda::{AgendaRow, demo_events};
7use super::agenda::{AgendaRow, demo_events};
@@ -7,6 +9,7 @@ use crate::app_state::{AppEvent, AppState, Selection};
7use crate::notify::selection_for;
9use crate::notify::selection_for;
8
10
9const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
11const NO_MEETING_CHAT_NOTICE: &str = "This meeting chat is not available";
12static DEMO_ANCHOR: OnceLock<DateTime<Utc>> = OnceLock::new();
10
13
11impl AppState {
14impl AppState {
12 pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
15 pub fn apply_calendar(&mut self, events: Vec<CalendarEvent>, cx: &mut Context<Self>) {
@@ -18,7 +21,10 @@ impl AppState {
18
21
19 pub fn refresh_calendar(&mut self, cx: &mut Context<Self>) {
22 pub fn refresh_calendar(&mut self, cx: &mut Context<Self>) {
20 if self.mode.demo {
23 if self.mode.demo {
21 self.apply_calendar(demo_events(Utc::now()), cx);
24 let mut events = demo_events(*DEMO_ANCHOR.get_or_init(Utc::now));
25 events.extend(self.demo_meetings.iter().cloned());
26 events.sort_by_key(|event| (event.start, event.end));
27 self.apply_calendar(events, cx);
22 return;
28 return;
23 }
29 }
24 if let Some(nudge) = &self.calendar_nudge {
30 if let Some(nudge) = &self.calendar_nudge {
@@ -43,6 +49,9 @@ impl AppState {
43 pub fn join_agenda_row(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
49 pub fn join_agenda_row(&mut self, row: &AgendaRow, cx: &mut Context<Self>) {
44 if let Some(url) = &row.join_url {
50 if let Some(url) = &row.join_url {
45 self.join_meeting_link(url, cx);
51 self.join_meeting_link(url, cx);
52 if let Some(pending) = self.prejoin.as_mut() {
53 pending.join.title = row.subject.clone();
54 }
46 }
55 }
47 }
56 }
48
57
crates/app/src/call/demo.rs +4 −0
@@ -517,6 +517,10 @@ async fn speak_until_hangup(
517 517 muted = command.target(muted);
518 518 control.send(CallUpdate::Muted(muted));
519 519 }
520 Some(CallCommand::DisableAudio) => {
521 muted = true;
522 control.send(CallUpdate::Muted(muted));
523 }
520 524 Some(CallCommand::SelectInput(choice)) => {
521 525 input = choice;
522 526 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
@@ -517,6 +517,10 @@ async fn speak_until_hangup(
517 muted = command.target(muted);
517 muted = command.target(muted);
518 control.send(CallUpdate::Muted(muted));
518 control.send(CallUpdate::Muted(muted));
519 }
519 }
520 Some(CallCommand::DisableAudio) => {
521 muted = true;
522 control.send(CallUpdate::Muted(muted));
523 }
520 Some(CallCommand::SelectInput(choice)) => {
524 Some(CallCommand::SelectInput(choice)) => {
521 input = choice;
525 input = choice;
522 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
526 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
crates/app/src/call/join.rs +40 −26
@@ -1,4 +1,4 @@
1 use calling::{CallSpec, MeetingTarget};
1 use calling::MeetingTarget;
2 2 use gpui_kit::*;
3 3 use teams_core::{
4 4 MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,
@@ -6,8 +6,7 @@ use teams_core::{
6 6 };
7 7
8 8 use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
9 use super::demo::{DemoCall, demo_guests};
10 use super::model::CallModel;
9 use super::prejoin::{DemoMeeting, MeetingJoin};
11 10 use crate::app_state::{AppState, selection_title};
12 11 use crate::notify::selection_for;
13 12 use crate::runtime;
@@ -30,8 +29,19 @@ pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
30 29 }
31 30 }
32 31
32 #[derive(Clone, Copy, PartialEq, Eq)]
33 enum JoinMode {
34 Prejoin,
35 Direct,
36 }
37
33 38 impl AppState {
34 fn join_resolved_meeting(&mut self, target: MeetingTarget, cx: &mut Context<Self>) {
39 fn join_resolved_meeting(
40 &mut self,
41 target: MeetingTarget,
42 mode: JoinMode,
43 cx: &mut Context<Self>,
44 ) {
35 45 if self.call.is_some() {
36 46 self.show_call(true, cx);
37 47 return;
@@ -44,24 +54,24 @@ impl AppState {
44 54 .me
45 55 .as_ref()
46 56 .is_some_and(|me| me.user_id.eq_ignore_ascii_case(&target.organizer_id));
47 let thread_id = target.thread_id.clone();
48 let demo = DemoCall::Meeting {
49 guests: demo_guests(DEMO_GUEST_COUNT),
50 lobby: false,
51 organizer: false,
57 let join = MeetingJoin {
58 conversation_id: Some(target.thread_id.clone()),
59 target,
60 title,
61 organizer,
62 demo: DemoMeeting {
63 guests: DEMO_GUEST_COUNT,
64 lobby: false,
65 organizer: false,
66 },
52 67 };
53 let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, false, cx) else {
54 return;
55 };
56 self.begin_call(
57 handle,
58 CallModel::meeting(&title, organizer),
59 Some(thread_id),
60 cx,
61 );
68 match mode {
69 JoinMode::Prejoin => self.stage_meeting_join(join, cx),
70 JoinMode::Direct => self.start_meeting(join, None, cx),
71 }
62 72 }
63 73
64 fn join_meeting_code(&mut self, code: MeetingCode, cx: &mut Context<Self>) {
74 fn join_meeting_code(&mut self, code: MeetingCode, mode: JoinMode, cx: &mut Context<Self>) {
65 75 if self.call.is_some() {
66 76 self.show_call(true, cx);
67 77 return;
@@ -74,7 +84,7 @@ impl AppState {
74 84 organizer_id: "demo-organizer".to_owned(),
75 85 meeting_data: Some(meeting_data),
76 86 };
77 self.join_resolved_meeting(target, cx);
87 self.join_resolved_meeting(target, mode, cx);
78 88 return;
79 89 }
80 90 let Some(launcher) = self.call_launcher.clone() else {
@@ -85,7 +95,7 @@ impl AppState {
85 95 cx.spawn(async move |this, cx| {
86 96 let resolved = receiver.await.ok().and_then(Result::ok);
87 97 this.update(cx, |state, cx| match resolved {
88 Some(target) => state.join_resolved_meeting(target, cx),
98 Some(target) => state.join_resolved_meeting(target, mode, cx),
89 99 None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
90 100 })
91 101 .ok();
@@ -94,11 +104,15 @@ impl AppState {
94 104 }
95 105
96 106 pub fn join_meeting_link(&mut self, text: &str, cx: &mut Context<Self>) {
107 self.join_link(text, JoinMode::Prejoin, cx);
108 }
109
110 fn join_link(&mut self, text: &str, mode: JoinMode, cx: &mut Context<Self>) {
97 111 match parse_meeting_link(text) {
98 112 Some(MeetingLink::Thread(meeting)) => {
99 self.join_resolved_meeting(meeting_target(&meeting), cx)
113 self.join_resolved_meeting(meeting_target(&meeting), mode, cx)
100 114 }
101 Some(MeetingLink::Code(code)) => self.join_meeting_code(code, cx),
115 Some(MeetingLink::Code(code)) => self.join_meeting_code(code, mode, cx),
102 116 None => self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx),
103 117 }
104 118 }
@@ -118,7 +132,7 @@ impl AppState {
118 132 organizer_id: "demo-organizer".to_owned(),
119 133 meeting_data: None,
120 134 };
121 self.join_resolved_meeting(target, cx);
135 self.join_resolved_meeting(target, JoinMode::Direct, cx);
122 136 return;
123 137 }
124 138 let Some(launcher) = self.call_launcher.clone() else {
@@ -134,7 +148,7 @@ impl AppState {
134 148 this.update(cx, |state, cx| {
135 149 state.meet_now_pending = false;
136 150 match created {
137 Some(url) => state.join_meeting_link(&url, cx),
151 Some(url) => state.join_link(&url, JoinMode::Direct, cx),
138 152 None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
139 153 }
140 154 cx.notify();
@@ -163,7 +177,7 @@ impl AppState {
163 177 ) -> Result<(), String> {
164 178 let code =
165 179 meeting_code_from_id(meeting_id, passcode).ok_or_else(|| BAD_ID_MESSAGE.to_owned())?;
166 self.join_meeting_code(code, cx);
180 self.join_meeting_code(code, JoinMode::Prejoin, cx);
167 181 Ok(())
168 182 }
169 183 }
@@ -1,4 +1,4 @@
1use calling::{CallSpec, MeetingTarget};
1use calling::MeetingTarget;
2use gpui_kit::*;
2use gpui_kit::*;
3use teams_core::{
3use teams_core::{
4 MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,
4 MeetingCode, MeetingLink, ThreadMeeting, find_meeting_link, meeting_code_from_id,
@@ -6,8 +6,7 @@ use teams_core::{
6};
6};
7
7
8use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
8use super::actions::{MEETING_UNAVAILABLE_NOTICE, NOT_CONNECTED_NOTICE};
9use super::demo::{DemoCall, demo_guests};
9use super::prejoin::{DemoMeeting, MeetingJoin};
10use super::model::CallModel;
11use crate::app_state::{AppState, selection_title};
10use crate::app_state::{AppState, selection_title};
12use crate::notify::selection_for;
11use crate::notify::selection_for;
13use crate::runtime;
12use crate::runtime;
@@ -30,8 +29,19 @@ pub fn meeting_target(meeting: &ThreadMeeting) -> MeetingTarget {
30 }
29 }
31}
30}
32
31
32#[derive(Clone, Copy, PartialEq, Eq)]
33enum JoinMode {
34 Prejoin,
35 Direct,
36}
37
33impl AppState {
38impl AppState {
34 fn join_resolved_meeting(&mut self, target: MeetingTarget, cx: &mut Context<Self>) {
39 fn join_resolved_meeting(
40 &mut self,
41 target: MeetingTarget,
42 mode: JoinMode,
43 cx: &mut Context<Self>,
44 ) {
35 if self.call.is_some() {
45 if self.call.is_some() {
36 self.show_call(true, cx);
46 self.show_call(true, cx);
37 return;
47 return;
@@ -44,24 +54,24 @@ impl AppState {
44 .me
54 .me
45 .as_ref()
55 .as_ref()
46 .is_some_and(|me| me.user_id.eq_ignore_ascii_case(&target.organizer_id));
56 .is_some_and(|me| me.user_id.eq_ignore_ascii_case(&target.organizer_id));
47 let thread_id = target.thread_id.clone();
57 let join = MeetingJoin {
48 let demo = DemoCall::Meeting {
58 conversation_id: Some(target.thread_id.clone()),
49 guests: demo_guests(DEMO_GUEST_COUNT),
59 target,
50 lobby: false,
60 title,
51 organizer: false,
61 organizer,
62 demo: DemoMeeting {
63 guests: DEMO_GUEST_COUNT,
64 lobby: false,
65 organizer: false,
66 },
52 };
67 };
53 let Some(handle) = self.place_call(CallSpec::Meeting(target), demo, false, cx) else {
68 match mode {
54 return;
69 JoinMode::Prejoin => self.stage_meeting_join(join, cx),
55 };
70 JoinMode::Direct => self.start_meeting(join, None, cx),
56 self.begin_call(
71 }
57 handle,
58 CallModel::meeting(&title, organizer),
59 Some(thread_id),
60 cx,
61 );
62 }
72 }
63
73
64 fn join_meeting_code(&mut self, code: MeetingCode, cx: &mut Context<Self>) {
74 fn join_meeting_code(&mut self, code: MeetingCode, mode: JoinMode, cx: &mut Context<Self>) {
65 if self.call.is_some() {
75 if self.call.is_some() {
66 self.show_call(true, cx);
76 self.show_call(true, cx);
67 return;
77 return;
@@ -74,7 +84,7 @@ impl AppState {
74 organizer_id: "demo-organizer".to_owned(),
84 organizer_id: "demo-organizer".to_owned(),
75 meeting_data: Some(meeting_data),
85 meeting_data: Some(meeting_data),
76 };
86 };
77 self.join_resolved_meeting(target, cx);
87 self.join_resolved_meeting(target, mode, cx);
78 return;
88 return;
79 }
89 }
80 let Some(launcher) = self.call_launcher.clone() else {
90 let Some(launcher) = self.call_launcher.clone() else {
@@ -85,7 +95,7 @@ impl AppState {
85 cx.spawn(async move |this, cx| {
95 cx.spawn(async move |this, cx| {
86 let resolved = receiver.await.ok().and_then(Result::ok);
96 let resolved = receiver.await.ok().and_then(Result::ok);
87 this.update(cx, |state, cx| match resolved {
97 this.update(cx, |state, cx| match resolved {
88 Some(target) => state.join_resolved_meeting(target, cx),
98 Some(target) => state.join_resolved_meeting(target, mode, cx),
89 None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
99 None => state.raise_notice(NOT_FOUND_NOTICE.to_owned(), None, cx),
90 })
100 })
91 .ok();
101 .ok();
@@ -94,11 +104,15 @@ impl AppState {
94 }
104 }
95
105
96 pub fn join_meeting_link(&mut self, text: &str, cx: &mut Context<Self>) {
106 pub fn join_meeting_link(&mut self, text: &str, cx: &mut Context<Self>) {
107 self.join_link(text, JoinMode::Prejoin, cx);
108 }
109
110 fn join_link(&mut self, text: &str, mode: JoinMode, cx: &mut Context<Self>) {
97 match parse_meeting_link(text) {
111 match parse_meeting_link(text) {
98 Some(MeetingLink::Thread(meeting)) => {
112 Some(MeetingLink::Thread(meeting)) => {
99 self.join_resolved_meeting(meeting_target(&meeting), cx)
113 self.join_resolved_meeting(meeting_target(&meeting), mode, cx)
100 }
114 }
101 Some(MeetingLink::Code(code)) => self.join_meeting_code(code, cx),
115 Some(MeetingLink::Code(code)) => self.join_meeting_code(code, mode, cx),
102 None => self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx),
116 None => self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx),
103 }
117 }
104 }
118 }
@@ -118,7 +132,7 @@ impl AppState {
118 organizer_id: "demo-organizer".to_owned(),
132 organizer_id: "demo-organizer".to_owned(),
119 meeting_data: None,
133 meeting_data: None,
120 };
134 };
121 self.join_resolved_meeting(target, cx);
135 self.join_resolved_meeting(target, JoinMode::Direct, cx);
122 return;
136 return;
123 }
137 }
124 let Some(launcher) = self.call_launcher.clone() else {
138 let Some(launcher) = self.call_launcher.clone() else {
@@ -134,7 +148,7 @@ impl AppState {
134 this.update(cx, |state, cx| {
148 this.update(cx, |state, cx| {
135 state.meet_now_pending = false;
149 state.meet_now_pending = false;
136 match created {
150 match created {
137 Some(url) => state.join_meeting_link(&url, cx),
151 Some(url) => state.join_link(&url, JoinMode::Direct, cx),
138 None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
152 None => state.raise_notice(MEET_NOW_FAILED_NOTICE.to_owned(), None, cx),
139 }
153 }
140 cx.notify();
154 cx.notify();
@@ -163,7 +177,7 @@ impl AppState {
163 ) -> Result<(), String> {
177 ) -> Result<(), String> {
164 let code =
178 let code =
165 meeting_code_from_id(meeting_id, passcode).ok_or_else(|| BAD_ID_MESSAGE.to_owned())?;
179 meeting_code_from_id(meeting_id, passcode).ok_or_else(|| BAD_ID_MESSAGE.to_owned())?;
166 self.join_meeting_code(code, cx);
180 self.join_meeting_code(code, JoinMode::Prejoin, cx);
167 Ok(())
181 Ok(())
168 }
182 }
169}
183}
crates/app/src/call/launcher.rs +44 −0
@@ -10,6 +10,8 @@ use calling::{
10 10 };
11 11 use session::{Session, SessionConfig, Transport};
12 12
13 use super::schedule::{MeetingDraft, attendee_for};
14
13 15 const START_RETRY_STEPS: [Duration; 3] = [
14 16 Duration::from_secs(1),
15 17 Duration::from_secs(2),
@@ -141,6 +143,48 @@ impl CallLauncher {
141 143 .map_err(|error| error.to_string())
142 144 }
143 145
146 pub async fn create_meeting(
147 &self,
148 draft: MeetingDraft,
149 ) -> Result<chatsvc::CreatedEvent, String> {
150 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
151 let graph = graph::Graph::new(session.clone());
152 let mut attendees = Vec::with_capacity(draft.people.len());
153 for invitee in &draft.people {
154 let looked_up = match invitee.mail {
155 Some(_) => None,
156 None => graph.user_mail(&invitee.user_id).await.ok().flatten(),
157 };
158 attendees.push(attendee_for(invitee, looked_up)?);
159 }
160 let event = chatsvc::NewEvent {
161 subject: draft.subject,
162 start: draft.start,
163 end: draft.end,
164 attendees,
165 repeat: draft.repeat,
166 details: draft.details,
167 };
168 chatsvc::Calendar::new(&session)
169 .create_event(&event)
170 .await
171 .map_err(|error| error.to_string())
172 }
173
174 pub async fn respond_to_event(
175 &self,
176 event_id: &str,
177 ical_uid: Option<&str>,
178 reply: chatsvc::Reply,
179 send_response: bool,
180 ) -> Result<(), String> {
181 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
182 chatsvc::Calendar::new(&session)
183 .respond(event_id, ical_uid, reply, send_response)
184 .await
185 .map_err(|error| error.to_string())
186 }
187
144 188 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
145 189 let session = self.engine()?.session();
146 190 fetch_live_meeting(&session, thread_id).await.ok().flatten()
@@ -10,6 +10,8 @@ use calling::{
10};
10};
11use session::{Session, SessionConfig, Transport};
11use session::{Session, SessionConfig, Transport};
12
12
13use super::schedule::{MeetingDraft, attendee_for};
14
13const START_RETRY_STEPS: [Duration; 3] = [
15const START_RETRY_STEPS: [Duration; 3] = [
14 Duration::from_secs(1),
16 Duration::from_secs(1),
15 Duration::from_secs(2),
17 Duration::from_secs(2),
@@ -141,6 +143,48 @@ impl CallLauncher {
141 .map_err(|error| error.to_string())
143 .map_err(|error| error.to_string())
142 }
144 }
143
145
146 pub async fn create_meeting(
147 &self,
148 draft: MeetingDraft,
149 ) -> Result<chatsvc::CreatedEvent, String> {
150 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
151 let graph = graph::Graph::new(session.clone());
152 let mut attendees = Vec::with_capacity(draft.people.len());
153 for invitee in &draft.people {
154 let looked_up = match invitee.mail {
155 Some(_) => None,
156 None => graph.user_mail(&invitee.user_id).await.ok().flatten(),
157 };
158 attendees.push(attendee_for(invitee, looked_up)?);
159 }
160 let event = chatsvc::NewEvent {
161 subject: draft.subject,
162 start: draft.start,
163 end: draft.end,
164 attendees,
165 repeat: draft.repeat,
166 details: draft.details,
167 };
168 chatsvc::Calendar::new(&session)
169 .create_event(&event)
170 .await
171 .map_err(|error| error.to_string())
172 }
173
174 pub async fn respond_to_event(
175 &self,
176 event_id: &str,
177 ical_uid: Option<&str>,
178 reply: chatsvc::Reply,
179 send_response: bool,
180 ) -> Result<(), String> {
181 let session = self.engine().ok_or_else(|| NOT_READY.to_owned())?.session();
182 chatsvc::Calendar::new(&session)
183 .respond(event_id, ical_uid, reply, send_response)
184 .await
185 .map_err(|error| error.to_string())
186 }
187
144 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
188 pub async fn live_meeting(&self, thread_id: &str) -> Option<LiveMeeting> {
145 let session = self.engine()?.session();
189 let session = self.engine()?.session();
146 fetch_live_meeting(&session, thread_id).await.ok().flatten()
190 fetch_live_meeting(&session, thread_id).await.ok().flatten()
crates/app/src/call/list.rs +1 −0
@@ -188,6 +188,7 @@ mod tests {
188 188 thread_id: None,
189 189 organizer_name: None,
190 190 organizer_address: None,
191 ical_uid: None,
191 192 response: ResponseType::Accepted,
192 193 }
193 194 }
@@ -188,6 +188,7 @@ mod tests {
188 thread_id: None,
188 thread_id: None,
189 organizer_name: None,
189 organizer_name: None,
190 organizer_address: None,
190 organizer_address: None,
191 ical_uid: None,
191 response: ResponseType::Accepted,
192 response: ResponseType::Accepted,
192 }
193 }
193 }
194 }
crates/app/src/call/mod.rs +7 −1
@@ -18,9 +18,12 @@ mod model;
18 18 mod overlay;
19 19 mod overlay_layout;
20 20 mod pictures;
21 mod prejoin;
21 22 mod preview;
22 23 mod push_to_talk;
24 mod reminder;
23 25 mod ring;
26 mod schedule;
24 27 mod stage_layout;
25 28 mod target;
26 29 mod view_actions;
@@ -28,7 +31,7 @@ mod view_settings;
28 31
29 32 pub use actions::{load_camera, load_camera_effects, load_share_sound};
30 33 pub use mic::load_mic;
31 pub use agenda::{AgendaRow, fetch_window, join_available};
34 pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
32 35 pub use background::{
33 36 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
34 37 load_custom_backgrounds,
@@ -49,8 +52,11 @@ pub use model::{
49 52 TileState,
50 53 };
51 54 pub use overlay::CallWindows;
55 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
52 56 pub use preview::{CameraPreview, preview_backgrounds};
57 pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
53 58 pub use ring::{MissedCall, RingEntry, Rings};
54 59 pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
60 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
55 61 pub use target::plan_for_chat;
56 62 pub use view_settings::{CallLayout, ViewSettings};
@@ -18,9 +18,12 @@ mod model;
18mod overlay;
18mod overlay;
19mod overlay_layout;
19mod overlay_layout;
20mod pictures;
20mod pictures;
21mod prejoin;
21mod preview;
22mod preview;
22mod push_to_talk;
23mod push_to_talk;
24mod reminder;
23mod ring;
25mod ring;
26mod schedule;
24mod stage_layout;
27mod stage_layout;
25mod target;
28mod target;
26mod view_actions;
29mod view_actions;
@@ -28,7 +31,7 @@ mod view_settings;
28
31
29pub use actions::{load_camera, load_camera_effects, load_share_sound};
32pub use actions::{load_camera, load_camera_effects, load_share_sound};
30pub use mic::load_mic;
33pub use mic::load_mic;
31pub use agenda::{AgendaRow, fetch_window, join_available};
34pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
32pub use background::{
35pub use background::{
33 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
36 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
34 load_custom_backgrounds,
37 load_custom_backgrounds,
@@ -49,8 +52,11 @@ pub use model::{
49 TileState,
52 TileState,
50};
53};
51pub use overlay::CallWindows;
54pub use overlay::CallWindows;
55pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
52pub use preview::{CameraPreview, preview_backgrounds};
56pub use preview::{CameraPreview, preview_backgrounds};
57pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
53pub use ring::{MissedCall, RingEntry, Rings};
58pub use ring::{MissedCall, RingEntry, Rings};
54pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
59pub use stage_layout::{FILMSTRIP_MAX, GALLERY_MAX, filmstrip, gallery_grid, split_overflow};
60pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
55pub use target::plan_for_chat;
61pub use target::plan_for_chat;
56pub use view_settings::{CallLayout, ViewSettings};
62pub use view_settings::{CallLayout, ViewSettings};
crates/app/src/call/model.rs +10 −1
@@ -239,6 +239,7 @@ pub struct CallModel {
239 239 pub progress: Option<Progress>,
240 240 pub muted: bool,
241 241 pub listen_only: bool,
242 pub audio_off: bool,
242 243 pub lobby: bool,
243 244 pub can_end_meeting: bool,
244 245 pub incoming: bool,
@@ -293,6 +294,7 @@ impl CallModel {
293 294 progress: None,
294 295 muted: false,
295 296 listen_only: false,
297 audio_off: false,
296 298 lobby: false,
297 299 can_end_meeting: false,
298 300 incoming: false,
@@ -1040,7 +1042,7 @@ impl CallModel {
1040 1042 }
1041 1043
1042 1044 pub fn can_unmute(&self) -> bool {
1043 !self.listen_only
1045 !self.listen_only && !self.audio_off
1044 1046 }
1045 1047 }
1046 1048
@@ -1256,6 +1258,13 @@ mod tests {
1256 1258 assert!(!model.can_unmute());
1257 1259 }
1258 1260
1261 #[test]
1262 fn a_call_without_audio_blocks_unmuting() {
1263 let mut model = connected_model();
1264 model.audio_off = true;
1265 assert!(!model.can_unmute());
1266 }
1267
1259 1268 #[test]
1260 1269 fn callees_start_invited_and_follow_the_progress() {
1261 1270 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
@@ -239,6 +239,7 @@ pub struct CallModel {
239 pub progress: Option<Progress>,
239 pub progress: Option<Progress>,
240 pub muted: bool,
240 pub muted: bool,
241 pub listen_only: bool,
241 pub listen_only: bool,
242 pub audio_off: bool,
242 pub lobby: bool,
243 pub lobby: bool,
243 pub can_end_meeting: bool,
244 pub can_end_meeting: bool,
244 pub incoming: bool,
245 pub incoming: bool,
@@ -293,6 +294,7 @@ impl CallModel {
293 progress: None,
294 progress: None,
294 muted: false,
295 muted: false,
295 listen_only: false,
296 listen_only: false,
297 audio_off: false,
296 lobby: false,
298 lobby: false,
297 can_end_meeting: false,
299 can_end_meeting: false,
298 incoming: false,
300 incoming: false,
@@ -1040,7 +1042,7 @@ impl CallModel {
1040 }
1042 }
1041
1043
1042 pub fn can_unmute(&self) -> bool {
1044 pub fn can_unmute(&self) -> bool {
1043 !self.listen_only
1045 !self.listen_only && !self.audio_off
1044 }
1046 }
1045}
1047}
1046
1048
@@ -1256,6 +1258,13 @@ mod tests {
1256 assert!(!model.can_unmute());
1258 assert!(!model.can_unmute());
1257 }
1259 }
1258
1260
1261 #[test]
1262 fn a_call_without_audio_blocks_unmuting() {
1263 let mut model = connected_model();
1264 model.audio_off = true;
1265 assert!(!model.can_unmute());
1266 }
1267
1259 #[test]
1268 #[test]
1260 fn callees_start_invited_and_follow_the_progress() {
1269 fn callees_start_invited_and_follow_the_progress() {
1261 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1270 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
crates/app/src/call/prejoin.rs added +259 −0
@@ -0,0 +1,259 @@
1 use calling::{CallCommand, CallSpec, DeviceChoice, MeetingTarget, MuteCommand};
2 use gpui_kit::Context;
3
4 use super::demo::{DemoCall, demo_guests};
5 use super::model::CallModel;
6 use crate::app_state::AppState;
7
8 const OPTIONS_META_KEY: &str = "prejoin_options";
9 const DEFAULT_DEVICE_META: &str = "default";
10
11 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12 pub enum AudioChoice {
13 #[default]
14 Computer,
15 NoAudio,
16 }
17
18 impl AudioChoice {
19 pub fn label(self) -> &'static str {
20 match self {
21 AudioChoice::Computer => "Computer audio",
22 AudioChoice::NoAudio => "Don't use audio",
23 }
24 }
25 }
26
27 #[derive(Debug, Clone, PartialEq, Eq)]
28 pub struct JoinOptions {
29 pub camera_on: bool,
30 pub mic_on: bool,
31 pub audio: AudioChoice,
32 pub input: DeviceChoice,
33 pub output: DeviceChoice,
34 }
35
36 impl Default for JoinOptions {
37 fn default() -> Self {
38 JoinOptions {
39 camera_on: false,
40 mic_on: true,
41 audio: AudioChoice::Computer,
42 input: DeviceChoice::SystemDefault,
43 output: DeviceChoice::SystemDefault,
44 }
45 }
46 }
47
48 fn device_meta(choice: &DeviceChoice) -> &str {
49 match choice {
50 DeviceChoice::SystemDefault => DEFAULT_DEVICE_META,
51 DeviceChoice::Device(key) => key,
52 }
53 }
54
55 fn device_from_meta(value: &str) -> DeviceChoice {
56 match value {
57 "" | DEFAULT_DEVICE_META => DeviceChoice::SystemDefault,
58 key => DeviceChoice::Device(key.to_owned()),
59 }
60 }
61
62 impl JoinOptions {
63 pub fn to_meta(&self) -> String {
64 format!(
65 "camera={}\nmic={}\ninput={}\noutput={}",
66 u8::from(self.camera_on),
67 u8::from(self.mic_on),
68 device_meta(&self.input),
69 device_meta(&self.output)
70 )
71 }
72
73 pub fn from_meta(text: &str) -> Self {
74 let mut options = JoinOptions::default();
75 for (key, value) in text.lines().filter_map(|line| line.split_once('=')) {
76 match key {
77 "camera" => options.camera_on = value == "1",
78 "mic" => options.mic_on = value == "1",
79 "input" => options.input = device_from_meta(value),
80 "output" => options.output = device_from_meta(value),
81 _ => {}
82 }
83 }
84 options
85 }
86
87 pub fn commands_after_join(&self) -> Vec<CallCommand> {
88 if self.audio == AudioChoice::NoAudio {
89 return vec![CallCommand::DisableAudio];
90 }
91 let mut commands = Vec::new();
92 if self.mic_on {
93 commands.push(CallCommand::Mute(MuteCommand::Unmute));
94 }
95 if self.input != DeviceChoice::SystemDefault {
96 commands.push(CallCommand::SelectInput(self.input.clone()));
97 }
98 if self.output != DeviceChoice::SystemDefault {
99 commands.push(CallCommand::SelectOutput(self.output.clone()));
100 }
101 commands
102 }
103 }
104
105 pub fn load_join_options(store: &store::Store) -> JoinOptions {
106 store
107 .meta(OPTIONS_META_KEY)
108 .ok()
109 .flatten()
110 .map(|text| JoinOptions::from_meta(&text))
111 .unwrap_or_default()
112 }
113
114 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
115 pub struct DemoMeeting {
116 pub guests: usize,
117 pub lobby: bool,
118 pub organizer: bool,
119 }
120
121 #[derive(Debug, Clone)]
122 pub struct MeetingJoin {
123 pub target: MeetingTarget,
124 pub title: String,
125 pub organizer: bool,
126 pub conversation_id: Option<String>,
127 pub demo: DemoMeeting,
128 }
129
130 #[derive(Debug, Clone)]
131 pub struct PendingJoin {
132 pub id: u64,
133 pub join: MeetingJoin,
134 }
135
136 impl AppState {
137 pub(super) fn stage_meeting_join(&mut self, join: MeetingJoin, cx: &mut Context<Self>) {
138 if self.call.is_some() {
139 self.show_call(true, cx);
140 return;
141 }
142 self.prejoin_count += 1;
143 self.prejoin = Some(PendingJoin {
144 id: self.prejoin_count,
145 join,
146 });
147 self.new_chat = false;
148 cx.notify();
149 }
150
151 pub fn confirm_prejoin(&mut self, options: JoinOptions, cx: &mut Context<Self>) {
152 let Some(pending) = self.prejoin.take() else {
153 return;
154 };
155 let _ = self.store.set_meta(OPTIONS_META_KEY, &options.to_meta());
156 self.join_options = options.clone();
157 self.start_meeting(pending.join, Some(&options), cx);
158 }
159
160 pub fn cancel_prejoin(&mut self, cx: &mut Context<Self>) {
161 if self.prejoin.take().is_some() {
162 cx.notify();
163 }
164 }
165
166 pub(super) fn start_meeting(
167 &mut self,
168 join: MeetingJoin,
169 options: Option<&JoinOptions>,
170 cx: &mut Context<Self>,
171 ) {
172 if self.call.is_some() {
173 self.show_call(true, cx);
174 return;
175 }
176 let demo = DemoCall::Meeting {
177 guests: demo_guests(join.demo.guests),
178 lobby: join.demo.lobby,
179 organizer: join.demo.organizer,
180 };
181 let with_video = options.is_some_and(|options| options.camera_on);
182 let Some(handle) =
183 self.place_call(CallSpec::Meeting(join.target.clone()), demo, with_video, cx)
184 else {
185 return;
186 };
187 let model = CallModel::meeting(&join.title, join.organizer);
188 self.begin_call(handle, model, join.conversation_id, cx);
189 if let Some(call) = self.call.as_mut() {
190 call.meeting_target = Some(join.target);
191 call.model.audio_off =
192 options.is_some_and(|options| options.audio == AudioChoice::NoAudio);
193 }
194 for command in options
195 .map(JoinOptions::commands_after_join)
196 .unwrap_or_default()
197 {
198 self.send_call_command(command);
199 }
200 }
201 }
202
203 #[cfg(test)]
204 mod tests {
205 use super::*;
206
207 #[test]
208 fn options_survive_a_round_trip_through_the_store_text() {
209 let options = JoinOptions {
210 camera_on: true,
211 mic_on: false,
212 audio: AudioChoice::Computer,
213 input: DeviceChoice::Device("usb-mic".into()),
214 output: DeviceChoice::SystemDefault,
215 };
216 assert_eq!(JoinOptions::from_meta(&options.to_meta()), options);
217 }
218
219 #[test]
220 fn empty_or_garbage_text_gives_the_defaults() {
221 assert_eq!(JoinOptions::from_meta(""), JoinOptions::default());
222 assert_eq!(JoinOptions::from_meta("junk\nmic"), JoinOptions::default());
223 }
224
225 #[test]
226 fn computer_audio_unmutes_and_selects_chosen_devices_only() {
227 let default = JoinOptions::default();
228 assert_eq!(
229 default.commands_after_join(),
230 vec![CallCommand::Mute(MuteCommand::Unmute)]
231 );
232 let chosen = JoinOptions {
233 mic_on: false,
234 input: DeviceChoice::Device("mic".into()),
235 output: DeviceChoice::Device("speaker".into()),
236 ..default
237 };
238 assert_eq!(
239 chosen.commands_after_join(),
240 vec![
241 CallCommand::SelectInput(DeviceChoice::Device("mic".into())),
242 CallCommand::SelectOutput(DeviceChoice::Device("speaker".into())),
243 ]
244 );
245 }
246
247 #[test]
248 fn without_audio_only_the_audio_is_switched_off() {
249 let options = JoinOptions {
250 audio: AudioChoice::NoAudio,
251 input: DeviceChoice::Device("mic".into()),
252 ..JoinOptions::default()
253 };
254 assert_eq!(
255 options.commands_after_join(),
256 vec![CallCommand::DisableAudio]
257 );
258 }
259 }
@@ -0,0 +1,259 @@
1use calling::{CallCommand, CallSpec, DeviceChoice, MeetingTarget, MuteCommand};
2use gpui_kit::Context;
3
4use super::demo::{DemoCall, demo_guests};
5use super::model::CallModel;
6use crate::app_state::AppState;
7
8const OPTIONS_META_KEY: &str = "prejoin_options";
9const DEFAULT_DEVICE_META: &str = "default";
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
12pub enum AudioChoice {
13 #[default]
14 Computer,
15 NoAudio,
16}
17
18impl AudioChoice {
19 pub fn label(self) -> &'static str {
20 match self {
21 AudioChoice::Computer => "Computer audio",
22 AudioChoice::NoAudio => "Don't use audio",
23 }
24 }
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct JoinOptions {
29 pub camera_on: bool,
30 pub mic_on: bool,
31 pub audio: AudioChoice,
32 pub input: DeviceChoice,
33 pub output: DeviceChoice,
34}
35
36impl Default for JoinOptions {
37 fn default() -> Self {
38 JoinOptions {
39 camera_on: false,
40 mic_on: true,
41 audio: AudioChoice::Computer,
42 input: DeviceChoice::SystemDefault,
43 output: DeviceChoice::SystemDefault,
44 }
45 }
46}
47
48fn device_meta(choice: &DeviceChoice) -> &str {
49 match choice {
50 DeviceChoice::SystemDefault => DEFAULT_DEVICE_META,
51 DeviceChoice::Device(key) => key,
52 }
53}
54
55fn device_from_meta(value: &str) -> DeviceChoice {
56 match value {
57 "" | DEFAULT_DEVICE_META => DeviceChoice::SystemDefault,
58 key => DeviceChoice::Device(key.to_owned()),
59 }
60}
61
62impl JoinOptions {
63 pub fn to_meta(&self) -> String {
64 format!(
65 "camera={}\nmic={}\ninput={}\noutput={}",
66 u8::from(self.camera_on),
67 u8::from(self.mic_on),
68 device_meta(&self.input),
69 device_meta(&self.output)
70 )
71 }
72
73 pub fn from_meta(text: &str) -> Self {
74 let mut options = JoinOptions::default();
75 for (key, value) in text.lines().filter_map(|line| line.split_once('=')) {
76 match key {
77 "camera" => options.camera_on = value == "1",
78 "mic" => options.mic_on = value == "1",
79 "input" => options.input = device_from_meta(value),
80 "output" => options.output = device_from_meta(value),
81 _ => {}
82 }
83 }
84 options
85 }
86
87 pub fn commands_after_join(&self) -> Vec<CallCommand> {
88 if self.audio == AudioChoice::NoAudio {
89 return vec![CallCommand::DisableAudio];
90 }
91 let mut commands = Vec::new();
92 if self.mic_on {
93 commands.push(CallCommand::Mute(MuteCommand::Unmute));
94 }
95 if self.input != DeviceChoice::SystemDefault {
96 commands.push(CallCommand::SelectInput(self.input.clone()));
97 }
98 if self.output != DeviceChoice::SystemDefault {
99 commands.push(CallCommand::SelectOutput(self.output.clone()));
100 }
101 commands
102 }
103}
104
105pub fn load_join_options(store: &store::Store) -> JoinOptions {
106 store
107 .meta(OPTIONS_META_KEY)
108 .ok()
109 .flatten()
110 .map(|text| JoinOptions::from_meta(&text))
111 .unwrap_or_default()
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub struct DemoMeeting {
116 pub guests: usize,
117 pub lobby: bool,
118 pub organizer: bool,
119}
120
121#[derive(Debug, Clone)]
122pub struct MeetingJoin {
123 pub target: MeetingTarget,
124 pub title: String,
125 pub organizer: bool,
126 pub conversation_id: Option<String>,
127 pub demo: DemoMeeting,
128}
129
130#[derive(Debug, Clone)]
131pub struct PendingJoin {
132 pub id: u64,
133 pub join: MeetingJoin,
134}
135
136impl AppState {
137 pub(super) fn stage_meeting_join(&mut self, join: MeetingJoin, cx: &mut Context<Self>) {
138 if self.call.is_some() {
139 self.show_call(true, cx);
140 return;
141 }
142 self.prejoin_count += 1;
143 self.prejoin = Some(PendingJoin {
144 id: self.prejoin_count,
145 join,
146 });
147 self.new_chat = false;
148 cx.notify();
149 }
150
151 pub fn confirm_prejoin(&mut self, options: JoinOptions, cx: &mut Context<Self>) {
152 let Some(pending) = self.prejoin.take() else {
153 return;
154 };
155 let _ = self.store.set_meta(OPTIONS_META_KEY, &options.to_meta());
156 self.join_options = options.clone();
157 self.start_meeting(pending.join, Some(&options), cx);
158 }
159
160 pub fn cancel_prejoin(&mut self, cx: &mut Context<Self>) {
161 if self.prejoin.take().is_some() {
162 cx.notify();
163 }
164 }
165
166 pub(super) fn start_meeting(
167 &mut self,
168 join: MeetingJoin,
169 options: Option<&JoinOptions>,
170 cx: &mut Context<Self>,
171 ) {
172 if self.call.is_some() {
173 self.show_call(true, cx);
174 return;
175 }
176 let demo = DemoCall::Meeting {
177 guests: demo_guests(join.demo.guests),
178 lobby: join.demo.lobby,
179 organizer: join.demo.organizer,
180 };
181 let with_video = options.is_some_and(|options| options.camera_on);
182 let Some(handle) =
183 self.place_call(CallSpec::Meeting(join.target.clone()), demo, with_video, cx)
184 else {
185 return;
186 };
187 let model = CallModel::meeting(&join.title, join.organizer);
188 self.begin_call(handle, model, join.conversation_id, cx);
189 if let Some(call) = self.call.as_mut() {
190 call.meeting_target = Some(join.target);
191 call.model.audio_off =
192 options.is_some_and(|options| options.audio == AudioChoice::NoAudio);
193 }
194 for command in options
195 .map(JoinOptions::commands_after_join)
196 .unwrap_or_default()
197 {
198 self.send_call_command(command);
199 }
200 }
201}
202
203#[cfg(test)]
204mod tests {
205 use super::*;
206
207 #[test]
208 fn options_survive_a_round_trip_through_the_store_text() {
209 let options = JoinOptions {
210 camera_on: true,
211 mic_on: false,
212 audio: AudioChoice::Computer,
213 input: DeviceChoice::Device("usb-mic".into()),
214 output: DeviceChoice::SystemDefault,
215 };
216 assert_eq!(JoinOptions::from_meta(&options.to_meta()), options);
217 }
218
219 #[test]
220 fn empty_or_garbage_text_gives_the_defaults() {
221 assert_eq!(JoinOptions::from_meta(""), JoinOptions::default());
222 assert_eq!(JoinOptions::from_meta("junk\nmic"), JoinOptions::default());
223 }
224
225 #[test]
226 fn computer_audio_unmutes_and_selects_chosen_devices_only() {
227 let default = JoinOptions::default();
228 assert_eq!(
229 default.commands_after_join(),
230 vec![CallCommand::Mute(MuteCommand::Unmute)]
231 );
232 let chosen = JoinOptions {
233 mic_on: false,
234 input: DeviceChoice::Device("mic".into()),
235 output: DeviceChoice::Device("speaker".into()),
236 ..default
237 };
238 assert_eq!(
239 chosen.commands_after_join(),
240 vec![
241 CallCommand::SelectInput(DeviceChoice::Device("mic".into())),
242 CallCommand::SelectOutput(DeviceChoice::Device("speaker".into())),
243 ]
244 );
245 }
246
247 #[test]
248 fn without_audio_only_the_audio_is_switched_off() {
249 let options = JoinOptions {
250 audio: AudioChoice::NoAudio,
251 input: DeviceChoice::Device("mic".into()),
252 ..JoinOptions::default()
253 };
254 assert_eq!(
255 options.commands_after_join(),
256 vec![CallCommand::DisableAudio]
257 );
258 }
259}
crates/app/src/call/preview.rs +9 −0
@@ -7,6 +7,7 @@ use calling::blur::BlurSettings;
7 7 use calling::camera::start_camera;
8 8 use calling::capture::Capture;
9 9 use calling::video_frame::picture_from_i420;
10 use calling::video_pattern::{PatternKind, pattern_frame};
10 11 use calling::{BackgroundChoice, CallUpdate, CameraEffects, DeviceChoice, VideoHub, VideoKey};
11 12 use gpui_kit::*;
12 13 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
@@ -78,6 +79,14 @@ impl CameraPreview {
78 79 }
79 80 }
80 81
82 pub fn publish_demo_frame(&self, tick: u32) {
83 if let Some(picture) =
84 picture_from_i420(pattern_frame(PatternKind::Camera, tick), PREVIEW_MAX_WIDTH)
85 {
86 self.hub.publish(VideoKey::LocalCamera, picture);
87 }
88 }
89
81 90 pub fn set_background(&self, choice: BackgroundChoice) {
82 91 let mut latest = self
83 92 .background_request
@@ -7,6 +7,7 @@ use calling::blur::BlurSettings;
7use calling::camera::start_camera;
7use calling::camera::start_camera;
8use calling::capture::Capture;
8use calling::capture::Capture;
9use calling::video_frame::picture_from_i420;
9use calling::video_frame::picture_from_i420;
10use calling::video_pattern::{PatternKind, pattern_frame};
10use calling::{BackgroundChoice, CallUpdate, CameraEffects, DeviceChoice, VideoHub, VideoKey};
11use calling::{BackgroundChoice, CallUpdate, CameraEffects, DeviceChoice, VideoHub, VideoKey};
11use gpui_kit::*;
12use gpui_kit::*;
12use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
13use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
@@ -78,6 +79,14 @@ impl CameraPreview {
78 }
79 }
79 }
80 }
80
81
82 pub fn publish_demo_frame(&self, tick: u32) {
83 if let Some(picture) =
84 picture_from_i420(pattern_frame(PatternKind::Camera, tick), PREVIEW_MAX_WIDTH)
85 {
86 self.hub.publish(VideoKey::LocalCamera, picture);
87 }
88 }
89
81 pub fn set_background(&self, choice: BackgroundChoice) {
90 pub fn set_background(&self, choice: BackgroundChoice) {
82 let mut latest = self
91 let mut latest = self
83 .background_request
92 .background_request
crates/app/src/call/reminder.rs added +380 −0
@@ -0,0 +1,380 @@
1 use std::collections::HashSet;
2
3 use chatsvc::{CalendarEvent, ResponseType};
4 use chrono::{DateTime, Duration, FixedOffset, Utc};
5 use gpui_kit::Context;
6
7 use crate::app_state::{AppEvent, AppState};
8
9 pub const LEAD_MINUTES: i64 = 5;
10 pub const GRACE_MINUTES: i64 = 5;
11 const CHECK_EVERY_SECONDS: i64 = 1;
12
13 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14 pub enum ReminderPhase {
15 Soon,
16 Started,
17 }
18
19 #[derive(Debug, Clone, PartialEq, Eq)]
20 pub struct MeetingToast {
21 pub id: u64,
22 pub event_key: String,
23 pub phase: ReminderPhase,
24 pub subject: String,
25 pub start: DateTime<Utc>,
26 pub join_url: String,
27 }
28
29 fn event_key(event: &CalendarEvent) -> String {
30 format!("{}@{}", event.object_id, event.start.timestamp())
31 }
32
33 pub fn phase_at(event: &CalendarEvent, now: DateTime<Utc>) -> Option<ReminderPhase> {
34 let eligible = event.online
35 && !event.cancelled
36 && !event.all_day
37 && event.join_url.is_some()
38 && event.response != ResponseType::Declined;
39 if !eligible {
40 return None;
41 }
42 if now >= event.start - Duration::minutes(LEAD_MINUTES) && now < event.start {
43 return Some(ReminderPhase::Soon);
44 }
45 let started_until = event
46 .end
47 .min(event.start + Duration::minutes(GRACE_MINUTES));
48 (now >= event.start && now < started_until).then_some(ReminderPhase::Started)
49 }
50
51 pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
52 let clock = toast.start.with_timezone(&offset).format("%H:%M");
53 match toast.phase {
54 ReminderPhase::Started => format!("{clock} - started"),
55 ReminderPhase::Soon => {
56 let minutes = ((toast.start - now).num_seconds().max(0) + 59) / 60;
57 match minutes {
58 0 => format!("{clock} - starting now"),
59 1 => format!("{clock} - starts in 1 min"),
60 minutes => format!("{clock} - starts in {minutes} min"),
61 }
62 }
63 }
64 }
65
66 #[derive(Debug, Default)]
67 pub struct MeetingToasts {
68 entries: Vec<MeetingToast>,
69 fired: HashSet<(String, ReminderPhase)>,
70 next_id: u64,
71 last_check: Option<DateTime<Utc>>,
72 }
73
74 impl MeetingToasts {
75 pub fn entries(&self) -> &[MeetingToast] {
76 &self.entries
77 }
78
79 pub fn get(&self, id: u64) -> Option<&MeetingToast> {
80 self.entries.iter().find(|toast| toast.id == id)
81 }
82
83 pub fn latest(&self) -> Option<&MeetingToast> {
84 self.entries.last()
85 }
86
87 pub fn is_empty(&self) -> bool {
88 self.entries.is_empty()
89 }
90
91 pub fn dismiss(&mut self, id: u64) -> Option<MeetingToast> {
92 let index = self.entries.iter().position(|toast| toast.id == id)?;
93 Some(self.entries.remove(index))
94 }
95
96 pub fn clear(&mut self) -> bool {
97 let had_any = !self.entries.is_empty();
98 self.entries.clear();
99 had_any
100 }
101
102 pub fn is_due_for_check(&self, now: DateTime<Utc>) -> bool {
103 self.last_check
104 .is_none_or(|last| now - last >= Duration::seconds(CHECK_EVERY_SECONDS))
105 }
106
107 pub fn update(&mut self, events: &[CalendarEvent], now: DateTime<Utc>, show: bool) -> bool {
108 self.last_check = Some(now);
109 let before = self.entries.clone();
110 self.entries.retain(|toast| {
111 events
112 .iter()
113 .any(|event| event_key(event) == toast.event_key && phase_at(event, now).is_some())
114 });
115 let keys: HashSet<String> = events.iter().map(event_key).collect();
116 self.fired.retain(|(key, _)| keys.contains(key));
117 for event in events {
118 let Some(phase) = phase_at(event, now) else {
119 continue;
120 };
121 let key = event_key(event);
122 if !self.fired.insert((key.clone(), phase)) || !show {
123 continue;
124 }
125 let Some(join_url) = event.join_url.clone() else {
126 continue;
127 };
128 let subject = if event.subject.is_empty() {
129 "(No title)".to_owned()
130 } else {
131 event.subject.clone()
132 };
133 if let Some(existing) = self.entries.iter_mut().find(|toast| toast.event_key == key) {
134 existing.phase = phase;
135 continue;
136 }
137 self.next_id += 1;
138 self.entries.push(MeetingToast {
139 id: self.next_id,
140 event_key: key,
141 phase,
142 subject,
143 start: event.start,
144 join_url,
145 });
146 }
147 self.entries != before
148 }
149 }
150
151 impl AppState {
152 pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {
153 let now = Utc::now();
154 let in_call = self.call.is_some();
155 let show = show && !in_call && !self.mode.read_only;
156 let changed = self.meeting_toasts.update(&self.calendar_events, now, show);
157 if (in_call && self.meeting_toasts.clear()) || changed {
158 cx.emit(AppEvent::MeetingReminder);
159 cx.notify();
160 }
161 }
162
163 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
164 let Some(toast) = self.meeting_toasts.dismiss(id) else {
165 return;
166 };
167 cx.emit(AppEvent::MeetingReminder);
168 self.join_meeting_link(&toast.join_url, cx);
169 if let Some(pending) = self.prejoin.as_mut() {
170 pending.join.title = toast.subject;
171 }
172 }
173
174 pub fn join_latest_meeting_toast(&mut self, cx: &mut Context<Self>) {
175 if let Some(id) = self.meeting_toasts.latest().map(|toast| toast.id) {
176 self.join_meeting_toast(id, cx);
177 }
178 }
179
180 pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
181 if self.meeting_toasts.dismiss(id).is_some() {
182 cx.emit(AppEvent::MeetingReminder);
183 cx.notify();
184 }
185 }
186 }
187
188 #[cfg(test)]
189 mod tests {
190 use chrono::TimeZone;
191
192 use super::*;
193
194 fn at(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
195 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
196 .unwrap()
197 }
198
199 fn event(id: &str) -> CalendarEvent {
200 CalendarEvent {
201 object_id: id.into(),
202 subject: format!("Meeting {id}"),
203 start: at(9, 0, 0),
204 end: at(9, 30, 0),
205 all_day: false,
206 cancelled: false,
207 online: true,
208 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
209 thread_id: None,
210 organizer_name: Some("Mara".into()),
211 organizer_address: None,
212 ical_uid: None,
213 response: ResponseType::Accepted,
214 }
215 }
216
217 #[test]
218 fn the_phase_follows_the_clock_around_the_start() {
219 let meeting = event("a");
220 assert_eq!(phase_at(&meeting, at(8, 54, 59)), None);
221 assert_eq!(phase_at(&meeting, at(8, 55, 0)), Some(ReminderPhase::Soon));
222 assert_eq!(phase_at(&meeting, at(8, 59, 59)), Some(ReminderPhase::Soon));
223 assert_eq!(
224 phase_at(&meeting, at(9, 0, 0)),
225 Some(ReminderPhase::Started)
226 );
227 assert_eq!(
228 phase_at(&meeting, at(9, 4, 59)),
229 Some(ReminderPhase::Started)
230 );
231 assert_eq!(phase_at(&meeting, at(9, 5, 0)), None);
232 }
233
234 #[test]
235 fn a_short_meeting_stops_reminding_at_its_end() {
236 let short = CalendarEvent {
237 end: at(9, 3, 0),
238 ..event("a")
239 };
240 assert_eq!(phase_at(&short, at(9, 2, 59)), Some(ReminderPhase::Started));
241 assert_eq!(phase_at(&short, at(9, 3, 0)), None);
242 }
243
244 #[test]
245 fn declined_cancelled_all_day_and_offline_events_stay_quiet() {
246 let declined = CalendarEvent {
247 response: ResponseType::Declined,
248 ..event("a")
249 };
250 let cancelled = CalendarEvent {
251 cancelled: true,
252 ..event("a")
253 };
254 let all_day = CalendarEvent {
255 all_day: true,
256 ..event("a")
257 };
258 let offline = CalendarEvent {
259 online: false,
260 ..event("a")
261 };
262 for quiet in [declined, cancelled, all_day, offline] {
263 assert_eq!(phase_at(&quiet, at(8, 58, 0)), None);
264 }
265 }
266
267 #[test]
268 fn each_phase_fires_once_per_meeting() {
269 let events = [event("a")];
270 let mut toasts = MeetingToasts::default();
271 assert!(!toasts.update(&events, at(8, 54, 0), true));
272 assert!(toasts.update(&events, at(8, 55, 0), true));
273 assert_eq!(toasts.entries().len(), 1);
274 let id = toasts.entries()[0].id;
275 toasts.dismiss(id);
276 assert!(!toasts.update(&events, at(8, 56, 0), true));
277 assert!(toasts.is_empty());
278 }
279
280 #[test]
281 fn the_start_brings_a_dismissed_toast_back_and_updates_an_open_one() {
282 let events = [event("a")];
283 let mut toasts = MeetingToasts::default();
284 toasts.update(&events, at(8, 55, 0), true);
285 let id = toasts.entries()[0].id;
286 assert!(toasts.update(&events, at(9, 0, 0), true));
287 assert_eq!(toasts.entries().len(), 1);
288 assert_eq!(toasts.entries()[0].id, id);
289 assert_eq!(toasts.entries()[0].phase, ReminderPhase::Started);
290 let mut dismissed = MeetingToasts::default();
291 dismissed.update(&events, at(8, 55, 0), true);
292 let soon_id = dismissed.entries()[0].id;
293 dismissed.dismiss(soon_id);
294 assert!(dismissed.update(&events, at(9, 0, 0), true));
295 assert_eq!(dismissed.entries()[0].phase, ReminderPhase::Started);
296 }
297
298 #[test]
299 fn a_hidden_reminder_is_spent_and_does_not_appear_later() {
300 let events = [event("a")];
301 let mut toasts = MeetingToasts::default();
302 assert!(!toasts.update(&events, at(8, 56, 0), false));
303 assert!(!toasts.update(&events, at(8, 57, 0), true));
304 assert!(toasts.is_empty());
305 }
306
307 #[test]
308 fn toasts_leave_when_the_window_closes_or_the_event_goes() {
309 let events = [event("a")];
310 let mut toasts = MeetingToasts::default();
311 toasts.update(&events, at(8, 56, 0), true);
312 assert!(toasts.update(&events, at(9, 5, 0), true));
313 assert!(toasts.is_empty());
314 let mut removed = MeetingToasts::default();
315 removed.update(&events, at(8, 56, 0), true);
316 assert!(removed.update(&[], at(8, 57, 0), true));
317 assert!(removed.is_empty());
318 }
319
320 #[test]
321 fn the_latest_toast_is_the_one_a_shortcut_joins() {
322 let events = [event("a"), event("b")];
323 let mut toasts = MeetingToasts::default();
324 toasts.update(&events, at(8, 56, 0), true);
325 assert_eq!(
326 toasts.latest().map(|toast| toast.subject.as_str()),
327 Some("Meeting b")
328 );
329 }
330
331 #[test]
332 fn the_subtitle_counts_down_to_the_start_in_local_time() {
333 let toast = |phase| MeetingToast {
334 id: 1,
335 event_key: "a".into(),
336 phase,
337 subject: "Planning".into(),
338 start: at(9, 0, 0),
339 join_url: "https://example.invalid".into(),
340 };
341 let offset = FixedOffset::east_opt(2 * 3600).unwrap();
342 let soon = toast(ReminderPhase::Soon);
343 assert_eq!(
344 subtitle(&soon, at(8, 55, 0), offset),
345 "11:00 - starts in 5 min"
346 );
347 assert_eq!(
348 subtitle(&soon, at(8, 58, 30), offset),
349 "11:00 - starts in 2 min"
350 );
351 assert_eq!(
352 subtitle(&soon, at(8, 59, 30), offset),
353 "11:00 - starts in 1 min"
354 );
355 assert_eq!(subtitle(&soon, at(9, 0, 0), offset), "11:00 - starting now");
356 assert_eq!(
357 subtitle(&toast(ReminderPhase::Started), at(9, 1, 0), offset),
358 "11:00 - started"
359 );
360 }
361
362 #[test]
363 fn clearing_removes_every_open_toast() {
364 let events = [event("a"), event("b")];
365 let mut toasts = MeetingToasts::default();
366 toasts.update(&events, at(8, 56, 0), true);
367 assert!(toasts.clear());
368 assert!(toasts.is_empty());
369 assert!(!toasts.clear());
370 }
371
372 #[test]
373 fn checks_run_at_most_once_a_second() {
374 let mut toasts = MeetingToasts::default();
375 assert!(toasts.is_due_for_check(at(9, 0, 0)));
376 toasts.update(&[], at(9, 0, 0), true);
377 assert!(!toasts.is_due_for_check(at(9, 0, 0)));
378 assert!(toasts.is_due_for_check(at(9, 0, 1)));
379 }
380 }
@@ -0,0 +1,380 @@
1use std::collections::HashSet;
2
3use chatsvc::{CalendarEvent, ResponseType};
4use chrono::{DateTime, Duration, FixedOffset, Utc};
5use gpui_kit::Context;
6
7use crate::app_state::{AppEvent, AppState};
8
9pub const LEAD_MINUTES: i64 = 5;
10pub const GRACE_MINUTES: i64 = 5;
11const CHECK_EVERY_SECONDS: i64 = 1;
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub enum ReminderPhase {
15 Soon,
16 Started,
17}
18
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct MeetingToast {
21 pub id: u64,
22 pub event_key: String,
23 pub phase: ReminderPhase,
24 pub subject: String,
25 pub start: DateTime<Utc>,
26 pub join_url: String,
27}
28
29fn event_key(event: &CalendarEvent) -> String {
30 format!("{}@{}", event.object_id, event.start.timestamp())
31}
32
33pub fn phase_at(event: &CalendarEvent, now: DateTime<Utc>) -> Option<ReminderPhase> {
34 let eligible = event.online
35 && !event.cancelled
36 && !event.all_day
37 && event.join_url.is_some()
38 && event.response != ResponseType::Declined;
39 if !eligible {
40 return None;
41 }
42 if now >= event.start - Duration::minutes(LEAD_MINUTES) && now < event.start {
43 return Some(ReminderPhase::Soon);
44 }
45 let started_until = event
46 .end
47 .min(event.start + Duration::minutes(GRACE_MINUTES));
48 (now >= event.start && now < started_until).then_some(ReminderPhase::Started)
49}
50
51pub fn subtitle(toast: &MeetingToast, now: DateTime<Utc>, offset: FixedOffset) -> String {
52 let clock = toast.start.with_timezone(&offset).format("%H:%M");
53 match toast.phase {
54 ReminderPhase::Started => format!("{clock} - started"),
55 ReminderPhase::Soon => {
56 let minutes = ((toast.start - now).num_seconds().max(0) + 59) / 60;
57 match minutes {
58 0 => format!("{clock} - starting now"),
59 1 => format!("{clock} - starts in 1 min"),
60 minutes => format!("{clock} - starts in {minutes} min"),
61 }
62 }
63 }
64}
65
66#[derive(Debug, Default)]
67pub struct MeetingToasts {
68 entries: Vec<MeetingToast>,
69 fired: HashSet<(String, ReminderPhase)>,
70 next_id: u64,
71 last_check: Option<DateTime<Utc>>,
72}
73
74impl MeetingToasts {
75 pub fn entries(&self) -> &[MeetingToast] {
76 &self.entries
77 }
78
79 pub fn get(&self, id: u64) -> Option<&MeetingToast> {
80 self.entries.iter().find(|toast| toast.id == id)
81 }
82
83 pub fn latest(&self) -> Option<&MeetingToast> {
84 self.entries.last()
85 }
86
87 pub fn is_empty(&self) -> bool {
88 self.entries.is_empty()
89 }
90
91 pub fn dismiss(&mut self, id: u64) -> Option<MeetingToast> {
92 let index = self.entries.iter().position(|toast| toast.id == id)?;
93 Some(self.entries.remove(index))
94 }
95
96 pub fn clear(&mut self) -> bool {
97 let had_any = !self.entries.is_empty();
98 self.entries.clear();
99 had_any
100 }
101
102 pub fn is_due_for_check(&self, now: DateTime<Utc>) -> bool {
103 self.last_check
104 .is_none_or(|last| now - last >= Duration::seconds(CHECK_EVERY_SECONDS))
105 }
106
107 pub fn update(&mut self, events: &[CalendarEvent], now: DateTime<Utc>, show: bool) -> bool {
108 self.last_check = Some(now);
109 let before = self.entries.clone();
110 self.entries.retain(|toast| {
111 events
112 .iter()
113 .any(|event| event_key(event) == toast.event_key && phase_at(event, now).is_some())
114 });
115 let keys: HashSet<String> = events.iter().map(event_key).collect();
116 self.fired.retain(|(key, _)| keys.contains(key));
117 for event in events {
118 let Some(phase) = phase_at(event, now) else {
119 continue;
120 };
121 let key = event_key(event);
122 if !self.fired.insert((key.clone(), phase)) || !show {
123 continue;
124 }
125 let Some(join_url) = event.join_url.clone() else {
126 continue;
127 };
128 let subject = if event.subject.is_empty() {
129 "(No title)".to_owned()
130 } else {
131 event.subject.clone()
132 };
133 if let Some(existing) = self.entries.iter_mut().find(|toast| toast.event_key == key) {
134 existing.phase = phase;
135 continue;
136 }
137 self.next_id += 1;
138 self.entries.push(MeetingToast {
139 id: self.next_id,
140 event_key: key,
141 phase,
142 subject,
143 start: event.start,
144 join_url,
145 });
146 }
147 self.entries != before
148 }
149}
150
151impl AppState {
152 pub fn tick_meeting_reminders(&mut self, show: bool, cx: &mut Context<Self>) {
153 let now = Utc::now();
154 let in_call = self.call.is_some();
155 let show = show && !in_call && !self.mode.read_only;
156 let changed = self.meeting_toasts.update(&self.calendar_events, now, show);
157 if (in_call && self.meeting_toasts.clear()) || changed {
158 cx.emit(AppEvent::MeetingReminder);
159 cx.notify();
160 }
161 }
162
163 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
164 let Some(toast) = self.meeting_toasts.dismiss(id) else {
165 return;
166 };
167 cx.emit(AppEvent::MeetingReminder);
168 self.join_meeting_link(&toast.join_url, cx);
169 if let Some(pending) = self.prejoin.as_mut() {
170 pending.join.title = toast.subject;
171 }
172 }
173
174 pub fn join_latest_meeting_toast(&mut self, cx: &mut Context<Self>) {
175 if let Some(id) = self.meeting_toasts.latest().map(|toast| toast.id) {
176 self.join_meeting_toast(id, cx);
177 }
178 }
179
180 pub fn dismiss_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
181 if self.meeting_toasts.dismiss(id).is_some() {
182 cx.emit(AppEvent::MeetingReminder);
183 cx.notify();
184 }
185 }
186}
187
188#[cfg(test)]
189mod tests {
190 use chrono::TimeZone;
191
192 use super::*;
193
194 fn at(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
195 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
196 .unwrap()
197 }
198
199 fn event(id: &str) -> CalendarEvent {
200 CalendarEvent {
201 object_id: id.into(),
202 subject: format!("Meeting {id}"),
203 start: at(9, 0, 0),
204 end: at(9, 30, 0),
205 all_day: false,
206 cancelled: false,
207 online: true,
208 join_url: Some("https://teams.microsoft.com/l/meetup-join/x".into()),
209 thread_id: None,
210 organizer_name: Some("Mara".into()),
211 organizer_address: None,
212 ical_uid: None,
213 response: ResponseType::Accepted,
214 }
215 }
216
217 #[test]
218 fn the_phase_follows_the_clock_around_the_start() {
219 let meeting = event("a");
220 assert_eq!(phase_at(&meeting, at(8, 54, 59)), None);
221 assert_eq!(phase_at(&meeting, at(8, 55, 0)), Some(ReminderPhase::Soon));
222 assert_eq!(phase_at(&meeting, at(8, 59, 59)), Some(ReminderPhase::Soon));
223 assert_eq!(
224 phase_at(&meeting, at(9, 0, 0)),
225 Some(ReminderPhase::Started)
226 );
227 assert_eq!(
228 phase_at(&meeting, at(9, 4, 59)),
229 Some(ReminderPhase::Started)
230 );
231 assert_eq!(phase_at(&meeting, at(9, 5, 0)), None);
232 }
233
234 #[test]
235 fn a_short_meeting_stops_reminding_at_its_end() {
236 let short = CalendarEvent {
237 end: at(9, 3, 0),
238 ..event("a")
239 };
240 assert_eq!(phase_at(&short, at(9, 2, 59)), Some(ReminderPhase::Started));
241 assert_eq!(phase_at(&short, at(9, 3, 0)), None);
242 }
243
244 #[test]
245 fn declined_cancelled_all_day_and_offline_events_stay_quiet() {
246 let declined = CalendarEvent {
247 response: ResponseType::Declined,
248 ..event("a")
249 };
250 let cancelled = CalendarEvent {
251 cancelled: true,
252 ..event("a")
253 };
254 let all_day = CalendarEvent {
255 all_day: true,
256 ..event("a")
257 };
258 let offline = CalendarEvent {
259 online: false,
260 ..event("a")
261 };
262 for quiet in [declined, cancelled, all_day, offline] {
263 assert_eq!(phase_at(&quiet, at(8, 58, 0)), None);
264 }
265 }
266
267 #[test]
268 fn each_phase_fires_once_per_meeting() {
269 let events = [event("a")];
270 let mut toasts = MeetingToasts::default();
271 assert!(!toasts.update(&events, at(8, 54, 0), true));
272 assert!(toasts.update(&events, at(8, 55, 0), true));
273 assert_eq!(toasts.entries().len(), 1);
274 let id = toasts.entries()[0].id;
275 toasts.dismiss(id);
276 assert!(!toasts.update(&events, at(8, 56, 0), true));
277 assert!(toasts.is_empty());
278 }
279
280 #[test]
281 fn the_start_brings_a_dismissed_toast_back_and_updates_an_open_one() {
282 let events = [event("a")];
283 let mut toasts = MeetingToasts::default();
284 toasts.update(&events, at(8, 55, 0), true);
285 let id = toasts.entries()[0].id;
286 assert!(toasts.update(&events, at(9, 0, 0), true));
287 assert_eq!(toasts.entries().len(), 1);
288 assert_eq!(toasts.entries()[0].id, id);
289 assert_eq!(toasts.entries()[0].phase, ReminderPhase::Started);
290 let mut dismissed = MeetingToasts::default();
291 dismissed.update(&events, at(8, 55, 0), true);
292 let soon_id = dismissed.entries()[0].id;
293 dismissed.dismiss(soon_id);
294 assert!(dismissed.update(&events, at(9, 0, 0), true));
295 assert_eq!(dismissed.entries()[0].phase, ReminderPhase::Started);
296 }
297
298 #[test]
299 fn a_hidden_reminder_is_spent_and_does_not_appear_later() {
300 let events = [event("a")];
301 let mut toasts = MeetingToasts::default();
302 assert!(!toasts.update(&events, at(8, 56, 0), false));
303 assert!(!toasts.update(&events, at(8, 57, 0), true));
304 assert!(toasts.is_empty());
305 }
306
307 #[test]
308 fn toasts_leave_when_the_window_closes_or_the_event_goes() {
309 let events = [event("a")];
310 let mut toasts = MeetingToasts::default();
311 toasts.update(&events, at(8, 56, 0), true);
312 assert!(toasts.update(&events, at(9, 5, 0), true));
313 assert!(toasts.is_empty());
314 let mut removed = MeetingToasts::default();
315 removed.update(&events, at(8, 56, 0), true);
316 assert!(removed.update(&[], at(8, 57, 0), true));
317 assert!(removed.is_empty());
318 }
319
320 #[test]
321 fn the_latest_toast_is_the_one_a_shortcut_joins() {
322 let events = [event("a"), event("b")];
323 let mut toasts = MeetingToasts::default();
324 toasts.update(&events, at(8, 56, 0), true);
325 assert_eq!(
326 toasts.latest().map(|toast| toast.subject.as_str()),
327 Some("Meeting b")
328 );
329 }
330
331 #[test]
332 fn the_subtitle_counts_down_to_the_start_in_local_time() {
333 let toast = |phase| MeetingToast {
334 id: 1,
335 event_key: "a".into(),
336 phase,
337 subject: "Planning".into(),
338 start: at(9, 0, 0),
339 join_url: "https://example.invalid".into(),
340 };
341 let offset = FixedOffset::east_opt(2 * 3600).unwrap();
342 let soon = toast(ReminderPhase::Soon);
343 assert_eq!(
344 subtitle(&soon, at(8, 55, 0), offset),
345 "11:00 - starts in 5 min"
346 );
347 assert_eq!(
348 subtitle(&soon, at(8, 58, 30), offset),
349 "11:00 - starts in 2 min"
350 );
351 assert_eq!(
352 subtitle(&soon, at(8, 59, 30), offset),
353 "11:00 - starts in 1 min"
354 );
355 assert_eq!(subtitle(&soon, at(9, 0, 0), offset), "11:00 - starting now");
356 assert_eq!(
357 subtitle(&toast(ReminderPhase::Started), at(9, 1, 0), offset),
358 "11:00 - started"
359 );
360 }
361
362 #[test]
363 fn clearing_removes_every_open_toast() {
364 let events = [event("a"), event("b")];
365 let mut toasts = MeetingToasts::default();
366 toasts.update(&events, at(8, 56, 0), true);
367 assert!(toasts.clear());
368 assert!(toasts.is_empty());
369 assert!(!toasts.clear());
370 }
371
372 #[test]
373 fn checks_run_at_most_once_a_second() {
374 let mut toasts = MeetingToasts::default();
375 assert!(toasts.is_due_for_check(at(9, 0, 0)));
376 toasts.update(&[], at(9, 0, 0), true);
377 assert!(!toasts.is_due_for_check(at(9, 0, 0)));
378 assert!(toasts.is_due_for_check(at(9, 0, 1)));
379 }
380}
crates/app/src/call/schedule.rs added +353 −0
@@ -0,0 +1,353 @@
1 use chatsvc::{Attendee, CalendarEvent, Repeat, Reply, ResponseType};
2 use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Utc};
3 use gpui_kit::Context;
4 use tokio::sync::oneshot;
5
6 use super::actions::NOT_CONNECTED_NOTICE;
7 use super::agenda::demo_join_url;
8 use crate::app_state::AppState;
9 use crate::runtime;
10
11 const HALF_HOUR_MINUTES: i64 = 30;
12 const DEFAULT_LENGTH_MINUTES: i64 = 30;
13 const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";
14 const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";
15
16 #[derive(Debug, Clone, PartialEq, Eq)]
17 pub struct Invitee {
18 pub user_id: String,
19 pub name: String,
20 pub mail: Option<String>,
21 }
22
23 #[derive(Debug, Clone, PartialEq, Eq)]
24 pub struct MeetingDraft {
25 pub subject: String,
26 pub start: DateTime<Utc>,
27 pub end: DateTime<Utc>,
28 pub repeat: Repeat,
29 pub details: String,
30 pub people: Vec<Invitee>,
31 }
32
33 pub fn default_window(now: DateTime<Utc>, zone: &impl TimeZone) -> (NaiveDateTime, NaiveDateTime) {
34 let local = now.with_timezone(zone).naive_local();
35 let past_half_hour = i64::from(local.minute()) % HALF_HOUR_MINUTES;
36 let start = local
37 .with_second(0)
38 .and_then(|time| time.with_nanosecond(0))
39 .unwrap_or(local)
40 - Duration::minutes(past_half_hour)
41 + Duration::minutes(HALF_HOUR_MINUTES);
42 (start, start + Duration::minutes(DEFAULT_LENGTH_MINUTES))
43 }
44
45 fn utc_of(zone: &impl TimeZone, date: NaiveDate, time: NaiveTime) -> Option<DateTime<Utc>> {
46 zone.from_local_datetime(&date.and_time(time))
47 .earliest()
48 .map(|moment| moment.with_timezone(&Utc))
49 }
50
51 #[derive(Debug, Clone)]
52 pub struct FormValues {
53 pub subject: String,
54 pub date: Option<NaiveDate>,
55 pub start: NaiveTime,
56 pub end: NaiveTime,
57 pub repeat: Repeat,
58 pub details: String,
59 pub people: Vec<Invitee>,
60 }
61
62 pub fn draft_from_form(values: FormValues, zone: &impl TimeZone) -> Result<MeetingDraft, String> {
63 let subject = values.subject.trim();
64 if subject.is_empty() {
65 return Err("Add a title.".to_owned());
66 }
67 let date = values.date.ok_or_else(|| "Pick a date.".to_owned())?;
68 let start = utc_of(zone, date, values.start)
69 .ok_or_else(|| "That start time does not exist.".to_owned())?;
70 let end =
71 utc_of(zone, date, values.end).ok_or_else(|| "That end time does not exist.".to_owned())?;
72 if end <= start {
73 return Err("The end must be after the start.".to_owned());
74 }
75 Ok(MeetingDraft {
76 subject: subject.to_owned(),
77 start,
78 end,
79 repeat: values.repeat,
80 details: values.details.trim().to_owned(),
81 people: values.people,
82 })
83 }
84
85 pub fn attendee_for(invitee: &Invitee, looked_up: Option<String>) -> Result<Attendee, String> {
86 let address = invitee
87 .mail
88 .clone()
89 .or(looked_up)
90 .ok_or_else(|| format!("No email address found for {}.", invitee.name))?;
91 Ok(Attendee {
92 name: invitee.name.clone(),
93 address,
94 })
95 }
96
97 pub fn response_for(reply: Reply) -> ResponseType {
98 match reply {
99 Reply::Accept => ResponseType::Accepted,
100 Reply::Tentative => ResponseType::Tentative,
101 Reply::Decline => ResponseType::Declined,
102 }
103 }
104
105 fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {
106 CalendarEvent {
107 object_id: format!("demo-new-{serial}"),
108 subject: draft.subject.clone(),
109 start: draft.start,
110 end: draft.end,
111 all_day: false,
112 cancelled: false,
113 online: true,
114 join_url: Some(demo_join_url("demo-new")),
115 thread_id: None,
116 organizer_name: Some("You".to_owned()),
117 organizer_address: None,
118 ical_uid: None,
119 response: ResponseType::Organizer,
120 }
121 }
122
123 impl AppState {
124 pub fn create_meeting(
125 &mut self,
126 draft: MeetingDraft,
127 cx: &mut Context<Self>,
128 ) -> oneshot::Receiver<Result<(), String>> {
129 let (sender, receiver) = oneshot::channel();
130 if self.mode.demo {
131 let event = demo_event(&draft, self.demo_meetings.len() as u64 + 1);
132 self.demo_meetings.push(event);
133 self.refresh_calendar(cx);
134 let _ = sender.send(Ok(()));
135 return receiver;
136 }
137 if self.mode.read_only {
138 let _ = sender.send(Err(READ_ONLY_MESSAGE.to_owned()));
139 return receiver;
140 }
141 let Some(launcher) = self.call_launcher.clone() else {
142 let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));
143 return receiver;
144 };
145 let created = runtime::spawn(async move { launcher.create_meeting(draft).await });
146 cx.spawn(async move |this, cx| {
147 let outcome = created
148 .await
149 .unwrap_or_else(|_| Err("The request was cancelled.".to_owned()))
150 .map(|_| ());
151 if outcome.is_ok() {
152 this.update(cx, |state, cx| state.refresh_calendar(cx)).ok();
153 }
154 let _ = sender.send(outcome);
155 })
156 .detach();
157 receiver
158 }
159
160 pub fn toggle_rsvp_send_response(&mut self, cx: &mut Context<Self>) {
161 self.rsvp_send_response = !self.rsvp_send_response;
162 cx.notify();
163 }
164
165 pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
166 if self.mode.read_only {
167 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
168 return;
169 }
170 let Some(event) = self
171 .calendar_events
172 .iter_mut()
173 .find(|event| event.object_id == event_key)
174 else {
175 return;
176 };
177 let previous = event.response;
178 let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
179 event.response = response_for(reply);
180 self.calls_list.invalidate();
181 cx.notify();
182 let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
183 let Some(launcher) = launcher else {
184 return;
185 };
186 let send_response = self.rsvp_send_response;
187 let answered = runtime::spawn({
188 let event_id = event_id.clone();
189 async move {
190 launcher
191 .respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
192 .await
193 }
194 });
195 cx.spawn(async move |this, cx| {
196 let sent = answered.await.is_ok_and(|result| result.is_ok());
197 this.update(cx, |state, cx| {
198 if sent {
199 state.refresh_calendar(cx);
200 return;
201 }
202 if let Some(event) = state
203 .calendar_events
204 .iter_mut()
205 .find(|event| event.object_id == event_id)
206 {
207 event.response = previous;
208 }
209 state.calls_list.invalidate();
210 state.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
211 })
212 .ok();
213 })
214 .detach();
215 }
216 }
217
218 #[cfg(test)]
219 mod tests {
220 use chrono::FixedOffset;
221
222 use super::*;
223
224 fn utc(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
225 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
226 .unwrap()
227 }
228
229 fn plus_two() -> FixedOffset {
230 FixedOffset::east_opt(2 * 3600).unwrap()
231 }
232
233 fn time(hour: u32, minute: u32) -> NaiveTime {
234 NaiveTime::from_hms_opt(hour, minute, 0).unwrap()
235 }
236
237 fn day() -> Option<NaiveDate> {
238 NaiveDate::from_ymd_opt(2026, 10, 14)
239 }
240
241 fn invitee(name: &str, mail: Option<&str>) -> Invitee {
242 Invitee {
243 user_id: format!("id-{name}"),
244 name: name.to_owned(),
245 mail: mail.map(str::to_owned),
246 }
247 }
248
249 #[test]
250 fn the_default_window_starts_at_the_next_half_hour_and_lasts_thirty_minutes() {
251 let (start, end) = default_window(utc(8, 12, 40), &plus_two());
252 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
253 assert_eq!(end.to_string(), "2026-10-13 11:00:00");
254 let (start, _) = default_window(utc(8, 40, 0), &plus_two());
255 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
256 }
257
258 #[test]
259 fn a_time_on_the_half_hour_moves_to_the_following_one() {
260 let (start, _) = default_window(utc(8, 30, 0), &plus_two());
261 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
262 let (start, _) = default_window(utc(8, 0, 0), &plus_two());
263 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
264 }
265
266 #[test]
267 fn the_late_evening_default_rolls_into_the_next_day() {
268 let (start, end) = default_window(utc(21, 45, 0), &plus_two());
269 assert_eq!(start.to_string(), "2026-10-14 00:00:00");
270 assert_eq!(end.to_string(), "2026-10-14 00:30:00");
271 }
272
273 #[test]
274 fn the_form_turns_local_times_into_utc() {
275 let draft = draft_from_form(
276 FormValues {
277 subject: " Planning ".into(),
278 date: day(),
279 start: time(11, 0),
280 end: time(11, 30),
281 repeat: Repeat::Weekly,
282 details: " Agenda ".into(),
283 people: Vec::new(),
284 },
285 &plus_two(),
286 )
287 .unwrap();
288 assert_eq!(draft.subject, "Planning");
289 assert_eq!(draft.details, "Agenda");
290 assert_eq!(
291 draft.start,
292 Utc.with_ymd_and_hms(2026, 10, 14, 9, 0, 0).unwrap()
293 );
294 assert_eq!(
295 draft.end,
296 Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap()
297 );
298 assert_eq!(draft.repeat, Repeat::Weekly);
299 }
300
301 #[test]
302 fn the_form_rejects_a_missing_title_date_or_backwards_times() {
303 let build = |subject: &str, date, start, end| {
304 let values = FormValues {
305 subject: subject.into(),
306 date,
307 start,
308 end,
309 repeat: Repeat::Never,
310 details: String::new(),
311 people: Vec::new(),
312 };
313 draft_from_form(values, &plus_two())
314 };
315 assert_eq!(
316 build(" ", day(), time(9, 0), time(10, 0)).unwrap_err(),
317 "Add a title."
318 );
319 assert_eq!(
320 build("x", None, time(9, 0), time(10, 0)).unwrap_err(),
321 "Pick a date."
322 );
323 assert_eq!(
324 build("x", day(), time(10, 0), time(10, 0)).unwrap_err(),
325 "The end must be after the start."
326 );
327 assert!(build("x", day(), time(11, 0), time(10, 0)).is_err());
328 }
329
330 #[test]
331 fn an_invitee_uses_the_known_address_before_a_looked_up_one() {
332 let known = invitee("Mara", Some("mara@example.invalid"));
333 let attendee = attendee_for(&known, Some("other@example.invalid".into())).unwrap();
334 assert_eq!(attendee.address, "mara@example.invalid");
335 let unknown = invitee("Jonas", None);
336 let attendee = attendee_for(&unknown, Some("jonas@example.invalid".into())).unwrap();
337 assert_eq!(attendee.address, "jonas@example.invalid");
338 assert_eq!(attendee.name, "Jonas");
339 }
340
341 #[test]
342 fn an_invitee_without_any_address_is_an_error_naming_the_person() {
343 let error = attendee_for(&invitee("Jonas", None), None).unwrap_err();
344 assert_eq!(error, "No email address found for Jonas.");
345 }
346
347 #[test]
348 fn replies_map_to_the_shown_response() {
349 assert_eq!(response_for(Reply::Accept), ResponseType::Accepted);
350 assert_eq!(response_for(Reply::Tentative), ResponseType::Tentative);
351 assert_eq!(response_for(Reply::Decline), ResponseType::Declined);
352 }
353 }
@@ -0,0 +1,353 @@
1use chatsvc::{Attendee, CalendarEvent, Repeat, Reply, ResponseType};
2use chrono::{DateTime, Duration, NaiveDate, NaiveDateTime, NaiveTime, TimeZone, Timelike, Utc};
3use gpui_kit::Context;
4use tokio::sync::oneshot;
5
6use super::actions::NOT_CONNECTED_NOTICE;
7use super::agenda::demo_join_url;
8use crate::app_state::AppState;
9use crate::runtime;
10
11const HALF_HOUR_MINUTES: i64 = 30;
12const DEFAULT_LENGTH_MINUTES: i64 = 30;
13const READ_ONLY_MESSAGE: &str = "Meetings cannot be scheduled in read-only mode.";
14const RESPONSE_FAILED_NOTICE: &str = "Could not send your response";
15
16#[derive(Debug, Clone, PartialEq, Eq)]
17pub struct Invitee {
18 pub user_id: String,
19 pub name: String,
20 pub mail: Option<String>,
21}
22
23#[derive(Debug, Clone, PartialEq, Eq)]
24pub struct MeetingDraft {
25 pub subject: String,
26 pub start: DateTime<Utc>,
27 pub end: DateTime<Utc>,
28 pub repeat: Repeat,
29 pub details: String,
30 pub people: Vec<Invitee>,
31}
32
33pub fn default_window(now: DateTime<Utc>, zone: &impl TimeZone) -> (NaiveDateTime, NaiveDateTime) {
34 let local = now.with_timezone(zone).naive_local();
35 let past_half_hour = i64::from(local.minute()) % HALF_HOUR_MINUTES;
36 let start = local
37 .with_second(0)
38 .and_then(|time| time.with_nanosecond(0))
39 .unwrap_or(local)
40 - Duration::minutes(past_half_hour)
41 + Duration::minutes(HALF_HOUR_MINUTES);
42 (start, start + Duration::minutes(DEFAULT_LENGTH_MINUTES))
43}
44
45fn utc_of(zone: &impl TimeZone, date: NaiveDate, time: NaiveTime) -> Option<DateTime<Utc>> {
46 zone.from_local_datetime(&date.and_time(time))
47 .earliest()
48 .map(|moment| moment.with_timezone(&Utc))
49}
50
51#[derive(Debug, Clone)]
52pub struct FormValues {
53 pub subject: String,
54 pub date: Option<NaiveDate>,
55 pub start: NaiveTime,
56 pub end: NaiveTime,
57 pub repeat: Repeat,
58 pub details: String,
59 pub people: Vec<Invitee>,
60}
61
62pub fn draft_from_form(values: FormValues, zone: &impl TimeZone) -> Result<MeetingDraft, String> {
63 let subject = values.subject.trim();
64 if subject.is_empty() {
65 return Err("Add a title.".to_owned());
66 }
67 let date = values.date.ok_or_else(|| "Pick a date.".to_owned())?;
68 let start = utc_of(zone, date, values.start)
69 .ok_or_else(|| "That start time does not exist.".to_owned())?;
70 let end =
71 utc_of(zone, date, values.end).ok_or_else(|| "That end time does not exist.".to_owned())?;
72 if end <= start {
73 return Err("The end must be after the start.".to_owned());
74 }
75 Ok(MeetingDraft {
76 subject: subject.to_owned(),
77 start,
78 end,
79 repeat: values.repeat,
80 details: values.details.trim().to_owned(),
81 people: values.people,
82 })
83}
84
85pub fn attendee_for(invitee: &Invitee, looked_up: Option<String>) -> Result<Attendee, String> {
86 let address = invitee
87 .mail
88 .clone()
89 .or(looked_up)
90 .ok_or_else(|| format!("No email address found for {}.", invitee.name))?;
91 Ok(Attendee {
92 name: invitee.name.clone(),
93 address,
94 })
95}
96
97pub fn response_for(reply: Reply) -> ResponseType {
98 match reply {
99 Reply::Accept => ResponseType::Accepted,
100 Reply::Tentative => ResponseType::Tentative,
101 Reply::Decline => ResponseType::Declined,
102 }
103}
104
105fn demo_event(draft: &MeetingDraft, serial: u64) -> CalendarEvent {
106 CalendarEvent {
107 object_id: format!("demo-new-{serial}"),
108 subject: draft.subject.clone(),
109 start: draft.start,
110 end: draft.end,
111 all_day: false,
112 cancelled: false,
113 online: true,
114 join_url: Some(demo_join_url("demo-new")),
115 thread_id: None,
116 organizer_name: Some("You".to_owned()),
117 organizer_address: None,
118 ical_uid: None,
119 response: ResponseType::Organizer,
120 }
121}
122
123impl AppState {
124 pub fn create_meeting(
125 &mut self,
126 draft: MeetingDraft,
127 cx: &mut Context<Self>,
128 ) -> oneshot::Receiver<Result<(), String>> {
129 let (sender, receiver) = oneshot::channel();
130 if self.mode.demo {
131 let event = demo_event(&draft, self.demo_meetings.len() as u64 + 1);
132 self.demo_meetings.push(event);
133 self.refresh_calendar(cx);
134 let _ = sender.send(Ok(()));
135 return receiver;
136 }
137 if self.mode.read_only {
138 let _ = sender.send(Err(READ_ONLY_MESSAGE.to_owned()));
139 return receiver;
140 }
141 let Some(launcher) = self.call_launcher.clone() else {
142 let _ = sender.send(Err(NOT_CONNECTED_NOTICE.to_owned()));
143 return receiver;
144 };
145 let created = runtime::spawn(async move { launcher.create_meeting(draft).await });
146 cx.spawn(async move |this, cx| {
147 let outcome = created
148 .await
149 .unwrap_or_else(|_| Err("The request was cancelled.".to_owned()))
150 .map(|_| ());
151 if outcome.is_ok() {
152 this.update(cx, |state, cx| state.refresh_calendar(cx)).ok();
153 }
154 let _ = sender.send(outcome);
155 })
156 .detach();
157 receiver
158 }
159
160 pub fn toggle_rsvp_send_response(&mut self, cx: &mut Context<Self>) {
161 self.rsvp_send_response = !self.rsvp_send_response;
162 cx.notify();
163 }
164
165 pub fn respond_to_event(&mut self, event_key: &str, reply: Reply, cx: &mut Context<Self>) {
166 if self.mode.read_only {
167 self.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
168 return;
169 }
170 let Some(event) = self
171 .calendar_events
172 .iter_mut()
173 .find(|event| event.object_id == event_key)
174 else {
175 return;
176 };
177 let previous = event.response;
178 let (event_id, ical_uid) = (event.object_id.clone(), event.ical_uid.clone());
179 event.response = response_for(reply);
180 self.calls_list.invalidate();
181 cx.notify();
182 let launcher = self.call_launcher.clone().filter(|_| !self.mode.demo);
183 let Some(launcher) = launcher else {
184 return;
185 };
186 let send_response = self.rsvp_send_response;
187 let answered = runtime::spawn({
188 let event_id = event_id.clone();
189 async move {
190 launcher
191 .respond_to_event(&event_id, ical_uid.as_deref(), reply, send_response)
192 .await
193 }
194 });
195 cx.spawn(async move |this, cx| {
196 let sent = answered.await.is_ok_and(|result| result.is_ok());
197 this.update(cx, |state, cx| {
198 if sent {
199 state.refresh_calendar(cx);
200 return;
201 }
202 if let Some(event) = state
203 .calendar_events
204 .iter_mut()
205 .find(|event| event.object_id == event_id)
206 {
207 event.response = previous;
208 }
209 state.calls_list.invalidate();
210 state.raise_notice(RESPONSE_FAILED_NOTICE.to_owned(), None, cx);
211 })
212 .ok();
213 })
214 .detach();
215 }
216}
217
218#[cfg(test)]
219mod tests {
220 use chrono::FixedOffset;
221
222 use super::*;
223
224 fn utc(hour: u32, minute: u32, second: u32) -> DateTime<Utc> {
225 Utc.with_ymd_and_hms(2026, 10, 13, hour, minute, second)
226 .unwrap()
227 }
228
229 fn plus_two() -> FixedOffset {
230 FixedOffset::east_opt(2 * 3600).unwrap()
231 }
232
233 fn time(hour: u32, minute: u32) -> NaiveTime {
234 NaiveTime::from_hms_opt(hour, minute, 0).unwrap()
235 }
236
237 fn day() -> Option<NaiveDate> {
238 NaiveDate::from_ymd_opt(2026, 10, 14)
239 }
240
241 fn invitee(name: &str, mail: Option<&str>) -> Invitee {
242 Invitee {
243 user_id: format!("id-{name}"),
244 name: name.to_owned(),
245 mail: mail.map(str::to_owned),
246 }
247 }
248
249 #[test]
250 fn the_default_window_starts_at_the_next_half_hour_and_lasts_thirty_minutes() {
251 let (start, end) = default_window(utc(8, 12, 40), &plus_two());
252 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
253 assert_eq!(end.to_string(), "2026-10-13 11:00:00");
254 let (start, _) = default_window(utc(8, 40, 0), &plus_two());
255 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
256 }
257
258 #[test]
259 fn a_time_on_the_half_hour_moves_to_the_following_one() {
260 let (start, _) = default_window(utc(8, 30, 0), &plus_two());
261 assert_eq!(start.to_string(), "2026-10-13 11:00:00");
262 let (start, _) = default_window(utc(8, 0, 0), &plus_two());
263 assert_eq!(start.to_string(), "2026-10-13 10:30:00");
264 }
265
266 #[test]
267 fn the_late_evening_default_rolls_into_the_next_day() {
268 let (start, end) = default_window(utc(21, 45, 0), &plus_two());
269 assert_eq!(start.to_string(), "2026-10-14 00:00:00");
270 assert_eq!(end.to_string(), "2026-10-14 00:30:00");
271 }
272
273 #[test]
274 fn the_form_turns_local_times_into_utc() {
275 let draft = draft_from_form(
276 FormValues {
277 subject: " Planning ".into(),
278 date: day(),
279 start: time(11, 0),
280 end: time(11, 30),
281 repeat: Repeat::Weekly,
282 details: " Agenda ".into(),
283 people: Vec::new(),
284 },
285 &plus_two(),
286 )
287 .unwrap();
288 assert_eq!(draft.subject, "Planning");
289 assert_eq!(draft.details, "Agenda");
290 assert_eq!(
291 draft.start,
292 Utc.with_ymd_and_hms(2026, 10, 14, 9, 0, 0).unwrap()
293 );
294 assert_eq!(
295 draft.end,
296 Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap()
297 );
298 assert_eq!(draft.repeat, Repeat::Weekly);
299 }
300
301 #[test]
302 fn the_form_rejects_a_missing_title_date_or_backwards_times() {
303 let build = |subject: &str, date, start, end| {
304 let values = FormValues {
305 subject: subject.into(),
306 date,
307 start,
308 end,
309 repeat: Repeat::Never,
310 details: String::new(),
311 people: Vec::new(),
312 };
313 draft_from_form(values, &plus_two())
314 };
315 assert_eq!(
316 build(" ", day(), time(9, 0), time(10, 0)).unwrap_err(),
317 "Add a title."
318 );
319 assert_eq!(
320 build("x", None, time(9, 0), time(10, 0)).unwrap_err(),
321 "Pick a date."
322 );
323 assert_eq!(
324 build("x", day(), time(10, 0), time(10, 0)).unwrap_err(),
325 "The end must be after the start."
326 );
327 assert!(build("x", day(), time(11, 0), time(10, 0)).is_err());
328 }
329
330 #[test]
331 fn an_invitee_uses_the_known_address_before_a_looked_up_one() {
332 let known = invitee("Mara", Some("mara@example.invalid"));
333 let attendee = attendee_for(&known, Some("other@example.invalid".into())).unwrap();
334 assert_eq!(attendee.address, "mara@example.invalid");
335 let unknown = invitee("Jonas", None);
336 let attendee = attendee_for(&unknown, Some("jonas@example.invalid".into())).unwrap();
337 assert_eq!(attendee.address, "jonas@example.invalid");
338 assert_eq!(attendee.name, "Jonas");
339 }
340
341 #[test]
342 fn an_invitee_without_any_address_is_an_error_naming_the_person() {
343 let error = attendee_for(&invitee("Jonas", None), None).unwrap_err();
344 assert_eq!(error, "No email address found for Jonas.");
345 }
346
347 #[test]
348 fn replies_map_to_the_shown_response() {
349 assert_eq!(response_for(Reply::Accept), ResponseType::Accepted);
350 assert_eq!(response_for(Reply::Tentative), ResponseType::Tentative);
351 assert_eq!(response_for(Reply::Decline), ResponseType::Declined);
352 }
353}
crates/app/src/layout_guard.rs +35 −1
@@ -125,7 +125,7 @@ mod frames {
125 125 use calling::{CallState, CallUpdate, RosterEntry, call_channel};
126 126 use gpui_kit::Entity;
127 127
128 use crate::app_state::{AppState, Mode, Selection};
128 use crate::app_state::{AppHandle, AppState, Mode, Selection};
129 129 use crate::call::{ActiveCall, CallModel};
130 130 use crate::demo;
131 131 use crate::user_activity::UserInput;
@@ -150,6 +150,20 @@ mod frames {
150 150 "shell/islands/main/call-stage",
151 151 "shell/islands/main/call-controls",
152 152 ];
153 const CALLS_TAGS: &[&str] = &[
154 "shell/islands/sidebar/calls-actions",
155 "shell/islands/sidebar/calls-actions/meet-now",
156 "shell/islands/sidebar/calls-actions/new-meeting",
157 ];
158 const PREJOIN_TAGS: &[&str] = &[
159 "shell/islands/main/prejoin",
160 "shell/islands/main/prejoin/preview",
161 "shell/islands/main/prejoin/controls",
162 "shell/islands/main/prejoin/devices",
163 "shell/islands/main/prejoin/audio",
164 "shell/islands/main/prejoin/actions",
165 ];
166 const PREJOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_guard%40thread.v2/0?context=%7b%22Tid%22%3a%22t%22%2c%22Oid%22%3a%22o%22%7d";
153 167 const MENU: &str = "popup-menu";
154 168 const OWN_STATUS: &str = "shell/title-bar/own-status";
155 169 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
@@ -164,6 +178,7 @@ mod frames {
164 178 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
165 179 StatusMenu,
166 180 Call,
181 Prejoin,
167 182 }
168 183
169 184 fn parent_of(path: &str) -> Option<&str> {
@@ -279,6 +294,8 @@ mod frames {
279 294 GUARDED
280 295 .iter()
281 296 .chain(CALL_GUARDED)
297 .chain(CALLS_TAGS)
298 .chain(PREJOIN_TAGS)
282 299 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
283 300 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
284 301 .collect()
@@ -393,6 +410,7 @@ mod frames {
393 410 ),
394 411 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
395 412 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
413 Screen::Prejoin,
396 414 Screen::StatusMenu,
397 415 Screen::Call,
398 416 ];
@@ -413,6 +431,13 @@ mod frames {
413 431 });
414 432 ("call", false)
415 433 }
434 Screen::Prejoin => {
435 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
436 visual.update(|_, cx| {
437 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
438 });
439 ("prejoin", false)
440 }
416 441 Screen::StatusMenu => {
417 442 let tags = collect(&mut visual, None);
418 443 let button = tags
@@ -432,6 +457,11 @@ mod frames {
432 457 if status_menu {
433 458 expected.push(MENU);
434 459 }
460 match screen_name {
461 "calls" => expected.extend(CALLS_TAGS),
462 "prejoin" => expected.extend(PREJOIN_TAGS),
463 _ => {}
464 }
435 465 let mut found = violations(&tags, window, &expected);
436 466 if status_menu {
437 467 let menu = tags
@@ -465,6 +495,10 @@ mod frames {
465 495 })
466 496 });
467 497 }
498 if screen_name == "prejoin" {
499 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
500 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
501 }
468 502 for (key, message) in found {
469 503 let full_key = format!("{screen_name}@{width}x{height}:{key}");
470 504 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
@@ -125,7 +125,7 @@ mod frames {
125 use calling::{CallState, CallUpdate, RosterEntry, call_channel};
125 use calling::{CallState, CallUpdate, RosterEntry, call_channel};
126 use gpui_kit::Entity;
126 use gpui_kit::Entity;
127
127
128 use crate::app_state::{AppState, Mode, Selection};
128 use crate::app_state::{AppHandle, AppState, Mode, Selection};
129 use crate::call::{ActiveCall, CallModel};
129 use crate::call::{ActiveCall, CallModel};
130 use crate::demo;
130 use crate::demo;
131 use crate::user_activity::UserInput;
131 use crate::user_activity::UserInput;
@@ -150,6 +150,20 @@ mod frames {
150 "shell/islands/main/call-stage",
150 "shell/islands/main/call-stage",
151 "shell/islands/main/call-controls",
151 "shell/islands/main/call-controls",
152 ];
152 ];
153 const CALLS_TAGS: &[&str] = &[
154 "shell/islands/sidebar/calls-actions",
155 "shell/islands/sidebar/calls-actions/meet-now",
156 "shell/islands/sidebar/calls-actions/new-meeting",
157 ];
158 const PREJOIN_TAGS: &[&str] = &[
159 "shell/islands/main/prejoin",
160 "shell/islands/main/prejoin/preview",
161 "shell/islands/main/prejoin/controls",
162 "shell/islands/main/prejoin/devices",
163 "shell/islands/main/prejoin/audio",
164 "shell/islands/main/prejoin/actions",
165 ];
166 const PREJOIN_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_guard%40thread.v2/0?context=%7b%22Tid%22%3a%22t%22%2c%22Oid%22%3a%22o%22%7d";
153 const MENU: &str = "popup-menu";
167 const MENU: &str = "popup-menu";
154 const OWN_STATUS: &str = "shell/title-bar/own-status";
168 const OWN_STATUS: &str = "shell/title-bar/own-status";
155 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
169 const RECAP_TAB: &str = "shell/islands/main/recap-tab";
@@ -164,6 +178,7 @@ mod frames {
164 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
178 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
165 StatusMenu,
179 StatusMenu,
166 Call,
180 Call,
181 Prejoin,
167 }
182 }
168
183
169 fn parent_of(path: &str) -> Option<&str> {
184 fn parent_of(path: &str) -> Option<&str> {
@@ -279,6 +294,8 @@ mod frames {
279 GUARDED
294 GUARDED
280 .iter()
295 .iter()
281 .chain(CALL_GUARDED)
296 .chain(CALL_GUARDED)
297 .chain(CALLS_TAGS)
298 .chain(PREJOIN_TAGS)
282 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
299 .chain([&MENU, &RECAP_TAB, &RECAP_REGION])
283 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
300 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
284 .collect()
301 .collect()
@@ -393,6 +410,7 @@ mod frames {
393 ),
410 ),
394 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
411 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
395 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
412 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
413 Screen::Prejoin,
396 Screen::StatusMenu,
414 Screen::StatusMenu,
397 Screen::Call,
415 Screen::Call,
398 ];
416 ];
@@ -413,6 +431,13 @@ mod frames {
413 });
431 });
414 ("call", false)
432 ("call", false)
415 }
433 }
434 Screen::Prejoin => {
435 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
436 visual.update(|_, cx| {
437 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
438 });
439 ("prejoin", false)
440 }
416 Screen::StatusMenu => {
441 Screen::StatusMenu => {
417 let tags = collect(&mut visual, None);
442 let tags = collect(&mut visual, None);
418 let button = tags
443 let button = tags
@@ -432,6 +457,11 @@ mod frames {
432 if status_menu {
457 if status_menu {
433 expected.push(MENU);
458 expected.push(MENU);
434 }
459 }
460 match screen_name {
461 "calls" => expected.extend(CALLS_TAGS),
462 "prejoin" => expected.extend(PREJOIN_TAGS),
463 _ => {}
464 }
435 let mut found = violations(&tags, window, &expected);
465 let mut found = violations(&tags, window, &expected);
436 if status_menu {
466 if status_menu {
437 let menu = tags
467 let menu = tags
@@ -465,6 +495,10 @@ mod frames {
465 })
495 })
466 });
496 });
467 }
497 }
498 if screen_name == "prejoin" {
499 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
500 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
501 }
468 for (key, message) in found {
502 for (key, message) in found {
469 let full_key = format!("{screen_name}@{width}x{height}:{key}");
503 let full_key = format!("{screen_name}@{width}x{height}:{key}");
470 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
504 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
crates/app/src/notify/center.rs +102 −36
@@ -7,7 +7,8 @@ use store::Sidebar;
7 7
8 8 use super::badge::{Badge, badge_for};
9 9 use super::incoming::IncomingTracker;
10 use super::layout::{self, Slot, ring_height};
10 use super::layout::{self, MEETING_HEIGHT, Slot, ring_height};
11 use super::meeting_view::MeetingToastView;
11 12 use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12 13 use super::ring_view::RingView;
13 14 use super::rules::{
@@ -38,6 +39,12 @@ const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
38 39 const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
39 40 const AGENT_BODY_LINES: usize = 2;
40 41
42 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43 enum CallToast {
44 Ring(u64),
45 Meeting(u64),
46 }
47
41 48 struct OpenWindow {
42 49 handle: AnyWindowHandle,
43 50 native: Option<NativeHandle>,
@@ -64,8 +71,8 @@ pub struct NotificationCenter {
64 71 throttle: SoundThrottle,
65 72 windows: HashMap<u64, OpenWindow>,
66 73 opening: HashSet<u64>,
67 ring_windows: HashMap<u64, OpenWindow>,
68 ring_opening: HashSet<u64>,
74 call_windows: HashMap<CallToast, OpenWindow>,
75 call_opening: HashSet<CallToast>,
69 76 ring_tone: Option<platform::RingTone>,
70 77 ringback: Option<platform::RingTone>,
71 78 demo_mode: bool,
@@ -111,8 +118,8 @@ impl NotificationCenter {
111 118 throttle: SoundThrottle::default(),
112 119 windows: HashMap::new(),
113 120 opening: HashSet::new(),
114 ring_windows: HashMap::new(),
115 ring_opening: HashSet::new(),
121 call_windows: HashMap::new(),
122 call_opening: HashSet::new(),
116 123 ring_tone: None,
117 124 ringback: None,
118 125 demo_mode: app.read(cx).mode.demo,
@@ -239,6 +246,7 @@ impl NotificationCenter {
239 246 AppEvent::Selection => self.on_selection(cx),
240 247 AppEvent::Sidebar => self.refresh_badge(cx),
241 248 AppEvent::Ring => self.on_rings_changed(cx),
249 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
242 250 AppEvent::Call => self.sync_ringback(cx),
243 251 _ => {}
244 252 }
@@ -279,9 +287,7 @@ impl NotificationCenter {
279 287 .selection
280 288 .as_ref()
281 289 .is_some_and(|selection| selection.conversation_id() == conversation_id);
282 let own_do_not_disturb = state.directory.me.as_ref().is_some_and(|me| {
283 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
284 });
290 let own_do_not_disturb = own_do_not_disturb(state);
285 291 let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
286 292 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
287 293 _ => false,
@@ -425,14 +431,19 @@ impl NotificationCenter {
425 431 }
426 432 }
427 433
428 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
434 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
429 435 let state = self.app.read(cx);
430 436 let in_call = state.call.is_some();
431 state
437 let rings = state
432 438 .rings
433 439 .ringing()
434 .map(|entry| (entry.ring.ring_id, in_call))
435 .collect()
440 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
441 let meetings = state
442 .meeting_toasts
443 .entries()
444 .iter()
445 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
446 rings.chain(meetings).collect()
436 447 }
437 448
438 449 fn sync_windows(&mut self, cx: &mut Context<Self>) {
@@ -446,15 +457,15 @@ impl NotificationCenter {
446 457 for id in stale {
447 458 self.close_window(id, cx);
448 459 }
449 let rings = self.ringing_ids(cx);
450 let stale_rings: Vec<u64> = self
451 .ring_windows
460 let call_toasts = self.call_toasts(cx);
461 let stale_call_toasts: Vec<CallToast> = self
462 .call_windows
452 463 .keys()
453 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
464 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
454 465 .copied()
455 466 .collect();
456 for id in stale_rings {
457 self.close_ring_window(id, cx);
467 for key in stale_call_toasts {
468 self.close_call_window(key, cx);
458 469 }
459 470 let area = self.work_area(cx);
460 471 let mut heights: Vec<f32> = self
@@ -469,21 +480,30 @@ impl NotificationCenter {
469 480 layout::toast_height(toast, lines)
470 481 })
471 482 .collect();
472 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
483 heights.extend(call_toasts.iter().map(|(_, height)| *height));
473 484 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
474 485 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
475 486 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
476 487 self.place_toast(*id, *slot, area, cx);
477 488 }
478 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
479 self.place_ring(*ring_id, *slot, area, cx);
489 for ((key, _), slot) in call_toasts
490 .iter()
491 .zip(slots.toasts.iter().skip(visible.len()))
492 {
493 self.place_call_toast(*key, *slot, area, cx);
480 494 }
481 495 self.sync_pill(slots.pill, area, cx);
482 496 }
483 497
484 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
485 let Some(window) = self.ring_windows.get(&ring_id) else {
486 self.open_ring_window(ring_id, slot, area, cx);
498 fn place_call_toast(
499 &mut self,
500 key: CallToast,
501 slot: Slot,
502 area: WorkArea,
503 cx: &mut Context<Self>,
504 ) {
505 let Some(window) = self.call_windows.get(&key) else {
506 self.open_call_window(key, slot, area, cx);
487 507 return;
488 508 };
489 509 if let Some(native) = window.native {
@@ -492,39 +512,69 @@ impl NotificationCenter {
492 512 }
493 513 }
494 514
495 fn open_ring_window(
515 fn open_call_window(
496 516 &mut self,
497 ring_id: u64,
517 key: CallToast,
498 518 slot: Slot,
499 519 area: WorkArea,
500 520 cx: &mut Context<Self>,
501 521 ) {
502 if !self.ring_opening.insert(ring_id) {
522 if !self.call_opening.insert(key) {
503 523 return;
504 524 }
505 525 open_popup(
506 526 popup_options(slot, area),
507 527 cx,
508 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
528 move |center, _, cx| match key {
529 CallToast::Ring(ring_id) => {
530 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
531 }
532 CallToast::Meeting(toast_id) => {
533 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
534 }
535 },
509 536 move |this, window| {
510 this.ring_opening.remove(&ring_id);
537 this.call_opening.remove(&key);
511 538 if let Some(window) = window {
512 this.ring_windows.insert(ring_id, window);
539 this.call_windows.insert(key, window);
513 540 }
514 541 },
515 542 );
516 543 }
517 544
518 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
519 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
545 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
546 let closed = self.call_windows.get(&key).is_some_and(|window| {
520 547 window
521 548 .handle
522 549 .update(cx, |_, window, _| window.remove_window())
523 550 .is_ok()
524 551 });
525 552 if closed {
526 self.ring_windows.remove(&ring_id);
553 self.call_windows.remove(&key);
554 }
555 }
556
557 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
558 if !self.app.read(cx).meeting_toasts.is_empty()
559 && !self.main_window_active(cx)
560 && let Some(native) = self.main_native
561 {
562 platform::flash(native);
527 563 }
564 self.sync_windows(cx);
565 cx.notify();
566 }
567
568 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
569 self.raise_main_window(cx);
570 self.app
571 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
572 }
573
574 fn reminders_quiet(&self, cx: &App) -> bool {
575 self.settings.do_not_disturb
576 || platform::system_quiet()
577 || own_do_not_disturb(self.app.read(cx))
528 578 }
529 579
530 580 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
@@ -700,10 +750,20 @@ impl NotificationCenter {
700 750 if !self.app.read(cx).rings.is_empty() {
701 751 self.app.update(cx, |state, cx| state.tick_rings(cx));
702 752 }
753 if self
754 .app
755 .read(cx)
756 .meeting_toasts
757 .is_due_for_check(Utc::now())
758 {
759 let show = !self.reminders_quiet(cx);
760 self.app
761 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
762 }
703 763 if !self.stack.is_empty()
704 764 || !self.windows.is_empty()
705 765 || self.pill.is_some()
706 || !self.ring_windows.is_empty()
766 || !self.call_windows.is_empty()
707 767 {
708 768 self.sync_windows(cx);
709 769 cx.notify();
@@ -1013,10 +1073,10 @@ impl NotificationCenter {
1013 1073
1014 1074 /// Opens a window outside the current update: `open_window` draws right away, and every
1015 1075 /// notification view reads the center while rendering.
1016 fn open_popup<V: Render>(
1076 fn open_popup<V: Into<AnyView>>(
1017 1077 options: WindowOptions,
1018 1078 cx: &mut Context<NotificationCenter>,
1019 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
1079 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1020 1080 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1021 1081 ) {
1022 1082 let center = cx.entity();
@@ -1046,6 +1106,12 @@ fn open_popup<V: Render>(
1046 1106 });
1047 1107 }
1048 1108
1109 fn own_do_not_disturb(state: &AppState) -> bool {
1110 state.directory.me.as_ref().is_some_and(|me| {
1111 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
1112 })
1113 }
1114
1049 1115 fn demo_scene() -> Option<DemoScene> {
1050 1116 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1051 1117 }
@@ -7,7 +7,8 @@ use store::Sidebar;
7
7
8use super::badge::{Badge, badge_for};
8use super::badge::{Badge, badge_for};
9use super::incoming::IncomingTracker;
9use super::incoming::IncomingTracker;
10use super::layout::{self, Slot, ring_height};
10use super::layout::{self, MEETING_HEIGHT, Slot, ring_height};
11use super::meeting_view::MeetingToastView;
11use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12use super::platform::{self, NativeHandle, Tray, TrayCommand, WorkArea};
12use super::ring_view::RingView;
13use super::ring_view::RingView;
13use super::rules::{
14use super::rules::{
@@ -38,6 +39,12 @@ const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
38const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
39const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
39const AGENT_BODY_LINES: usize = 2;
40const AGENT_BODY_LINES: usize = 2;
40
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
43enum CallToast {
44 Ring(u64),
45 Meeting(u64),
46}
47
41struct OpenWindow {
48struct OpenWindow {
42 handle: AnyWindowHandle,
49 handle: AnyWindowHandle,
43 native: Option<NativeHandle>,
50 native: Option<NativeHandle>,
@@ -64,8 +71,8 @@ pub struct NotificationCenter {
64 throttle: SoundThrottle,
71 throttle: SoundThrottle,
65 windows: HashMap<u64, OpenWindow>,
72 windows: HashMap<u64, OpenWindow>,
66 opening: HashSet<u64>,
73 opening: HashSet<u64>,
67 ring_windows: HashMap<u64, OpenWindow>,
74 call_windows: HashMap<CallToast, OpenWindow>,
68 ring_opening: HashSet<u64>,
75 call_opening: HashSet<CallToast>,
69 ring_tone: Option<platform::RingTone>,
76 ring_tone: Option<platform::RingTone>,
70 ringback: Option<platform::RingTone>,
77 ringback: Option<platform::RingTone>,
71 demo_mode: bool,
78 demo_mode: bool,
@@ -111,8 +118,8 @@ impl NotificationCenter {
111 throttle: SoundThrottle::default(),
118 throttle: SoundThrottle::default(),
112 windows: HashMap::new(),
119 windows: HashMap::new(),
113 opening: HashSet::new(),
120 opening: HashSet::new(),
114 ring_windows: HashMap::new(),
121 call_windows: HashMap::new(),
115 ring_opening: HashSet::new(),
122 call_opening: HashSet::new(),
116 ring_tone: None,
123 ring_tone: None,
117 ringback: None,
124 ringback: None,
118 demo_mode: app.read(cx).mode.demo,
125 demo_mode: app.read(cx).mode.demo,
@@ -239,6 +246,7 @@ impl NotificationCenter {
239 AppEvent::Selection => self.on_selection(cx),
246 AppEvent::Selection => self.on_selection(cx),
240 AppEvent::Sidebar => self.refresh_badge(cx),
247 AppEvent::Sidebar => self.refresh_badge(cx),
241 AppEvent::Ring => self.on_rings_changed(cx),
248 AppEvent::Ring => self.on_rings_changed(cx),
249 AppEvent::MeetingReminder => self.on_meeting_reminder(cx),
242 AppEvent::Call => self.sync_ringback(cx),
250 AppEvent::Call => self.sync_ringback(cx),
243 _ => {}
251 _ => {}
244 }
252 }
@@ -279,9 +287,7 @@ impl NotificationCenter {
279 .selection
287 .selection
280 .as_ref()
288 .as_ref()
281 .is_some_and(|selection| selection.conversation_id() == conversation_id);
289 .is_some_and(|selection| selection.conversation_id() == conversation_id);
282 let own_do_not_disturb = state.directory.me.as_ref().is_some_and(|me| {
290 let own_do_not_disturb = own_do_not_disturb(state);
283 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
284 });
285 let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
291 let server_in_call = match (state.engine.as_ref(), state.directory.me.as_ref()) {
286 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
292 (Some(engine), Some(me)) => data::in_call(engine, &me.user_id),
287 _ => false,
293 _ => false,
@@ -425,14 +431,19 @@ impl NotificationCenter {
425 }
431 }
426 }
432 }
427
433
428 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
434 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
429 let state = self.app.read(cx);
435 let state = self.app.read(cx);
430 let in_call = state.call.is_some();
436 let in_call = state.call.is_some();
431 state
437 let rings = state
432 .rings
438 .rings
433 .ringing()
439 .ringing()
434 .map(|entry| (entry.ring.ring_id, in_call))
440 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
435 .collect()
441 let meetings = state
442 .meeting_toasts
443 .entries()
444 .iter()
445 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
446 rings.chain(meetings).collect()
436 }
447 }
437
448
438 fn sync_windows(&mut self, cx: &mut Context<Self>) {
449 fn sync_windows(&mut self, cx: &mut Context<Self>) {
@@ -446,15 +457,15 @@ impl NotificationCenter {
446 for id in stale {
457 for id in stale {
447 self.close_window(id, cx);
458 self.close_window(id, cx);
448 }
459 }
449 let rings = self.ringing_ids(cx);
460 let call_toasts = self.call_toasts(cx);
450 let stale_rings: Vec<u64> = self
461 let stale_call_toasts: Vec<CallToast> = self
451 .ring_windows
462 .call_windows
452 .keys()
463 .keys()
453 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
464 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
454 .copied()
465 .copied()
455 .collect();
466 .collect();
456 for id in stale_rings {
467 for key in stale_call_toasts {
457 self.close_ring_window(id, cx);
468 self.close_call_window(key, cx);
458 }
469 }
459 let area = self.work_area(cx);
470 let area = self.work_area(cx);
460 let mut heights: Vec<f32> = self
471 let mut heights: Vec<f32> = self
@@ -469,21 +480,30 @@ impl NotificationCenter {
469 layout::toast_height(toast, lines)
480 layout::toast_height(toast, lines)
470 })
481 })
471 .collect();
482 .collect();
472 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
483 heights.extend(call_toasts.iter().map(|(_, height)| *height));
473 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
484 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
474 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
485 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
475 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
486 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
476 self.place_toast(*id, *slot, area, cx);
487 self.place_toast(*id, *slot, area, cx);
477 }
488 }
478 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
489 for ((key, _), slot) in call_toasts
479 self.place_ring(*ring_id, *slot, area, cx);
490 .iter()
491 .zip(slots.toasts.iter().skip(visible.len()))
492 {
493 self.place_call_toast(*key, *slot, area, cx);
480 }
494 }
481 self.sync_pill(slots.pill, area, cx);
495 self.sync_pill(slots.pill, area, cx);
482 }
496 }
483
497
484 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
498 fn place_call_toast(
485 let Some(window) = self.ring_windows.get(&ring_id) else {
499 &mut self,
486 self.open_ring_window(ring_id, slot, area, cx);
500 key: CallToast,
501 slot: Slot,
502 area: WorkArea,
503 cx: &mut Context<Self>,
504 ) {
505 let Some(window) = self.call_windows.get(&key) else {
506 self.open_call_window(key, slot, area, cx);
487 return;
507 return;
488 };
508 };
489 if let Some(native) = window.native {
509 if let Some(native) = window.native {
@@ -492,39 +512,69 @@ impl NotificationCenter {
492 }
512 }
493 }
513 }
494
514
495 fn open_ring_window(
515 fn open_call_window(
496 &mut self,
516 &mut self,
497 ring_id: u64,
517 key: CallToast,
498 slot: Slot,
518 slot: Slot,
499 area: WorkArea,
519 area: WorkArea,
500 cx: &mut Context<Self>,
520 cx: &mut Context<Self>,
501 ) {
521 ) {
502 if !self.ring_opening.insert(ring_id) {
522 if !self.call_opening.insert(key) {
503 return;
523 return;
504 }
524 }
505 open_popup(
525 open_popup(
506 popup_options(slot, area),
526 popup_options(slot, area),
507 cx,
527 cx,
508 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
528 move |center, _, cx| match key {
529 CallToast::Ring(ring_id) => {
530 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
531 }
532 CallToast::Meeting(toast_id) => {
533 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
534 }
535 },
509 move |this, window| {
536 move |this, window| {
510 this.ring_opening.remove(&ring_id);
537 this.call_opening.remove(&key);
511 if let Some(window) = window {
538 if let Some(window) = window {
512 this.ring_windows.insert(ring_id, window);
539 this.call_windows.insert(key, window);
513 }
540 }
514 },
541 },
515 );
542 );
516 }
543 }
517
544
518 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
545 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
519 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
546 let closed = self.call_windows.get(&key).is_some_and(|window| {
520 window
547 window
521 .handle
548 .handle
522 .update(cx, |_, window, _| window.remove_window())
549 .update(cx, |_, window, _| window.remove_window())
523 .is_ok()
550 .is_ok()
524 });
551 });
525 if closed {
552 if closed {
526 self.ring_windows.remove(&ring_id);
553 self.call_windows.remove(&key);
554 }
555 }
556
557 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
558 if !self.app.read(cx).meeting_toasts.is_empty()
559 && !self.main_window_active(cx)
560 && let Some(native) = self.main_native
561 {
562 platform::flash(native);
527 }
563 }
564 self.sync_windows(cx);
565 cx.notify();
566 }
567
568 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
569 self.raise_main_window(cx);
570 self.app
571 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
572 }
573
574 fn reminders_quiet(&self, cx: &App) -> bool {
575 self.settings.do_not_disturb
576 || platform::system_quiet()
577 || own_do_not_disturb(self.app.read(cx))
528 }
578 }
529
579
530 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
580 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
@@ -700,10 +750,20 @@ impl NotificationCenter {
700 if !self.app.read(cx).rings.is_empty() {
750 if !self.app.read(cx).rings.is_empty() {
701 self.app.update(cx, |state, cx| state.tick_rings(cx));
751 self.app.update(cx, |state, cx| state.tick_rings(cx));
702 }
752 }
753 if self
754 .app
755 .read(cx)
756 .meeting_toasts
757 .is_due_for_check(Utc::now())
758 {
759 let show = !self.reminders_quiet(cx);
760 self.app
761 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
762 }
703 if !self.stack.is_empty()
763 if !self.stack.is_empty()
704 || !self.windows.is_empty()
764 || !self.windows.is_empty()
705 || self.pill.is_some()
765 || self.pill.is_some()
706 || !self.ring_windows.is_empty()
766 || !self.call_windows.is_empty()
707 {
767 {
708 self.sync_windows(cx);
768 self.sync_windows(cx);
709 cx.notify();
769 cx.notify();
@@ -1013,10 +1073,10 @@ impl NotificationCenter {
1013
1073
1014/// Opens a window outside the current update: `open_window` draws right away, and every
1074/// Opens a window outside the current update: `open_window` draws right away, and every
1015/// notification view reads the center while rendering.
1075/// notification view reads the center while rendering.
1016fn open_popup<V: Render>(
1076fn open_popup<V: Into<AnyView>>(
1017 options: WindowOptions,
1077 options: WindowOptions,
1018 cx: &mut Context<NotificationCenter>,
1078 cx: &mut Context<NotificationCenter>,
1019 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
1079 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1020 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1080 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1021) {
1081) {
1022 let center = cx.entity();
1082 let center = cx.entity();
@@ -1046,6 +1106,12 @@ fn open_popup<V: Render>(
1046 });
1106 });
1047}
1107}
1048
1108
1109fn own_do_not_disturb(state: &AppState) -> bool {
1110 state.directory.me.as_ref().is_some_and(|me| {
1111 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
1112 })
1113}
1114
1049fn demo_scene() -> Option<DemoScene> {
1115fn demo_scene() -> Option<DemoScene> {
1050 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1116 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1051}
1117}
crates/app/src/notify/layout.rs +1 −0
@@ -27,6 +27,7 @@ const CONFIRM_HEIGHT: f32 = 56.;
27 27 const AGENT_CHROME_HEIGHT: f32 = 116.;
28 28 pub const AGENT_BODY_WIDTH: f32 = TOAST_WIDTH - 2. * TOAST_PADDING - 2.;
29 29 const RING_BASE_HEIGHT: f32 = 120.;
30 pub const MEETING_HEIGHT: f32 = 112.;
30 31 const RING_NOTE_HEIGHT: f32 = 18.;
31 32
32 33 #[derive(Debug, Clone, Copy, PartialEq)]
@@ -27,6 +27,7 @@ const CONFIRM_HEIGHT: f32 = 56.;
27const AGENT_CHROME_HEIGHT: f32 = 116.;
27const AGENT_CHROME_HEIGHT: f32 = 116.;
28pub const AGENT_BODY_WIDTH: f32 = TOAST_WIDTH - 2. * TOAST_PADDING - 2.;
28pub const AGENT_BODY_WIDTH: f32 = TOAST_WIDTH - 2. * TOAST_PADDING - 2.;
29const RING_BASE_HEIGHT: f32 = 120.;
29const RING_BASE_HEIGHT: f32 = 120.;
30pub const MEETING_HEIGHT: f32 = 112.;
30const RING_NOTE_HEIGHT: f32 = 18.;
31const RING_NOTE_HEIGHT: f32 = 18.;
31
32
32#[derive(Debug, Clone, Copy, PartialEq)]
33#[derive(Debug, Clone, Copy, PartialEq)]
crates/app/src/notify/meeting_view.rs added +121 −0
@@ -0,0 +1,121 @@
1 use chrono::{Local, Offset, Utc};
2 use gpui_kit::assets::IconName;
3 use gpui_kit::component::{h_flex, v_flex};
4 use gpui_kit::*;
5
6 use super::center::NotificationCenter;
7 use super::layout::{AVATAR_GAP, TOAST_PADDING};
8 use super::ring_view::{RING_AVATAR, RING_BORDER, TOAST_RADIUS, answer_button};
9 use crate::app_state::AppState;
10 use crate::call::meeting_subtitle;
11 use crate::theme;
12 use crate::views::widgets::icon;
13
14 const MEETING_ICON: f32 = 22.;
15
16 pub struct MeetingToastView {
17 center: Entity<NotificationCenter>,
18 app: Entity<AppState>,
19 toast_id: u64,
20 _subscriptions: [Subscription; 2],
21 }
22
23 impl MeetingToastView {
24 pub fn new(center: Entity<NotificationCenter>, toast_id: u64, cx: &mut Context<Self>) -> Self {
25 let app = center.read(cx).app().clone();
26 let subscriptions = [
27 cx.observe(&app, |_, _, cx| cx.notify()),
28 cx.observe(&center, |_, _, cx| cx.notify()),
29 ];
30 MeetingToastView {
31 center,
32 app,
33 toast_id,
34 _subscriptions: subscriptions,
35 }
36 }
37 }
38
39 impl Render for MeetingToastView {
40 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
41 let Some(toast) = self.app.read(cx).meeting_toasts.get(self.toast_id).cloned() else {
42 return div()
43 .size_full()
44 .bg(theme::surface_raised())
45 .into_any_element();
46 };
47 window.set_window_title(&toast.subject);
48 let subtitle = meeting_subtitle(&toast, Utc::now(), Local::now().offset().fix());
49 let toast_id = self.toast_id;
50 let dismiss_app = self.app.clone();
51 let join_center = self.center.clone();
52 let dismiss = answer_button(
53 "meeting-dismiss",
54 "Dismiss",
55 IconName::Close,
56 theme::surface_raised(),
57 )
58 .border_1()
59 .border_color(theme::border_strong())
60 .text_color(theme::text())
61 .on_click(move |_, _, cx| {
62 cx.stop_propagation();
63 dismiss_app.update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx));
64 });
65 let join = answer_button("meeting-join", "Join", IconName::Video, theme::accent())
66 .text_color(theme::on_accent())
67 .on_click(move |_, _, cx| {
68 cx.stop_propagation();
69 join_center.update(cx, |center, cx| center.join_meeting_toast(toast_id, cx));
70 });
71 div()
72 .id(("meeting-toast", toast_id))
73 .size_full()
74 .rounded(px(TOAST_RADIUS))
75 .bg(theme::surface_raised())
76 .border(px(RING_BORDER))
77 .border_color(theme::accent())
78 .overflow_hidden()
79 .child(
80 div().size_full().p(px(TOAST_PADDING)).child(
81 h_flex()
82 .size_full()
83 .gap(px(AVATAR_GAP))
84 .items_start()
85 .child(
86 div()
87 .size(px(RING_AVATAR))
88 .flex_none()
89 .flex()
90 .items_center()
91 .justify_center()
92 .rounded_full()
93 .bg(theme::border_strong())
94 .child(icon(IconName::Video, MEETING_ICON, theme::text())),
95 )
96 .child(
97 v_flex()
98 .flex_1()
99 .min_w_0()
100 .gap(px(2.))
101 .child(
102 div()
103 .truncate()
104 .text_size(px(15.))
105 .font_weight(FontWeight::SEMIBOLD)
106 .text_color(theme::text())
107 .child(toast.subject.clone()),
108 )
109 .child(
110 div()
111 .text_size(px(12.5))
112 .text_color(theme::text_muted())
113 .child(subtitle),
114 )
115 .child(h_flex().mt(px(8.)).gap(px(6.)).child(dismiss).child(join)),
116 ),
117 ),
118 )
119 .into_any_element()
120 }
121 }
@@ -0,0 +1,121 @@
1use chrono::{Local, Offset, Utc};
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::*;
5
6use super::center::NotificationCenter;
7use super::layout::{AVATAR_GAP, TOAST_PADDING};
8use super::ring_view::{RING_AVATAR, RING_BORDER, TOAST_RADIUS, answer_button};
9use crate::app_state::AppState;
10use crate::call::meeting_subtitle;
11use crate::theme;
12use crate::views::widgets::icon;
13
14const MEETING_ICON: f32 = 22.;
15
16pub struct MeetingToastView {
17 center: Entity<NotificationCenter>,
18 app: Entity<AppState>,
19 toast_id: u64,
20 _subscriptions: [Subscription; 2],
21}
22
23impl MeetingToastView {
24 pub fn new(center: Entity<NotificationCenter>, toast_id: u64, cx: &mut Context<Self>) -> Self {
25 let app = center.read(cx).app().clone();
26 let subscriptions = [
27 cx.observe(&app, |_, _, cx| cx.notify()),
28 cx.observe(&center, |_, _, cx| cx.notify()),
29 ];
30 MeetingToastView {
31 center,
32 app,
33 toast_id,
34 _subscriptions: subscriptions,
35 }
36 }
37}
38
39impl Render for MeetingToastView {
40 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
41 let Some(toast) = self.app.read(cx).meeting_toasts.get(self.toast_id).cloned() else {
42 return div()
43 .size_full()
44 .bg(theme::surface_raised())
45 .into_any_element();
46 };
47 window.set_window_title(&toast.subject);
48 let subtitle = meeting_subtitle(&toast, Utc::now(), Local::now().offset().fix());
49 let toast_id = self.toast_id;
50 let dismiss_app = self.app.clone();
51 let join_center = self.center.clone();
52 let dismiss = answer_button(
53 "meeting-dismiss",
54 "Dismiss",
55 IconName::Close,
56 theme::surface_raised(),
57 )
58 .border_1()
59 .border_color(theme::border_strong())
60 .text_color(theme::text())
61 .on_click(move |_, _, cx| {
62 cx.stop_propagation();
63 dismiss_app.update(cx, |state, cx| state.dismiss_meeting_toast(toast_id, cx));
64 });
65 let join = answer_button("meeting-join", "Join", IconName::Video, theme::accent())
66 .text_color(theme::on_accent())
67 .on_click(move |_, _, cx| {
68 cx.stop_propagation();
69 join_center.update(cx, |center, cx| center.join_meeting_toast(toast_id, cx));
70 });
71 div()
72 .id(("meeting-toast", toast_id))
73 .size_full()
74 .rounded(px(TOAST_RADIUS))
75 .bg(theme::surface_raised())
76 .border(px(RING_BORDER))
77 .border_color(theme::accent())
78 .overflow_hidden()
79 .child(
80 div().size_full().p(px(TOAST_PADDING)).child(
81 h_flex()
82 .size_full()
83 .gap(px(AVATAR_GAP))
84 .items_start()
85 .child(
86 div()
87 .size(px(RING_AVATAR))
88 .flex_none()
89 .flex()
90 .items_center()
91 .justify_center()
92 .rounded_full()
93 .bg(theme::border_strong())
94 .child(icon(IconName::Video, MEETING_ICON, theme::text())),
95 )
96 .child(
97 v_flex()
98 .flex_1()
99 .min_w_0()
100 .gap(px(2.))
101 .child(
102 div()
103 .truncate()
104 .text_size(px(15.))
105 .font_weight(FontWeight::SEMIBOLD)
106 .text_color(theme::text())
107 .child(toast.subject.clone()),
108 )
109 .child(
110 div()
111 .text_size(px(12.5))
112 .text_color(theme::text_muted())
113 .child(subtitle),
114 )
115 .child(h_flex().mt(px(8.)).gap(px(6.)).child(dismiss).child(join)),
116 ),
117 ),
118 )
119 .into_any_element()
120 }
121}
crates/app/src/notify/mod.rs +1 −0
@@ -4,6 +4,7 @@ mod badge;
4 4 mod center;
5 5 mod incoming;
6 6 mod layout;
7 mod meeting_view;
7 8 #[cfg_attr(not(windows), allow(dead_code))]
8 9 pub(crate) mod platform;
9 10 #[cfg_attr(not(windows), allow(dead_code))]
@@ -4,6 +4,7 @@ mod badge;
4mod center;
4mod center;
5mod incoming;
5mod incoming;
6mod layout;
6mod layout;
7mod meeting_view;
7#[cfg_attr(not(windows), allow(dead_code))]
8#[cfg_attr(not(windows), allow(dead_code))]
8pub(crate) mod platform;
9pub(crate) mod platform;
9#[cfg_attr(not(windows), allow(dead_code))]
10#[cfg_attr(not(windows), allow(dead_code))]
crates/app/src/notify/ring_view.rs +3 −3
@@ -14,10 +14,10 @@ use crate::views::call_view::pulsing;
14 14 use crate::views::widgets::icon;
15 15
16 16 pub const RING_AVATAR: f32 = 56.;
17 const RING_BORDER: f32 = 2.;
17 pub(super) const RING_BORDER: f32 = 2.;
18 18 const RING_WIDTH: f32 = 3.;
19 19 const RING_GAP: f32 = 3.;
20 const TOAST_RADIUS: f32 = 12.;
20 pub(super) const TOAST_RADIUS: f32 = 12.;
21 21 const BUTTON_HEIGHT: f32 = 32.;
22 22 pub const ENDS_CURRENT_CALL: &str = "Accept ends current call";
23 23
@@ -39,7 +39,7 @@ impl RingView {
39 39 }
40 40 }
41 41
42 fn answer_button(
42 pub(super) fn answer_button(
43 43 id: &'static str,
44 44 label: &str,
45 45 glyph: IconName,
@@ -14,10 +14,10 @@ use crate::views::call_view::pulsing;
14use crate::views::widgets::icon;
14use crate::views::widgets::icon;
15
15
16pub const RING_AVATAR: f32 = 56.;
16pub const RING_AVATAR: f32 = 56.;
17const RING_BORDER: f32 = 2.;
17pub(super) const RING_BORDER: f32 = 2.;
18const RING_WIDTH: f32 = 3.;
18const RING_WIDTH: f32 = 3.;
19const RING_GAP: f32 = 3.;
19const RING_GAP: f32 = 3.;
20const TOAST_RADIUS: f32 = 12.;
20pub(super) const TOAST_RADIUS: f32 = 12.;
21const BUTTON_HEIGHT: f32 = 32.;
21const BUTTON_HEIGHT: f32 = 32.;
22pub const ENDS_CURRENT_CALL: &str = "Accept ends current call";
22pub const ENDS_CURRENT_CALL: &str = "Accept ends current call";
23
23
@@ -39,7 +39,7 @@ impl RingView {
39 }
39 }
40}
40}
41
41
42fn answer_button(
42pub(super) fn answer_button(
43 id: &'static str,
43 id: &'static str,
44 label: &str,
44 label: &str,
45 glyph: IconName,
45 glyph: IconName,
crates/app/src/views/call_view.rs +10 −1
@@ -60,6 +60,7 @@ pub(super) const STRIP_VISIBLE: f32 = 4.;
60 60 const TILE_RADIUS: f32 = 12.;
61 61 const NAME_PLATE_BACKGROUND: f32 = 0.6;
62 62 pub const NO_MICROPHONE_HINT: &str = "No microphone found";
63 const AUDIO_OFF_HINT: &str = "Audio is off for this meeting";
63 64 pub const NO_CAMERA_HINT: &str = "No camera found";
64 65 pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";
65 66 pub const NO_WINDOWS_HINT: &str = "No windows found";
@@ -350,10 +351,15 @@ pub fn mute_button(
350 351 };
351 352 let button = round_control(id, glyph, background, foreground).size(px(size));
352 353 if !model.can_unmute() {
354 let hint = if model.audio_off {
355 AUDIO_OFF_HINT
356 } else {
357 NO_MICROPHONE_HINT
358 };
353 359 return button
354 360 .opacity(DISABLED_OPACITY)
355 361 .cursor_default()
356 .tooltip(|window, cx| Tooltip::new(NO_MICROPHONE_HINT).build(window, cx));
362 .tooltip(move |window, cx| Tooltip::new(hint).build(window, cx));
357 363 }
358 364 let app = app.clone();
359 365 button.on_click(move |_, _, cx| {
@@ -824,6 +830,9 @@ fn devices_menu(
824 830 model: &CallModel,
825 831 mic: MicSettings,
826 832 ) -> PopupMenu {
833 if model.audio_off {
834 return popup.item(PopupMenuItem::new(AUDIO_OFF_HINT).disabled(true));
835 }
827 836 let input_app = app.clone();
828 837 let output_app = app.clone();
829 838 let inputs = device_items(
@@ -60,6 +60,7 @@ pub(super) const STRIP_VISIBLE: f32 = 4.;
60const TILE_RADIUS: f32 = 12.;
60const TILE_RADIUS: f32 = 12.;
61const NAME_PLATE_BACKGROUND: f32 = 0.6;
61const NAME_PLATE_BACKGROUND: f32 = 0.6;
62pub const NO_MICROPHONE_HINT: &str = "No microphone found";
62pub const NO_MICROPHONE_HINT: &str = "No microphone found";
63const AUDIO_OFF_HINT: &str = "Audio is off for this meeting";
63pub const NO_CAMERA_HINT: &str = "No camera found";
64pub const NO_CAMERA_HINT: &str = "No camera found";
64pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";
65pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";
65pub const NO_WINDOWS_HINT: &str = "No windows found";
66pub const NO_WINDOWS_HINT: &str = "No windows found";
@@ -350,10 +351,15 @@ pub fn mute_button(
350 };
351 };
351 let button = round_control(id, glyph, background, foreground).size(px(size));
352 let button = round_control(id, glyph, background, foreground).size(px(size));
352 if !model.can_unmute() {
353 if !model.can_unmute() {
354 let hint = if model.audio_off {
355 AUDIO_OFF_HINT
356 } else {
357 NO_MICROPHONE_HINT
358 };
353 return button
359 return button
354 .opacity(DISABLED_OPACITY)
360 .opacity(DISABLED_OPACITY)
355 .cursor_default()
361 .cursor_default()
356 .tooltip(|window, cx| Tooltip::new(NO_MICROPHONE_HINT).build(window, cx));
362 .tooltip(move |window, cx| Tooltip::new(hint).build(window, cx));
357 }
363 }
358 let app = app.clone();
364 let app = app.clone();
359 button.on_click(move |_, _, cx| {
365 button.on_click(move |_, _, cx| {
@@ -824,6 +830,9 @@ fn devices_menu(
824 model: &CallModel,
830 model: &CallModel,
825 mic: MicSettings,
831 mic: MicSettings,
826) -> PopupMenu {
832) -> PopupMenu {
833 if model.audio_off {
834 return popup.item(PopupMenuItem::new(AUDIO_OFF_HINT).disabled(true));
835 }
827 let input_app = app.clone();
836 let input_app = app.clone();
828 let output_app = app.clone();
837 let output_app = app.clone();
829 let inputs = device_items(
838 let inputs = device_items(
crates/app/src/views/calls_tab.rs +107 −9
@@ -1,19 +1,21 @@
1 use chatsvc::{Reply, ResponseType};
1 2 use chrono::{Local, Offset, Utc};
2 3 use gpui_kit::assets::IconName;
3 4 use gpui_kit::component::Sizable as _;
4 5 use gpui_kit::component::button::{Button, ButtonVariants as _};
5 use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6 use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenuItem};
6 7 use gpui_kit::component::{h_flex, v_flex};
7 8 use gpui_kit::prelude::FluentBuilder as _;
8 9 use gpui_kit::*;
9 10
10 11 use super::avatar::person_avatar;
11 12 use super::join_dialog::open_join_with_id;
13 use super::new_meeting_dialog::open_new_meeting;
12 14 use super::widgets::icon;
13 15 use crate::app_state::AppState;
14 16 use crate::call::{
15 17 AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
16 SECTION_HEIGHT, join_available,
18 SECTION_HEIGHT, join_available, response_label,
17 19 };
18 20 use crate::theme;
19 21
@@ -172,9 +174,11 @@ fn join_button(id: &'static str, label: &'static str, primary: bool) -> Stateful
172 174
173 175 fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoElement {
174 176 let meet_state = state.clone();
177 let new_state = state.clone();
175 178 let id_state = state.clone();
176 179 let paste_state = state.clone();
177 180 h_flex()
181 .debug_selector(|| "shell/islands/sidebar/calls-actions".into())
178 182 .w_full()
179 183 .px(px(16.))
180 184 .pb(px(8.))
@@ -182,6 +186,7 @@ fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoEl
182 186 .flex_wrap()
183 187 .child(
184 188 join_button("meet-now", "Meet now", true)
189 .debug_selector(|| "shell/islands/sidebar/calls-actions/meet-now".into())
185 190 .when(meet_now_pending, |button| button.opacity(0.5))
186 191 .when(!meet_now_pending, |button| {
187 192 button.on_click(move |_, _, cx| {
@@ -189,6 +194,11 @@ fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoEl
189 194 })
190 195 }),
191 196 )
197 .child(
198 join_button("new-meeting", "New meeting", false)
199 .debug_selector(|| "shell/islands/sidebar/calls-actions/new-meeting".into())
200 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
201 )
192 202 .child(
193 203 join_button("join-with-id", "Join with ID", false)
194 204 .on_click(move |_, window, cx| open_join_with_id(id_state.clone(), window, cx)),
@@ -240,7 +250,84 @@ fn empty_row(text: &'static str) -> AnyElement {
240 250 .into_any_element()
241 251 }
242 252
243 fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyElement {
253 fn rsvp_menu_item(
254 state: &Entity<AppState>,
255 event_key: &str,
256 label: &'static str,
257 reply: Reply,
258 chosen: bool,
259 ) -> PopupMenuItem {
260 let state = state.clone();
261 let event_key = event_key.to_owned();
262 PopupMenuItem::new(label)
263 .checked(chosen)
264 .on_click(move |_, _, cx| {
265 state.update(cx, |state, cx| {
266 state.respond_to_event(&event_key, reply, cx)
267 });
268 })
269 }
270
271 fn rsvp_control(state: &Entity<AppState>, row: &AgendaRow, send_response: bool) -> AnyElement {
272 let menu_state = state.clone();
273 let key = row.key.clone();
274 let response = row.response;
275 div()
276 .id(SharedString::from(format!("agenda-rsvp-{}", row.key)))
277 .flex_none()
278 .on_click(|_, _, cx| cx.stop_propagation())
279 .child(
280 Button::new(SharedString::from(format!(
281 "agenda-rsvp-button-{}",
282 row.key
283 )))
284 .xsmall()
285 .outline()
286 .label(response_label(response))
287 .icon(IconName::ChevronDown)
288 .dropdown_menu(move |menu, _, _| {
289 let toggle_state = menu_state.clone();
290 menu.item(rsvp_menu_item(
291 &menu_state,
292 &key,
293 "Accept",
294 Reply::Accept,
295 response == ResponseType::Accepted,
296 ))
297 .item(rsvp_menu_item(
298 &menu_state,
299 &key,
300 "Tentative",
301 Reply::Tentative,
302 response == ResponseType::Tentative,
303 ))
304 .item(rsvp_menu_item(
305 &menu_state,
306 &key,
307 "Decline",
308 Reply::Decline,
309 response == ResponseType::Declined,
310 ))
311 .separator()
312 .item(
313 PopupMenuItem::new("Send a response")
314 .checked(send_response)
315 .on_click(move |_, _, cx| {
316 toggle_state
317 .update(cx, |state, cx| state.toggle_rsvp_send_response(cx));
318 }),
319 )
320 }),
321 )
322 .into_any_element()
323 }
324
325 fn agenda_row(
326 state: &Entity<AppState>,
327 row: &AgendaRow,
328 joinable: bool,
329 send_response: bool,
330 ) -> AnyElement {
244 331 let click_state = state.clone();
245 332 let click_row = row.clone();
246 333 let join_state = state.clone();
@@ -275,13 +362,23 @@ fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyE
275 362 .text_color(theme::text())
276 363 .child(row.subject.clone()),
277 364 )
278 .when(!row.detail.is_empty(), |column| {
365 .when(!row.detail.is_empty() || row.can_respond, |column| {
279 366 column.child(
280 div()
281 .truncate()
282 .text_size(px(12.5))
283 .text_color(theme::text_muted())
284 .child(row.detail.clone()),
367 h_flex()
368 .gap(px(6.))
369 .items_center()
370 .child(
371 div()
372 .flex_1()
373 .min_w_0()
374 .truncate()
375 .text_size(px(12.5))
376 .text_color(theme::text_muted())
377 .child(row.detail.clone()),
378 )
379 .when(row.can_respond, |line| {
380 line.child(rsvp_control(state, row, send_response))
381 }),
285 382 )
286 383 }),
287 384 )
@@ -340,6 +437,7 @@ pub fn calls_body(
340 437 state,
341 438 row,
342 439 join_available(row.start, row.end, now) && row.join_url.is_some(),
440 app.rsvp_send_response,
343 441 ),
344 442 ListEntry::Call(row) => call_row(
345 443 state,
@@ -1,19 +1,21 @@
1use chatsvc::{Reply, ResponseType};
1use chrono::{Local, Offset, Utc};
2use chrono::{Local, Offset, Utc};
2use gpui_kit::assets::IconName;
3use gpui_kit::assets::IconName;
3use gpui_kit::component::Sizable as _;
4use gpui_kit::component::Sizable as _;
4use gpui_kit::component::button::{Button, ButtonVariants as _};
5use gpui_kit::component::button::{Button, ButtonVariants as _};
5use gpui_kit::component::menu::{ContextMenuExt as _, PopupMenuItem};
6use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenuItem};
6use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::component::{h_flex, v_flex};
7use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::*;
9use gpui_kit::*;
9
10
10use super::avatar::person_avatar;
11use super::avatar::person_avatar;
11use super::join_dialog::open_join_with_id;
12use super::join_dialog::open_join_with_id;
13use super::new_meeting_dialog::open_new_meeting;
12use super::widgets::icon;
14use super::widgets::icon;
13use crate::app_state::AppState;
15use crate::app_state::AppState;
14use crate::call::{
16use crate::call::{
15 AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
17 AGENDA_ROW_HEIGHT, AgendaRow, CALL_ROW_HEIGHT, CallRow, DAY_HEIGHT, EMPTY_HEIGHT, ListEntry,
16 SECTION_HEIGHT, join_available,
18 SECTION_HEIGHT, join_available, response_label,
17};
19};
18use crate::theme;
20use crate::theme;
19
21
@@ -172,9 +174,11 @@ fn join_button(id: &'static str, label: &'static str, primary: bool) -> Stateful
172
174
173fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoElement {
175fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoElement {
174 let meet_state = state.clone();
176 let meet_state = state.clone();
177 let new_state = state.clone();
175 let id_state = state.clone();
178 let id_state = state.clone();
176 let paste_state = state.clone();
179 let paste_state = state.clone();
177 h_flex()
180 h_flex()
181 .debug_selector(|| "shell/islands/sidebar/calls-actions".into())
178 .w_full()
182 .w_full()
179 .px(px(16.))
183 .px(px(16.))
180 .pb(px(8.))
184 .pb(px(8.))
@@ -182,6 +186,7 @@ fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoEl
182 .flex_wrap()
186 .flex_wrap()
183 .child(
187 .child(
184 join_button("meet-now", "Meet now", true)
188 join_button("meet-now", "Meet now", true)
189 .debug_selector(|| "shell/islands/sidebar/calls-actions/meet-now".into())
185 .when(meet_now_pending, |button| button.opacity(0.5))
190 .when(meet_now_pending, |button| button.opacity(0.5))
186 .when(!meet_now_pending, |button| {
191 .when(!meet_now_pending, |button| {
187 button.on_click(move |_, _, cx| {
192 button.on_click(move |_, _, cx| {
@@ -189,6 +194,11 @@ fn join_buttons(state: &Entity<AppState>, meet_now_pending: bool) -> impl IntoEl
189 })
194 })
190 }),
195 }),
191 )
196 )
197 .child(
198 join_button("new-meeting", "New meeting", false)
199 .debug_selector(|| "shell/islands/sidebar/calls-actions/new-meeting".into())
200 .on_click(move |_, window, cx| open_new_meeting(new_state.clone(), window, cx)),
201 )
192 .child(
202 .child(
193 join_button("join-with-id", "Join with ID", false)
203 join_button("join-with-id", "Join with ID", false)
194 .on_click(move |_, window, cx| open_join_with_id(id_state.clone(), window, cx)),
204 .on_click(move |_, window, cx| open_join_with_id(id_state.clone(), window, cx)),
@@ -240,7 +250,84 @@ fn empty_row(text: &'static str) -> AnyElement {
240 .into_any_element()
250 .into_any_element()
241}
251}
242
252
243fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyElement {
253fn rsvp_menu_item(
254 state: &Entity<AppState>,
255 event_key: &str,
256 label: &'static str,
257 reply: Reply,
258 chosen: bool,
259) -> PopupMenuItem {
260 let state = state.clone();
261 let event_key = event_key.to_owned();
262 PopupMenuItem::new(label)
263 .checked(chosen)
264 .on_click(move |_, _, cx| {
265 state.update(cx, |state, cx| {
266 state.respond_to_event(&event_key, reply, cx)
267 });
268 })
269}
270
271fn rsvp_control(state: &Entity<AppState>, row: &AgendaRow, send_response: bool) -> AnyElement {
272 let menu_state = state.clone();
273 let key = row.key.clone();
274 let response = row.response;
275 div()
276 .id(SharedString::from(format!("agenda-rsvp-{}", row.key)))
277 .flex_none()
278 .on_click(|_, _, cx| cx.stop_propagation())
279 .child(
280 Button::new(SharedString::from(format!(
281 "agenda-rsvp-button-{}",
282 row.key
283 )))
284 .xsmall()
285 .outline()
286 .label(response_label(response))
287 .icon(IconName::ChevronDown)
288 .dropdown_menu(move |menu, _, _| {
289 let toggle_state = menu_state.clone();
290 menu.item(rsvp_menu_item(
291 &menu_state,
292 &key,
293 "Accept",
294 Reply::Accept,
295 response == ResponseType::Accepted,
296 ))
297 .item(rsvp_menu_item(
298 &menu_state,
299 &key,
300 "Tentative",
301 Reply::Tentative,
302 response == ResponseType::Tentative,
303 ))
304 .item(rsvp_menu_item(
305 &menu_state,
306 &key,
307 "Decline",
308 Reply::Decline,
309 response == ResponseType::Declined,
310 ))
311 .separator()
312 .item(
313 PopupMenuItem::new("Send a response")
314 .checked(send_response)
315 .on_click(move |_, _, cx| {
316 toggle_state
317 .update(cx, |state, cx| state.toggle_rsvp_send_response(cx));
318 }),
319 )
320 }),
321 )
322 .into_any_element()
323}
324
325fn agenda_row(
326 state: &Entity<AppState>,
327 row: &AgendaRow,
328 joinable: bool,
329 send_response: bool,
330) -> AnyElement {
244 let click_state = state.clone();
331 let click_state = state.clone();
245 let click_row = row.clone();
332 let click_row = row.clone();
246 let join_state = state.clone();
333 let join_state = state.clone();
@@ -275,13 +362,23 @@ fn agenda_row(state: &Entity<AppState>, row: &AgendaRow, joinable: bool) -> AnyE
275 .text_color(theme::text())
362 .text_color(theme::text())
276 .child(row.subject.clone()),
363 .child(row.subject.clone()),
277 )
364 )
278 .when(!row.detail.is_empty(), |column| {
365 .when(!row.detail.is_empty() || row.can_respond, |column| {
279 column.child(
366 column.child(
280 div()
367 h_flex()
281 .truncate()
368 .gap(px(6.))
282 .text_size(px(12.5))
369 .items_center()
283 .text_color(theme::text_muted())
370 .child(
284 .child(row.detail.clone()),
371 div()
372 .flex_1()
373 .min_w_0()
374 .truncate()
375 .text_size(px(12.5))
376 .text_color(theme::text_muted())
377 .child(row.detail.clone()),
378 )
379 .when(row.can_respond, |line| {
380 line.child(rsvp_control(state, row, send_response))
381 }),
285 )
382 )
286 }),
383 }),
287 )
384 )
@@ -340,6 +437,7 @@ pub fn calls_body(
340 state,
437 state,
341 row,
438 row,
342 join_available(row.start, row.end, now) && row.join_url.is_some(),
439 join_available(row.start, row.end, now) && row.join_url.is_some(),
440 app.rsvp_send_response,
343 ),
441 ),
344 ListEntry::Call(row) => call_row(
442 ListEntry::Call(row) => call_row(
345 state,
443 state,
crates/app/src/views/conversation.rs +1 −0
@@ -624,6 +624,7 @@ impl ConversationView {
624 624 | AppEvent::CallHistory
625 625 | AppEvent::Ring
626 626 | AppEvent::MissedCall(_)
627 | AppEvent::MeetingReminder
627 628 | AppEvent::Call => {}
628 629 AppEvent::LiveMeeting => cx.notify(),
629 630 AppEvent::Saved => cx.notify(),
@@ -624,6 +624,7 @@ impl ConversationView {
624 | AppEvent::CallHistory
624 | AppEvent::CallHistory
625 | AppEvent::Ring
625 | AppEvent::Ring
626 | AppEvent::MissedCall(_)
626 | AppEvent::MissedCall(_)
627 | AppEvent::MeetingReminder
627 | AppEvent::Call => {}
628 | AppEvent::Call => {}
628 AppEvent::LiveMeeting => cx.notify(),
629 AppEvent::LiveMeeting => cx.notify(),
629 AppEvent::Saved => cx.notify(),
630 AppEvent::Saved => cx.notify(),
crates/app/src/views/mod.rs +2 −0
@@ -37,8 +37,10 @@ pub mod link_preview;
37 37 pub mod message_actions;
38 38 pub mod message_row;
39 39 pub mod new_chat;
40 pub mod new_meeting_dialog;
40 41 pub mod pin_banner;
41 42 pub mod post_card;
43 pub mod prejoin_view;
42 44 pub mod profile_card;
43 45 pub mod proposal_card;
44 46 pub mod rail;
@@ -37,8 +37,10 @@ pub mod link_preview;
37pub mod message_actions;
37pub mod message_actions;
38pub mod message_row;
38pub mod message_row;
39pub mod new_chat;
39pub mod new_chat;
40pub mod new_meeting_dialog;
40pub mod pin_banner;
41pub mod pin_banner;
41pub mod post_card;
42pub mod post_card;
43pub mod prejoin_view;
42pub mod profile_card;
44pub mod profile_card;
43pub mod proposal_card;
45pub mod proposal_card;
44pub mod rail;
46pub mod rail;
crates/app/src/views/new_chat.rs +68 −41
@@ -26,6 +26,8 @@ const RESULT_LIMIT: usize = 8;
26 26 const POPUP_WIDTH: f32 = 300.;
27 27 const POPUP_ROW_HEIGHT: f32 = 44.;
28 28 const CHIP_NAME_MAX_WIDTH: f32 = 180.;
29 const FIELD_MIN_HEIGHT: f32 = 36.;
30 const FIELD_PADDING: f32 = 8.;
29 31 const DEFAULT_PLACEHOLDER: &str = "Type a message";
30 32
31 33 #[derive(Debug, Clone, PartialEq, Eq)]
@@ -182,6 +184,7 @@ pub struct NewChatDraft {
182 184 query: Entity<InputState>,
183 185 name: Entity<InputState>,
184 186 chips: Vec<Pick>,
187 form_field: bool,
185 188 remote: Vec<Pick>,
186 189 highlighted: usize,
187 190 popup_open: bool,
@@ -207,6 +210,7 @@ impl NewChatDraft {
207 210 query,
208 211 name,
209 212 chips: Vec::new(),
213 form_field: false,
210 214 remote: Vec::new(),
211 215 highlighted: 0,
212 216 popup_open: true,
@@ -218,6 +222,12 @@ impl NewChatDraft {
218 222 }
219 223 }
220 224
225 pub fn compact(mut self) -> Self {
226 self.form_field = true;
227 self.popup_open = false;
228 self
229 }
230
221 231 pub fn chips(&self) -> &[Pick] {
222 232 &self.chips
223 233 }
@@ -407,7 +417,7 @@ impl NewChatDraft {
407 417 );
408 418 match (action, highlighted) {
409 419 (EnterAction::Add, Some(pick)) => self.add(pick, window, cx),
410 (EnterAction::Advance, _) if self.chips.len() >= 2 => {
420 (EnterAction::Advance, _) if self.chips.len() >= 2 && !self.form_field => {
411 421 self.popup_open = false;
412 422 self.name.update(cx, |input, cx| input.focus(window, cx));
413 423 cx.notify();
@@ -538,46 +548,50 @@ impl NewChatDraft {
538 548 .child(text)
539 549 };
540 550 let results_empty = self.results(cx).is_empty();
551 let panel = v_flex()
552 .id("new-chat-popup")
553 .mt(px(4.))
554 .p(px(6.))
555 .rounded(px(10.))
556 .bg(theme::popup())
557 .occlude()
558 .when(!results_empty, |popup| {
559 popup.child(
560 div()
561 .px(px(6.))
562 .pb(px(4.))
563 .text_size(px(11.))
564 .font_weight(FontWeight::SEMIBOLD)
565 .text_color(theme::text_muted())
566 .child(label),
567 )
568 })
569 .children(rows)
570 .when(self.search_failed, |popup| {
571 popup.child(note("Search failed".to_owned(), theme::red_soft()))
572 })
573 .when(self.searching && results_empty, |popup| {
574 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
575 })
576 .when(
577 !self.searching && !self.search_failed && results_empty,
578 |popup| {
579 popup.child(note(
580 format!("No people found for \"{query}\""),
581 theme::text_muted(),
582 ))
583 },
584 );
585 if self.form_field {
586 return Some(panel.w_full().into_any_element());
587 }
541 588 Some(
542 589 deferred(
543 v_flex()
544 .id("new-chat-popup")
590 panel
545 591 .absolute()
546 592 .top(relative(1.))
547 593 .left(px(20.))
548 .mt(px(4.))
549 .w(px(POPUP_WIDTH))
550 .p(px(6.))
551 .rounded(px(10.))
552 .bg(theme::popup())
553 .occlude()
554 .when(!results_empty, |popup| {
555 popup.child(
556 div()
557 .px(px(6.))
558 .pb(px(4.))
559 .text_size(px(11.))
560 .font_weight(FontWeight::SEMIBOLD)
561 .text_color(theme::text_muted())
562 .child(label),
563 )
564 })
565 .children(rows)
566 .when(self.search_failed, |popup| {
567 popup.child(note("Search failed".to_owned(), theme::red_soft()))
568 })
569 .when(self.searching && results_empty, |popup| {
570 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
571 })
572 .when(
573 !self.searching && !self.search_failed && results_empty,
574 |popup| {
575 popup.child(note(
576 format!("No people found for \"{query}\""),
577 theme::text_muted(),
578 ))
579 },
580 ),
594 .w(px(POPUP_WIDTH)),
581 595 )
582 596 .with_priority(1)
583 597 .into_any_element(),
@@ -594,10 +608,14 @@ impl NewChatDraft {
594 608 h_flex()
595 609 .relative()
596 610 .w_full()
597 .min_h(px(60.))
611 .min_h(px(if self.form_field {
612 FIELD_MIN_HEIGHT
613 } else {
614 60.
615 }))
598 616 .flex_none()
599 .px(px(20.))
600 .py(px(8.))
617 .px(px(if self.form_field { FIELD_PADDING } else { 20. }))
618 .py(px(if self.form_field { 4. } else { 8. }))
601 619 .gap(px(8.))
602 620 .flex_wrap()
603 621 .items_center()
@@ -614,11 +632,15 @@ impl NewChatDraft {
614 632 .min_w(px(160.))
615 633 .child(Input::new(&self.query).appearance(false).bordered(false)),
616 634 )
617 .children(self.render_popup(cx))
635 .children(if self.form_field {
636 None
637 } else {
638 self.render_popup(cx)
639 })
618 640 }
619 641
620 642 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
621 if self.chips.len() < 2 {
643 if self.chips.len() < 2 || self.form_field {
622 644 return None;
623 645 }
624 646 let focused = self.name.focus_handle(cx).is_focused(window);
@@ -755,6 +777,11 @@ impl Render for NewChatDraft {
755 777 }
756 778 }))
757 779 .child(self.render_bar(cx))
780 .children(if self.form_field {
781 self.render_popup(cx)
782 } else {
783 None
784 })
758 785 .children(self.render_name_row(window, cx))
759 786 }
760 787 }
@@ -26,6 +26,8 @@ const RESULT_LIMIT: usize = 8;
26const POPUP_WIDTH: f32 = 300.;
26const POPUP_WIDTH: f32 = 300.;
27const POPUP_ROW_HEIGHT: f32 = 44.;
27const POPUP_ROW_HEIGHT: f32 = 44.;
28const CHIP_NAME_MAX_WIDTH: f32 = 180.;
28const CHIP_NAME_MAX_WIDTH: f32 = 180.;
29const FIELD_MIN_HEIGHT: f32 = 36.;
30const FIELD_PADDING: f32 = 8.;
29const DEFAULT_PLACEHOLDER: &str = "Type a message";
31const DEFAULT_PLACEHOLDER: &str = "Type a message";
30
32
31#[derive(Debug, Clone, PartialEq, Eq)]
33#[derive(Debug, Clone, PartialEq, Eq)]
@@ -182,6 +184,7 @@ pub struct NewChatDraft {
182 query: Entity<InputState>,
184 query: Entity<InputState>,
183 name: Entity<InputState>,
185 name: Entity<InputState>,
184 chips: Vec<Pick>,
186 chips: Vec<Pick>,
187 form_field: bool,
185 remote: Vec<Pick>,
188 remote: Vec<Pick>,
186 highlighted: usize,
189 highlighted: usize,
187 popup_open: bool,
190 popup_open: bool,
@@ -207,6 +210,7 @@ impl NewChatDraft {
207 query,
210 query,
208 name,
211 name,
209 chips: Vec::new(),
212 chips: Vec::new(),
213 form_field: false,
210 remote: Vec::new(),
214 remote: Vec::new(),
211 highlighted: 0,
215 highlighted: 0,
212 popup_open: true,
216 popup_open: true,
@@ -218,6 +222,12 @@ impl NewChatDraft {
218 }
222 }
219 }
223 }
220
224
225 pub fn compact(mut self) -> Self {
226 self.form_field = true;
227 self.popup_open = false;
228 self
229 }
230
221 pub fn chips(&self) -> &[Pick] {
231 pub fn chips(&self) -> &[Pick] {
222 &self.chips
232 &self.chips
223 }
233 }
@@ -407,7 +417,7 @@ impl NewChatDraft {
407 );
417 );
408 match (action, highlighted) {
418 match (action, highlighted) {
409 (EnterAction::Add, Some(pick)) => self.add(pick, window, cx),
419 (EnterAction::Add, Some(pick)) => self.add(pick, window, cx),
410 (EnterAction::Advance, _) if self.chips.len() >= 2 => {
420 (EnterAction::Advance, _) if self.chips.len() >= 2 && !self.form_field => {
411 self.popup_open = false;
421 self.popup_open = false;
412 self.name.update(cx, |input, cx| input.focus(window, cx));
422 self.name.update(cx, |input, cx| input.focus(window, cx));
413 cx.notify();
423 cx.notify();
@@ -538,46 +548,50 @@ impl NewChatDraft {
538 .child(text)
548 .child(text)
539 };
549 };
540 let results_empty = self.results(cx).is_empty();
550 let results_empty = self.results(cx).is_empty();
551 let panel = v_flex()
552 .id("new-chat-popup")
553 .mt(px(4.))
554 .p(px(6.))
555 .rounded(px(10.))
556 .bg(theme::popup())
557 .occlude()
558 .when(!results_empty, |popup| {
559 popup.child(
560 div()
561 .px(px(6.))
562 .pb(px(4.))
563 .text_size(px(11.))
564 .font_weight(FontWeight::SEMIBOLD)
565 .text_color(theme::text_muted())
566 .child(label),
567 )
568 })
569 .children(rows)
570 .when(self.search_failed, |popup| {
571 popup.child(note("Search failed".to_owned(), theme::red_soft()))
572 })
573 .when(self.searching && results_empty, |popup| {
574 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
575 })
576 .when(
577 !self.searching && !self.search_failed && results_empty,
578 |popup| {
579 popup.child(note(
580 format!("No people found for \"{query}\""),
581 theme::text_muted(),
582 ))
583 },
584 );
585 if self.form_field {
586 return Some(panel.w_full().into_any_element());
587 }
541 Some(
588 Some(
542 deferred(
589 deferred(
543 v_flex()
590 panel
544 .id("new-chat-popup")
545 .absolute()
591 .absolute()
546 .top(relative(1.))
592 .top(relative(1.))
547 .left(px(20.))
593 .left(px(20.))
548 .mt(px(4.))
594 .w(px(POPUP_WIDTH)),
549 .w(px(POPUP_WIDTH))
550 .p(px(6.))
551 .rounded(px(10.))
552 .bg(theme::popup())
553 .occlude()
554 .when(!results_empty, |popup| {
555 popup.child(
556 div()
557 .px(px(6.))
558 .pb(px(4.))
559 .text_size(px(11.))
560 .font_weight(FontWeight::SEMIBOLD)
561 .text_color(theme::text_muted())
562 .child(label),
563 )
564 })
565 .children(rows)
566 .when(self.search_failed, |popup| {
567 popup.child(note("Search failed".to_owned(), theme::red_soft()))
568 })
569 .when(self.searching && results_empty, |popup| {
570 popup.child(note("Searching ...".to_owned(), theme::text_muted()))
571 })
572 .when(
573 !self.searching && !self.search_failed && results_empty,
574 |popup| {
575 popup.child(note(
576 format!("No people found for \"{query}\""),
577 theme::text_muted(),
578 ))
579 },
580 ),
581 )
595 )
582 .with_priority(1)
596 .with_priority(1)
583 .into_any_element(),
597 .into_any_element(),
@@ -594,10 +608,14 @@ impl NewChatDraft {
594 h_flex()
608 h_flex()
595 .relative()
609 .relative()
596 .w_full()
610 .w_full()
597 .min_h(px(60.))
611 .min_h(px(if self.form_field {
612 FIELD_MIN_HEIGHT
613 } else {
614 60.
615 }))
598 .flex_none()
616 .flex_none()
599 .px(px(20.))
617 .px(px(if self.form_field { FIELD_PADDING } else { 20. }))
600 .py(px(8.))
618 .py(px(if self.form_field { 4. } else { 8. }))
601 .gap(px(8.))
619 .gap(px(8.))
602 .flex_wrap()
620 .flex_wrap()
603 .items_center()
621 .items_center()
@@ -614,11 +632,15 @@ impl NewChatDraft {
614 .min_w(px(160.))
632 .min_w(px(160.))
615 .child(Input::new(&self.query).appearance(false).bordered(false)),
633 .child(Input::new(&self.query).appearance(false).bordered(false)),
616 )
634 )
617 .children(self.render_popup(cx))
635 .children(if self.form_field {
636 None
637 } else {
638 self.render_popup(cx)
639 })
618 }
640 }
619
641
620 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
642 fn render_name_row(&self, window: &Window, cx: &App) -> Option<impl IntoElement> {
621 if self.chips.len() < 2 {
643 if self.chips.len() < 2 || self.form_field {
622 return None;
644 return None;
623 }
645 }
624 let focused = self.name.focus_handle(cx).is_focused(window);
646 let focused = self.name.focus_handle(cx).is_focused(window);
@@ -755,6 +777,11 @@ impl Render for NewChatDraft {
755 }
777 }
756 }))
778 }))
757 .child(self.render_bar(cx))
779 .child(self.render_bar(cx))
780 .children(if self.form_field {
781 self.render_popup(cx)
782 } else {
783 None
784 })
758 .children(self.render_name_row(window, cx))
785 .children(self.render_name_row(window, cx))
759 }
786 }
760}
787}
crates/app/src/views/new_meeting_dialog.rs added +263 −0
@@ -0,0 +1,263 @@
1 use chatsvc::Repeat;
2 use chrono::{Local, Utc};
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::button::{Button, ButtonVariants as _};
5 use gpui_kit::component::date_picker::DatePicker;
6 use gpui_kit::component::date_picker::DatePickerState;
7 use gpui_kit::component::dialog::{Dialog, DialogFooter};
8 use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
9 use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
10 use gpui_kit::component::time_field::{TimeField, TimeFieldState};
11 use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12 use gpui_kit::prelude::FluentBuilder as _;
13 use gpui_kit::*;
14
15 use super::new_chat::NewChatDraft;
16 use super::widgets::icon;
17 use crate::app_state::AppState;
18 use crate::call::{FormValues, Invitee, default_window, draft_from_form};
19 use crate::theme;
20
21 const DIALOG_WIDTH: f32 = 520.;
22 const FIELD_GAP: f32 = 12.;
23 const LABEL_SIZE: f32 = 12.;
24 const TITLE: &str = "New meeting";
25 const DATE_FORMAT: &str = "%a, %b %-d, %Y";
26 const DETAILS_MIN_ROWS: usize = 3;
27 const DETAILS_MAX_ROWS: usize = 6;
28 const TIME_FIELD_WIDTH: f32 = 96.;
29 const DATE_FIELD_WIDTH: f32 = 176.;
30 const REPEAT_WIDTH: f32 = 180.;
31
32 struct MeetingForm {
33 state: Entity<AppState>,
34 title: Entity<InputState>,
35 people: Entity<NewChatDraft>,
36 date: Entity<DatePickerState>,
37 start: Entity<TimeFieldState>,
38 end: Entity<TimeFieldState>,
39 details: Entity<TextareaState>,
40 repeat: Repeat,
41 error: Option<String>,
42 sending: bool,
43 }
44
45 impl MeetingForm {
46 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
47 let (start_moment, end_moment) = default_window(Utc::now(), &Local);
48 let title = cx.new(|cx| InputState::new(window, cx).placeholder("Add a title"));
49 let people_state = state.clone();
50 let people = cx.new(|cx| NewChatDraft::new(people_state, window, cx).compact());
51 let date = cx.new(|cx| {
52 let mut picker = DatePickerState::new(window, cx).date_format(DATE_FORMAT);
53 picker.set_date(start_moment.date(), window, cx);
54 picker
55 });
56 let start = cx.new(|cx| {
57 let mut field = TimeFieldState::new(window, cx);
58 field.set_time(start_moment.time(), window, cx);
59 field
60 });
61 let end = cx.new(|cx| {
62 let mut field = TimeFieldState::new(window, cx);
63 field.set_time(end_moment.time(), window, cx);
64 field
65 });
66 let details = cx.new(|cx| {
67 TextareaState::new(window, cx)
68 .auto_grow(DETAILS_MIN_ROWS, DETAILS_MAX_ROWS)
69 .placeholder("Add details")
70 });
71 MeetingForm {
72 state,
73 title,
74 people,
75 date,
76 start,
77 end,
78 details,
79 repeat: Repeat::Never,
80 error: None,
81 sending: false,
82 }
83 }
84
85 fn set_repeat(&mut self, repeat: Repeat, cx: &mut Context<Self>) {
86 self.repeat = repeat;
87 cx.notify();
88 }
89
90 fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
91 if self.sending {
92 return;
93 }
94 let people = self
95 .people
96 .read(cx)
97 .chips()
98 .iter()
99 .map(|pick| Invitee {
100 user_id: pick.user_id.clone(),
101 name: pick.name.clone(),
102 mail: pick.mail.clone(),
103 })
104 .collect();
105 let values = FormValues {
106 subject: self.title.read(cx).value().to_string(),
107 date: self.date.read(cx).date().start(),
108 start: self.start.read(cx).time(),
109 end: self.end.read(cx).time(),
110 repeat: self.repeat,
111 details: self.details.read(cx).value().to_string(),
112 people,
113 };
114 let draft = match draft_from_form(values, &Local) {
115 Ok(draft) => draft,
116 Err(message) => {
117 self.error = Some(message);
118 cx.notify();
119 return;
120 }
121 };
122 self.error = None;
123 self.sending = true;
124 let created = self
125 .state
126 .update(cx, |state, cx| state.create_meeting(draft, cx));
127 cx.notify();
128 cx.spawn_in(window, async move |this, cx| {
129 let outcome = created
130 .await
131 .unwrap_or_else(|_| Err("The request was cancelled.".to_owned()));
132 this.update_in(cx, |form, window, cx| match outcome {
133 Ok(()) => window.close_dialog(cx),
134 Err(message) => {
135 form.sending = false;
136 form.error = Some(message);
137 cx.notify();
138 }
139 })
140 .ok();
141 })
142 .detach();
143 }
144 }
145
146 fn labeled(label: &str, field: impl IntoElement) -> Div {
147 v_flex()
148 .gap(px(4.))
149 .child(
150 div()
151 .text_size(px(LABEL_SIZE))
152 .text_color(theme::text_muted())
153 .child(label.to_owned()),
154 )
155 .child(field)
156 }
157
158 impl Render for MeetingForm {
159 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
160 let form = cx.entity();
161 let current = self.repeat;
162 let repeat_button = Button::new("meeting-repeat")
163 .outline()
164 .w(px(REPEAT_WIDTH))
165 .label(current.label())
166 .icon(IconName::ChevronDown)
167 .dropdown_menu(move |menu, _, _| {
168 Repeat::ALL.into_iter().fold(menu, |menu, repeat| {
169 let form = form.clone();
170 menu.item(
171 PopupMenuItem::new(repeat.label())
172 .checked(repeat == current)
173 .on_click(move |_, _, cx| {
174 form.update(cx, |form, cx| form.set_repeat(repeat, cx))
175 }),
176 )
177 })
178 });
179 v_flex()
180 .debug_selector(|| "new-meeting".into())
181 .gap(px(FIELD_GAP))
182 .child(labeled("Title", Input::new(&self.title)))
183 .child(labeled(
184 "People",
185 div()
186 .debug_selector(|| "new-meeting/people".into())
187 .rounded(px(6.))
188 .border_1()
189 .border_color(theme::border())
190 .child(self.people.clone()),
191 ))
192 .child(
193 h_flex()
194 .debug_selector(|| "new-meeting/when".into())
195 .gap(px(8.))
196 .items_end()
197 .child(div().w(px(DATE_FIELD_WIDTH)).child(labeled(
198 "Date",
199 DatePicker::new(&self.date).cleanable(false),
200 )))
201 .child(
202 div()
203 .w(px(TIME_FIELD_WIDTH))
204 .child(labeled("Start", TimeField::new(&self.start))),
205 )
206 .child(
207 div()
208 .w(px(TIME_FIELD_WIDTH))
209 .child(labeled("End", TimeField::new(&self.end))),
210 ),
211 )
212 .child(labeled("Repeat", repeat_button))
213 .child(labeled("Details", Textarea::new(&self.details)))
214 .child(
215 h_flex()
216 .gap(px(6.))
217 .items_center()
218 .text_size(px(LABEL_SIZE))
219 .text_color(theme::text_muted())
220 .child(icon(IconName::Video, 14., theme::text_muted()))
221 .child("Teams meeting link is added"),
222 )
223 .when_some(self.error.clone(), |form, error| {
224 form.child(
225 div()
226 .text_size(px(LABEL_SIZE))
227 .text_color(theme::red_soft())
228 .child(error),
229 )
230 })
231 }
232 }
233
234 pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
235 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
236 let first_field = form.read(cx).title.clone();
237 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
238 let submit_form = form.clone();
239 let sending = form.read(cx).sending;
240 let footer = DialogFooter::new()
241 .child(
242 Button::new("meeting-cancel")
243 .label("Cancel")
244 .on_click(|_, window, cx| window.close_dialog(cx)),
245 )
246 .child(
247 Button::new("meeting-send")
248 .primary()
249 .label(if sending { "Sending..." } else { "Send" })
250 .on_click(move |_, window, cx| {
251 submit_form.update(cx, |form, cx| form.submit(window, cx));
252 }),
253 );
254 dialog
255 .title(TITLE)
256 .w(px(DIALOG_WIDTH))
257 .child(form.clone())
258 .footer(footer)
259 });
260 window.defer(cx, move |window, cx| {
261 first_field.update(cx, |input, cx| input.focus(window, cx));
262 });
263 }
@@ -0,0 +1,263 @@
1use chatsvc::Repeat;
2use chrono::{Local, Utc};
3use gpui_kit::assets::IconName;
4use gpui_kit::component::button::{Button, ButtonVariants as _};
5use gpui_kit::component::date_picker::DatePicker;
6use gpui_kit::component::date_picker::DatePickerState;
7use gpui_kit::component::dialog::{Dialog, DialogFooter};
8use gpui_kit::component::input::{Input, InputState, Textarea, TextareaState};
9use gpui_kit::component::menu::{DropdownMenu as _, PopupMenuItem};
10use gpui_kit::component::time_field::{TimeField, TimeFieldState};
11use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14
15use super::new_chat::NewChatDraft;
16use super::widgets::icon;
17use crate::app_state::AppState;
18use crate::call::{FormValues, Invitee, default_window, draft_from_form};
19use crate::theme;
20
21const DIALOG_WIDTH: f32 = 520.;
22const FIELD_GAP: f32 = 12.;
23const LABEL_SIZE: f32 = 12.;
24const TITLE: &str = "New meeting";
25const DATE_FORMAT: &str = "%a, %b %-d, %Y";
26const DETAILS_MIN_ROWS: usize = 3;
27const DETAILS_MAX_ROWS: usize = 6;
28const TIME_FIELD_WIDTH: f32 = 96.;
29const DATE_FIELD_WIDTH: f32 = 176.;
30const REPEAT_WIDTH: f32 = 180.;
31
32struct MeetingForm {
33 state: Entity<AppState>,
34 title: Entity<InputState>,
35 people: Entity<NewChatDraft>,
36 date: Entity<DatePickerState>,
37 start: Entity<TimeFieldState>,
38 end: Entity<TimeFieldState>,
39 details: Entity<TextareaState>,
40 repeat: Repeat,
41 error: Option<String>,
42 sending: bool,
43}
44
45impl MeetingForm {
46 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
47 let (start_moment, end_moment) = default_window(Utc::now(), &Local);
48 let title = cx.new(|cx| InputState::new(window, cx).placeholder("Add a title"));
49 let people_state = state.clone();
50 let people = cx.new(|cx| NewChatDraft::new(people_state, window, cx).compact());
51 let date = cx.new(|cx| {
52 let mut picker = DatePickerState::new(window, cx).date_format(DATE_FORMAT);
53 picker.set_date(start_moment.date(), window, cx);
54 picker
55 });
56 let start = cx.new(|cx| {
57 let mut field = TimeFieldState::new(window, cx);
58 field.set_time(start_moment.time(), window, cx);
59 field
60 });
61 let end = cx.new(|cx| {
62 let mut field = TimeFieldState::new(window, cx);
63 field.set_time(end_moment.time(), window, cx);
64 field
65 });
66 let details = cx.new(|cx| {
67 TextareaState::new(window, cx)
68 .auto_grow(DETAILS_MIN_ROWS, DETAILS_MAX_ROWS)
69 .placeholder("Add details")
70 });
71 MeetingForm {
72 state,
73 title,
74 people,
75 date,
76 start,
77 end,
78 details,
79 repeat: Repeat::Never,
80 error: None,
81 sending: false,
82 }
83 }
84
85 fn set_repeat(&mut self, repeat: Repeat, cx: &mut Context<Self>) {
86 self.repeat = repeat;
87 cx.notify();
88 }
89
90 fn submit(&mut self, window: &mut Window, cx: &mut Context<Self>) {
91 if self.sending {
92 return;
93 }
94 let people = self
95 .people
96 .read(cx)
97 .chips()
98 .iter()
99 .map(|pick| Invitee {
100 user_id: pick.user_id.clone(),
101 name: pick.name.clone(),
102 mail: pick.mail.clone(),
103 })
104 .collect();
105 let values = FormValues {
106 subject: self.title.read(cx).value().to_string(),
107 date: self.date.read(cx).date().start(),
108 start: self.start.read(cx).time(),
109 end: self.end.read(cx).time(),
110 repeat: self.repeat,
111 details: self.details.read(cx).value().to_string(),
112 people,
113 };
114 let draft = match draft_from_form(values, &Local) {
115 Ok(draft) => draft,
116 Err(message) => {
117 self.error = Some(message);
118 cx.notify();
119 return;
120 }
121 };
122 self.error = None;
123 self.sending = true;
124 let created = self
125 .state
126 .update(cx, |state, cx| state.create_meeting(draft, cx));
127 cx.notify();
128 cx.spawn_in(window, async move |this, cx| {
129 let outcome = created
130 .await
131 .unwrap_or_else(|_| Err("The request was cancelled.".to_owned()));
132 this.update_in(cx, |form, window, cx| match outcome {
133 Ok(()) => window.close_dialog(cx),
134 Err(message) => {
135 form.sending = false;
136 form.error = Some(message);
137 cx.notify();
138 }
139 })
140 .ok();
141 })
142 .detach();
143 }
144}
145
146fn labeled(label: &str, field: impl IntoElement) -> Div {
147 v_flex()
148 .gap(px(4.))
149 .child(
150 div()
151 .text_size(px(LABEL_SIZE))
152 .text_color(theme::text_muted())
153 .child(label.to_owned()),
154 )
155 .child(field)
156}
157
158impl Render for MeetingForm {
159 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
160 let form = cx.entity();
161 let current = self.repeat;
162 let repeat_button = Button::new("meeting-repeat")
163 .outline()
164 .w(px(REPEAT_WIDTH))
165 .label(current.label())
166 .icon(IconName::ChevronDown)
167 .dropdown_menu(move |menu, _, _| {
168 Repeat::ALL.into_iter().fold(menu, |menu, repeat| {
169 let form = form.clone();
170 menu.item(
171 PopupMenuItem::new(repeat.label())
172 .checked(repeat == current)
173 .on_click(move |_, _, cx| {
174 form.update(cx, |form, cx| form.set_repeat(repeat, cx))
175 }),
176 )
177 })
178 });
179 v_flex()
180 .debug_selector(|| "new-meeting".into())
181 .gap(px(FIELD_GAP))
182 .child(labeled("Title", Input::new(&self.title)))
183 .child(labeled(
184 "People",
185 div()
186 .debug_selector(|| "new-meeting/people".into())
187 .rounded(px(6.))
188 .border_1()
189 .border_color(theme::border())
190 .child(self.people.clone()),
191 ))
192 .child(
193 h_flex()
194 .debug_selector(|| "new-meeting/when".into())
195 .gap(px(8.))
196 .items_end()
197 .child(div().w(px(DATE_FIELD_WIDTH)).child(labeled(
198 "Date",
199 DatePicker::new(&self.date).cleanable(false),
200 )))
201 .child(
202 div()
203 .w(px(TIME_FIELD_WIDTH))
204 .child(labeled("Start", TimeField::new(&self.start))),
205 )
206 .child(
207 div()
208 .w(px(TIME_FIELD_WIDTH))
209 .child(labeled("End", TimeField::new(&self.end))),
210 ),
211 )
212 .child(labeled("Repeat", repeat_button))
213 .child(labeled("Details", Textarea::new(&self.details)))
214 .child(
215 h_flex()
216 .gap(px(6.))
217 .items_center()
218 .text_size(px(LABEL_SIZE))
219 .text_color(theme::text_muted())
220 .child(icon(IconName::Video, 14., theme::text_muted()))
221 .child("Teams meeting link is added"),
222 )
223 .when_some(self.error.clone(), |form, error| {
224 form.child(
225 div()
226 .text_size(px(LABEL_SIZE))
227 .text_color(theme::red_soft())
228 .child(error),
229 )
230 })
231 }
232}
233
234pub fn open_new_meeting(state: Entity<AppState>, window: &mut Window, cx: &mut App) {
235 let form = cx.new(|cx| MeetingForm::new(state, window, cx));
236 let first_field = form.read(cx).title.clone();
237 window.open_dialog(cx, move |dialog: Dialog, _, cx| {
238 let submit_form = form.clone();
239 let sending = form.read(cx).sending;
240 let footer = DialogFooter::new()
241 .child(
242 Button::new("meeting-cancel")
243 .label("Cancel")
244 .on_click(|_, window, cx| window.close_dialog(cx)),
245 )
246 .child(
247 Button::new("meeting-send")
248 .primary()
249 .label(if sending { "Sending..." } else { "Send" })
250 .on_click(move |_, window, cx| {
251 submit_form.update(cx, |form, cx| form.submit(window, cx));
252 }),
253 );
254 dialog
255 .title(TITLE)
256 .w(px(DIALOG_WIDTH))
257 .child(form.clone())
258 .footer(footer)
259 });
260 window.defer(cx, move |window, cx| {
261 first_field.update(cx, |input, cx| input.focus(window, cx));
262 });
263}
crates/app/src/views/prejoin_view.rs added +567 −0
@@ -0,0 +1,567 @@
1 use std::time::{Duration, Instant};
2
3 use calling::camera::list_cameras;
4 use calling::devices::{AudioDevice, DeviceLists, list_devices, shared_factory};
5 use calling::{DeviceChoice, DeviceEntry, camera_entries};
6 use gpui_kit::assets::IconName;
7 use gpui_kit::component::Disableable as _;
8 use gpui_kit::component::button::{Button, ButtonVariants as _};
9 use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu};
10 use gpui_kit::component::{h_flex, v_flex};
11 use gpui_kit::prelude::FluentBuilder as _;
12 use gpui_kit::*;
13
14 use super::avatar::person_avatar;
15 use super::call_extras::{CameraMenu, background_items};
16 use super::call_view::{device_items, round_control};
17 use crate::app_state::AppState;
18 use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
19 use crate::theme;
20
21 const CONTENT_WIDTH: f32 = 560.;
22 const PREVIEW_HEIGHT: f32 = 315.;
23 const PREVIEW_RADIUS: f32 = 12.;
24 const AVATAR_SIZE: f32 = 96.;
25 const SELECT_WIDTH: f32 = 176.;
26 const SECTION_GAP: f32 = 12.;
27 const PANE_PADDING: f32 = 12.;
28 const PREVIEW_MIN_HEIGHT: f32 = 60.;
29 const FRAME_TICK: Duration = Duration::from_millis(100);
30 const FPS_TICK: Duration = Duration::from_millis(500);
31 const CAMERA_OFF_TEXT: &str = "Your camera is off";
32 const DEFAULT_LABEL: &str = "Default device";
33 const DEMO_MICROPHONES: [&str; 2] = ["Headset microphone", "Laptop microphone"];
34 const DEMO_SPEAKERS: [&str; 2] = ["Headset earphones", "Laptop speakers"];
35
36 pub struct PrejoinView {
37 app: Entity<AppState>,
38 pending_id: u64,
39 demo: bool,
40 preview: CameraPreview,
41 options: JoinOptions,
42 cameras: Vec<DeviceEntry>,
43 devices: DeviceLists,
44 camera: DeviceChoice,
45 applied_background: crate::call::BackgroundPick,
46 tick: u32,
47 _subscription: Subscription,
48 _release: Subscription,
49 }
50
51 struct DeviceSelect {
52 id: &'static str,
53 label: &'static str,
54 entries: Vec<DeviceEntry>,
55 current: DeviceChoice,
56 enabled: bool,
57 }
58
59 fn demo_devices() -> DeviceLists {
60 let device = |index: u16, name: &str| AudioDevice {
61 index,
62 guid: format!("demo-{name}"),
63 name: name.to_owned(),
64 };
65 DeviceLists {
66 inputs: DEMO_MICROPHONES
67 .iter()
68 .enumerate()
69 .map(|(index, name)| device(index as u16, name))
70 .collect(),
71 outputs: DEMO_SPEAKERS
72 .iter()
73 .enumerate()
74 .map(|(index, name)| device(index as u16, name))
75 .collect(),
76 }
77 }
78
79 fn label_of(entries: &[DeviceEntry], choice: &DeviceChoice) -> String {
80 entries
81 .iter()
82 .find(|entry| &entry.choice == choice)
83 .map_or_else(|| DEFAULT_LABEL.to_owned(), |entry| entry.label.clone())
84 }
85
86 impl PrejoinView {
87 pub fn new(
88 app: Entity<AppState>,
89 pending: &PendingJoin,
90 _window: &mut Window,
91 cx: &mut Context<Self>,
92 ) -> Self {
93 let subscription = cx.observe(&app, |view, _, cx| view.sync_background(cx));
94 let release = cx.on_release(|view, cx| view.preview.stop(cx));
95 let (preview, mut updates) = CameraPreview::new();
96 let state = app.read(cx);
97 preview.set_effects(state.call_effects);
98 let demo = state.mode.demo;
99 let mut options = state.join_options.clone();
100 options.camera_on = options.camera_on && !state.mode.read_only;
101 let camera = state.call_camera.clone();
102 let mut view = PrejoinView {
103 pending_id: pending.id,
104 demo,
105 preview,
106 options,
107 cameras: camera_entries(&[]),
108 devices: if demo {
109 demo_devices()
110 } else {
111 DeviceLists::default()
112 },
113 camera,
114 applied_background: crate::call::BackgroundPick::None,
115 tick: 0,
116 _subscription: subscription,
117 _release: release,
118 app,
119 };
120 cx.spawn(async move |this, cx| {
121 while updates.recv().await.is_some() {
122 if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
123 return;
124 }
125 }
126 })
127 .detach();
128 cx.spawn(async move |this, cx| {
129 loop {
130 cx.background_executor().timer(FPS_TICK).await;
131 if this
132 .update(cx, |view, cx| {
133 view.preview.tick(Instant::now());
134 cx.notify();
135 })
136 .is_err()
137 {
138 break;
139 }
140 }
141 })
142 .detach();
143 if demo {
144 cx.spawn(async move |this, cx| {
145 loop {
146 cx.background_executor().timer(FRAME_TICK).await;
147 if this.update(cx, |view, cx| view.demo_frame(cx)).is_err() {
148 break;
149 }
150 }
151 })
152 .detach();
153 } else {
154 view.load_devices(cx);
155 }
156 view.sync_background(cx);
157 view.restart_preview();
158 view
159 }
160
161 pub fn pending_id(&self) -> u64 {
162 self.pending_id
163 }
164
165 fn take_frames(&mut self, cx: &mut Context<Self>) {
166 self.preview.take_frames(cx);
167 cx.notify();
168 }
169
170 fn demo_frame(&mut self, cx: &mut Context<Self>) {
171 if self.options.camera_on {
172 self.tick = self.tick.wrapping_add(1);
173 self.preview.publish_demo_frame(self.tick);
174 self.take_frames(cx);
175 }
176 }
177
178 fn load_devices(&mut self, cx: &mut Context<Self>) {
179 cx.spawn(async move |this, cx| {
180 let (cameras, devices) = cx
181 .background_executor()
182 .spawn(async { (list_cameras(), list_devices(&shared_factory())) })
183 .await;
184 this.update(cx, |view, cx| {
185 view.cameras = camera_entries(&cameras);
186 view.devices = devices;
187 cx.notify();
188 })
189 .ok();
190 })
191 .detach();
192 }
193
194 fn restart_preview(&mut self) {
195 if self.options.camera_on && !self.demo {
196 self.preview.start(&self.camera);
197 }
198 }
199
200 fn sync_background(&mut self, cx: &mut Context<Self>) {
201 let state = self.app.read(cx);
202 let pick = state.call_background.clone();
203 if pick == self.applied_background {
204 return;
205 }
206 if let Some(choice) = state.call_backgrounds.choice_for(&pick) {
207 self.preview.set_background(choice);
208 self.applied_background = pick;
209 }
210 cx.notify();
211 }
212
213 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
214 self.options.camera_on = !self.options.camera_on;
215 if self.options.camera_on {
216 self.restart_preview();
217 } else {
218 self.preview.stop(cx);
219 }
220 cx.notify();
221 }
222
223 fn toggle_mic(&mut self, cx: &mut Context<Self>) {
224 self.options.mic_on = !self.options.mic_on;
225 cx.notify();
226 }
227
228 fn set_audio(&mut self, audio: AudioChoice, cx: &mut Context<Self>) {
229 self.options.audio = audio;
230 cx.notify();
231 }
232
233 fn pick_camera(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
234 self.camera = choice.clone();
235 self.app
236 .update(cx, |state, cx| state.select_call_camera(choice, cx));
237 self.restart_preview();
238 cx.notify();
239 }
240
241 fn pick_input(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
242 self.options.input = choice;
243 cx.notify();
244 }
245
246 fn pick_output(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
247 self.options.output = choice;
248 cx.notify();
249 }
250
251 fn join(&mut self, cx: &mut Context<Self>) {
252 self.preview.stop(cx);
253 let options = self.options.clone();
254 self.app
255 .update(cx, |state, cx| state.confirm_prejoin(options, cx));
256 }
257
258 fn cancel(&mut self, cx: &mut Context<Self>) {
259 self.app.update(cx, |state, cx| state.cancel_prejoin(cx));
260 }
261
262 fn preview_status(&self) -> String {
263 match self.preview.failure() {
264 Some(reason) => format!("Camera could not start: {reason}"),
265 None => "Starting camera...".to_owned(),
266 }
267 }
268
269 fn preview_box(&self, cx: &mut Context<Self>) -> Div {
270 let state = self.app.read(cx);
271 let image = self
272 .options
273 .camera_on
274 .then(|| self.preview.image(Instant::now()))
275 .flatten();
276 let me = state.directory.me.clone();
277 let face = match (&image, self.options.camera_on) {
278 (Some(image), _) => img(ImageSource::Render(image.clone()))
279 .size_full()
280 .object_fit(ObjectFit::Cover)
281 .into_any_element(),
282 (None, true) => centered_note(&self.preview_status()),
283 (None, false) => v_flex()
284 .items_center()
285 .gap(px(10.))
286 .child(person_avatar(
287 &state.directory,
288 me.as_ref().map(|me| me.user_id.as_str()),
289 me.as_ref().map_or("You", |me| me.display_name.as_str()),
290 AVATAR_SIZE,
291 ))
292 .child(
293 div()
294 .text_size(px(13.))
295 .text_color(theme::text_muted())
296 .child(CAMERA_OFF_TEXT),
297 )
298 .into_any_element(),
299 };
300 div()
301 .debug_selector(|| "shell/islands/main/prejoin/preview".into())
302 .relative()
303 .w_full()
304 .h(px(PREVIEW_HEIGHT))
305 .flex_shrink(1.)
306 .min_h(px(PREVIEW_MIN_HEIGHT))
307 .flex()
308 .items_center()
309 .justify_center()
310 .overflow_hidden()
311 .rounded(px(PREVIEW_RADIUS))
312 .bg(theme::background())
313 .child(face)
314 }
315
316 fn controls(&self, cx: &mut Context<Self>) -> impl IntoElement {
317 let view = cx.entity();
318 let camera_view = view.clone();
319 let mic_view = view.clone();
320 let (camera_glyph, camera_bg, camera_fg) = if self.options.camera_on {
321 (IconName::Video, theme::accent(), theme::on_accent())
322 } else {
323 (IconName::VideoOff, theme::surface_raised(), theme::text())
324 };
325 let (mic_glyph, mic_bg, mic_fg) = if self.options.mic_on {
326 (IconName::Mic, theme::surface_raised(), theme::text())
327 } else {
328 (IconName::MicOff, theme::red(), theme::white())
329 };
330 let audio_on = self.options.audio == AudioChoice::Computer;
331 let backgrounds = CameraMenu::of(self.app.read(cx));
332 let background_app = self.app.clone();
333 h_flex()
334 .debug_selector(|| "shell/islands/main/prejoin/controls".into())
335 .flex_none()
336 .gap(px(10.))
337 .items_center()
338 .justify_center()
339 .child(
340 round_control("prejoin-camera", camera_glyph, camera_bg, camera_fg).on_click(
341 move |_, _, cx| camera_view.update(cx, |view, cx| view.toggle_camera(cx)),
342 ),
343 )
344 .child(
345 round_control("prejoin-mic", mic_glyph, mic_bg, mic_fg)
346 .when(!audio_on, |button| button.opacity(0.4).cursor_default())
347 .when(audio_on, |button| {
348 button.on_click(move |_, _, cx| {
349 mic_view.update(cx, |view, cx| view.toggle_mic(cx))
350 })
351 }),
352 )
353 .child(
354 Button::new("prejoin-background")
355 .outline()
356 .label("Background")
357 .icon(IconName::ChevronDown)
358 .dropdown_menu(move |menu: PopupMenu, _, _| {
359 background_items(menu, &background_app, &backgrounds)
360 }),
361 )
362 }
363
364 fn select(
365 &self,
366 spec: DeviceSelect,
367 pick: impl Fn(&mut PrejoinView, DeviceChoice, &mut Context<PrejoinView>) + Clone + 'static,
368 cx: &mut Context<Self>,
369 ) -> Div {
370 let DeviceSelect {
371 id,
372 label,
373 entries,
374 current,
375 enabled,
376 } = spec;
377 let view = cx.entity();
378 let face = label_of(&entries, &current);
379 let items_entries = entries;
380 let items_current = current;
381 let button = Button::new(id)
382 .outline()
383 .w_full()
384 .label(face)
385 .icon(IconName::ChevronDown)
386 .disabled(!enabled)
387 .dropdown_menu(move |menu, _, _| {
388 let view = view.clone();
389 let pick = pick.clone();
390 device_items(items_entries.clone(), &items_current, move |choice, cx| {
391 let pick = pick.clone();
392 view.update(cx, |view, cx| pick(view, choice, cx));
393 })
394 .into_iter()
395 .fold(menu, |menu, item| menu.item(item))
396 });
397 v_flex()
398 .flex_1()
399 .min_w_0()
400 .max_w(px(SELECT_WIDTH))
401 .gap(px(4.))
402 .child(
403 div()
404 .text_size(px(12.))
405 .text_color(theme::text_muted())
406 .child(label),
407 )
408 .child(div().w_full().overflow_hidden().child(button))
409 }
410
411 fn audio_choice(&self, choice: AudioChoice, cx: &mut Context<Self>) -> Stateful<Div> {
412 let selected = self.options.audio == choice;
413 let view = cx.entity();
414 h_flex()
415 .id(match choice {
416 AudioChoice::Computer => "prejoin-audio-computer",
417 AudioChoice::NoAudio => "prejoin-audio-none",
418 })
419 .h(px(32.))
420 .px(px(14.))
421 .items_center()
422 .rounded(px(8.))
423 .border_1()
424 .border_color(if selected {
425 theme::accent()
426 } else {
427 theme::border_strong()
428 })
429 .when(selected, |option| option.bg(theme::surface_raised()))
430 .cursor_pointer()
431 .text_size(px(13.))
432 .text_color(theme::text())
433 .child(choice.label())
434 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.set_audio(choice, cx)))
435 }
436 }
437
438 fn centered_note(text: &str) -> AnyElement {
439 div()
440 .text_size(px(13.))
441 .text_color(theme::text_muted())
442 .child(text.to_owned())
443 .into_any_element()
444 }
445
446 impl Render for PrejoinView {
447 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
448 let title = self
449 .app
450 .read(cx)
451 .prejoin
452 .as_ref()
453 .map(|pending| pending.join.title.clone())
454 .unwrap_or_default();
455 let audio_on = self.options.audio == AudioChoice::Computer;
456 let (cameras, camera) = (self.cameras.clone(), self.camera.clone());
457 let (inputs, input) = (self.devices.input_entries(), self.options.input.clone());
458 let (outputs, output) = (self.devices.output_entries(), self.options.output.clone());
459 let devices = h_flex()
460 .debug_selector(|| "shell/islands/main/prejoin/devices".into())
461 .flex_none()
462 .w_full()
463 .gap(px(10.))
464 .child(self.select(
465 DeviceSelect {
466 id: "prejoin-camera-select",
467 label: "Camera",
468 entries: cameras,
469 current: camera,
470 enabled: true,
471 },
472 |view, choice, cx| view.pick_camera(choice, cx),
473 cx,
474 ))
475 .child(self.select(
476 DeviceSelect {
477 id: "prejoin-mic-select",
478 label: "Microphone",
479 entries: inputs,
480 current: input,
481 enabled: audio_on,
482 },
483 |view, choice, cx| view.pick_input(choice, cx),
484 cx,
485 ))
486 .child(self.select(
487 DeviceSelect {
488 id: "prejoin-speaker-select",
489 label: "Speaker",
490 entries: outputs,
491 current: output,
492 enabled: audio_on,
493 },
494 |view, choice, cx| view.pick_output(choice, cx),
495 cx,
496 ));
497 let audio_row = h_flex()
498 .debug_selector(|| "shell/islands/main/prejoin/audio".into())
499 .flex_none()
500 .flex_wrap()
501 .gap(px(8.))
502 .child(self.audio_choice(AudioChoice::Computer, cx))
503 .child(self.audio_choice(AudioChoice::NoAudio, cx));
504 let cancel_view = cx.entity();
505 let join_view = cx.entity();
506 let actions = h_flex()
507 .debug_selector(|| "shell/islands/main/prejoin/actions".into())
508 .flex_none()
509 .gap(px(8.))
510 .justify_end()
511 .child(
512 Button::new("prejoin-cancel")
513 .ghost()
514 .label("Cancel")
515 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
516 )
517 .child(
518 Button::new("prejoin-join")
519 .primary()
520 .label("Join now")
521 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
522 );
523 v_flex()
524 .debug_selector(|| "shell/islands/main".into())
525 .size_full()
526 .p(px(PANE_PADDING))
527 .items_center()
528 .justify_center()
529 .rounded(px(10.))
530 .bg(theme::surface())
531 .overflow_hidden()
532 .child(
533 v_flex()
534 .debug_selector(|| "shell/islands/main/prejoin".into())
535 .w(px(CONTENT_WIDTH))
536 .max_w_full()
537 .max_h_full()
538 .min_h_0()
539 .gap(px(SECTION_GAP))
540 .child(
541 v_flex()
542 .flex_none()
543 .gap(px(2.))
544 .child(
545 div()
546 .truncate()
547 .text_size(px(20.))
548 .font_weight(FontWeight::SEMIBOLD)
549 .text_color(theme::text_strong())
550 .child(title),
551 )
552 .child(
553 div()
554 .truncate()
555 .text_size(px(13.))
556 .text_color(theme::text_muted())
557 .child("Choose your video and audio settings, then join"),
558 ),
559 )
560 .child(self.preview_box(cx))
561 .child(self.controls(cx))
562 .child(devices)
563 .child(audio_row)
564 .child(actions),
565 )
566 }
567 }
@@ -0,0 +1,567 @@
1use std::time::{Duration, Instant};
2
3use calling::camera::list_cameras;
4use calling::devices::{AudioDevice, DeviceLists, list_devices, shared_factory};
5use calling::{DeviceChoice, DeviceEntry, camera_entries};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::Disableable as _;
8use gpui_kit::component::button::{Button, ButtonVariants as _};
9use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu};
10use gpui_kit::component::{h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::avatar::person_avatar;
15use super::call_extras::{CameraMenu, background_items};
16use super::call_view::{device_items, round_control};
17use crate::app_state::AppState;
18use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
19use crate::theme;
20
21const CONTENT_WIDTH: f32 = 560.;
22const PREVIEW_HEIGHT: f32 = 315.;
23const PREVIEW_RADIUS: f32 = 12.;
24const AVATAR_SIZE: f32 = 96.;
25const SELECT_WIDTH: f32 = 176.;
26const SECTION_GAP: f32 = 12.;
27const PANE_PADDING: f32 = 12.;
28const PREVIEW_MIN_HEIGHT: f32 = 60.;
29const FRAME_TICK: Duration = Duration::from_millis(100);
30const FPS_TICK: Duration = Duration::from_millis(500);
31const CAMERA_OFF_TEXT: &str = "Your camera is off";
32const DEFAULT_LABEL: &str = "Default device";
33const DEMO_MICROPHONES: [&str; 2] = ["Headset microphone", "Laptop microphone"];
34const DEMO_SPEAKERS: [&str; 2] = ["Headset earphones", "Laptop speakers"];
35
36pub struct PrejoinView {
37 app: Entity<AppState>,
38 pending_id: u64,
39 demo: bool,
40 preview: CameraPreview,
41 options: JoinOptions,
42 cameras: Vec<DeviceEntry>,
43 devices: DeviceLists,
44 camera: DeviceChoice,
45 applied_background: crate::call::BackgroundPick,
46 tick: u32,
47 _subscription: Subscription,
48 _release: Subscription,
49}
50
51struct DeviceSelect {
52 id: &'static str,
53 label: &'static str,
54 entries: Vec<DeviceEntry>,
55 current: DeviceChoice,
56 enabled: bool,
57}
58
59fn demo_devices() -> DeviceLists {
60 let device = |index: u16, name: &str| AudioDevice {
61 index,
62 guid: format!("demo-{name}"),
63 name: name.to_owned(),
64 };
65 DeviceLists {
66 inputs: DEMO_MICROPHONES
67 .iter()
68 .enumerate()
69 .map(|(index, name)| device(index as u16, name))
70 .collect(),
71 outputs: DEMO_SPEAKERS
72 .iter()
73 .enumerate()
74 .map(|(index, name)| device(index as u16, name))
75 .collect(),
76 }
77}
78
79fn label_of(entries: &[DeviceEntry], choice: &DeviceChoice) -> String {
80 entries
81 .iter()
82 .find(|entry| &entry.choice == choice)
83 .map_or_else(|| DEFAULT_LABEL.to_owned(), |entry| entry.label.clone())
84}
85
86impl PrejoinView {
87 pub fn new(
88 app: Entity<AppState>,
89 pending: &PendingJoin,
90 _window: &mut Window,
91 cx: &mut Context<Self>,
92 ) -> Self {
93 let subscription = cx.observe(&app, |view, _, cx| view.sync_background(cx));
94 let release = cx.on_release(|view, cx| view.preview.stop(cx));
95 let (preview, mut updates) = CameraPreview::new();
96 let state = app.read(cx);
97 preview.set_effects(state.call_effects);
98 let demo = state.mode.demo;
99 let mut options = state.join_options.clone();
100 options.camera_on = options.camera_on && !state.mode.read_only;
101 let camera = state.call_camera.clone();
102 let mut view = PrejoinView {
103 pending_id: pending.id,
104 demo,
105 preview,
106 options,
107 cameras: camera_entries(&[]),
108 devices: if demo {
109 demo_devices()
110 } else {
111 DeviceLists::default()
112 },
113 camera,
114 applied_background: crate::call::BackgroundPick::None,
115 tick: 0,
116 _subscription: subscription,
117 _release: release,
118 app,
119 };
120 cx.spawn(async move |this, cx| {
121 while updates.recv().await.is_some() {
122 if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
123 return;
124 }
125 }
126 })
127 .detach();
128 cx.spawn(async move |this, cx| {
129 loop {
130 cx.background_executor().timer(FPS_TICK).await;
131 if this
132 .update(cx, |view, cx| {
133 view.preview.tick(Instant::now());
134 cx.notify();
135 })
136 .is_err()
137 {
138 break;
139 }
140 }
141 })
142 .detach();
143 if demo {
144 cx.spawn(async move |this, cx| {
145 loop {
146 cx.background_executor().timer(FRAME_TICK).await;
147 if this.update(cx, |view, cx| view.demo_frame(cx)).is_err() {
148 break;
149 }
150 }
151 })
152 .detach();
153 } else {
154 view.load_devices(cx);
155 }
156 view.sync_background(cx);
157 view.restart_preview();
158 view
159 }
160
161 pub fn pending_id(&self) -> u64 {
162 self.pending_id
163 }
164
165 fn take_frames(&mut self, cx: &mut Context<Self>) {
166 self.preview.take_frames(cx);
167 cx.notify();
168 }
169
170 fn demo_frame(&mut self, cx: &mut Context<Self>) {
171 if self.options.camera_on {
172 self.tick = self.tick.wrapping_add(1);
173 self.preview.publish_demo_frame(self.tick);
174 self.take_frames(cx);
175 }
176 }
177
178 fn load_devices(&mut self, cx: &mut Context<Self>) {
179 cx.spawn(async move |this, cx| {
180 let (cameras, devices) = cx
181 .background_executor()
182 .spawn(async { (list_cameras(), list_devices(&shared_factory())) })
183 .await;
184 this.update(cx, |view, cx| {
185 view.cameras = camera_entries(&cameras);
186 view.devices = devices;
187 cx.notify();
188 })
189 .ok();
190 })
191 .detach();
192 }
193
194 fn restart_preview(&mut self) {
195 if self.options.camera_on && !self.demo {
196 self.preview.start(&self.camera);
197 }
198 }
199
200 fn sync_background(&mut self, cx: &mut Context<Self>) {
201 let state = self.app.read(cx);
202 let pick = state.call_background.clone();
203 if pick == self.applied_background {
204 return;
205 }
206 if let Some(choice) = state.call_backgrounds.choice_for(&pick) {
207 self.preview.set_background(choice);
208 self.applied_background = pick;
209 }
210 cx.notify();
211 }
212
213 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
214 self.options.camera_on = !self.options.camera_on;
215 if self.options.camera_on {
216 self.restart_preview();
217 } else {
218 self.preview.stop(cx);
219 }
220 cx.notify();
221 }
222
223 fn toggle_mic(&mut self, cx: &mut Context<Self>) {
224 self.options.mic_on = !self.options.mic_on;
225 cx.notify();
226 }
227
228 fn set_audio(&mut self, audio: AudioChoice, cx: &mut Context<Self>) {
229 self.options.audio = audio;
230 cx.notify();
231 }
232
233 fn pick_camera(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
234 self.camera = choice.clone();
235 self.app
236 .update(cx, |state, cx| state.select_call_camera(choice, cx));
237 self.restart_preview();
238 cx.notify();
239 }
240
241 fn pick_input(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
242 self.options.input = choice;
243 cx.notify();
244 }
245
246 fn pick_output(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
247 self.options.output = choice;
248 cx.notify();
249 }
250
251 fn join(&mut self, cx: &mut Context<Self>) {
252 self.preview.stop(cx);
253 let options = self.options.clone();
254 self.app
255 .update(cx, |state, cx| state.confirm_prejoin(options, cx));
256 }
257
258 fn cancel(&mut self, cx: &mut Context<Self>) {
259 self.app.update(cx, |state, cx| state.cancel_prejoin(cx));
260 }
261
262 fn preview_status(&self) -> String {
263 match self.preview.failure() {
264 Some(reason) => format!("Camera could not start: {reason}"),
265 None => "Starting camera...".to_owned(),
266 }
267 }
268
269 fn preview_box(&self, cx: &mut Context<Self>) -> Div {
270 let state = self.app.read(cx);
271 let image = self
272 .options
273 .camera_on
274 .then(|| self.preview.image(Instant::now()))
275 .flatten();
276 let me = state.directory.me.clone();
277 let face = match (&image, self.options.camera_on) {
278 (Some(image), _) => img(ImageSource::Render(image.clone()))
279 .size_full()
280 .object_fit(ObjectFit::Cover)
281 .into_any_element(),
282 (None, true) => centered_note(&self.preview_status()),
283 (None, false) => v_flex()
284 .items_center()
285 .gap(px(10.))
286 .child(person_avatar(
287 &state.directory,
288 me.as_ref().map(|me| me.user_id.as_str()),
289 me.as_ref().map_or("You", |me| me.display_name.as_str()),
290 AVATAR_SIZE,
291 ))
292 .child(
293 div()
294 .text_size(px(13.))
295 .text_color(theme::text_muted())
296 .child(CAMERA_OFF_TEXT),
297 )
298 .into_any_element(),
299 };
300 div()
301 .debug_selector(|| "shell/islands/main/prejoin/preview".into())
302 .relative()
303 .w_full()
304 .h(px(PREVIEW_HEIGHT))
305 .flex_shrink(1.)
306 .min_h(px(PREVIEW_MIN_HEIGHT))
307 .flex()
308 .items_center()
309 .justify_center()
310 .overflow_hidden()
311 .rounded(px(PREVIEW_RADIUS))
312 .bg(theme::background())
313 .child(face)
314 }
315
316 fn controls(&self, cx: &mut Context<Self>) -> impl IntoElement {
317 let view = cx.entity();
318 let camera_view = view.clone();
319 let mic_view = view.clone();
320 let (camera_glyph, camera_bg, camera_fg) = if self.options.camera_on {
321 (IconName::Video, theme::accent(), theme::on_accent())
322 } else {
323 (IconName::VideoOff, theme::surface_raised(), theme::text())
324 };
325 let (mic_glyph, mic_bg, mic_fg) = if self.options.mic_on {
326 (IconName::Mic, theme::surface_raised(), theme::text())
327 } else {
328 (IconName::MicOff, theme::red(), theme::white())
329 };
330 let audio_on = self.options.audio == AudioChoice::Computer;
331 let backgrounds = CameraMenu::of(self.app.read(cx));
332 let background_app = self.app.clone();
333 h_flex()
334 .debug_selector(|| "shell/islands/main/prejoin/controls".into())
335 .flex_none()
336 .gap(px(10.))
337 .items_center()
338 .justify_center()
339 .child(
340 round_control("prejoin-camera", camera_glyph, camera_bg, camera_fg).on_click(
341 move |_, _, cx| camera_view.update(cx, |view, cx| view.toggle_camera(cx)),
342 ),
343 )
344 .child(
345 round_control("prejoin-mic", mic_glyph, mic_bg, mic_fg)
346 .when(!audio_on, |button| button.opacity(0.4).cursor_default())
347 .when(audio_on, |button| {
348 button.on_click(move |_, _, cx| {
349 mic_view.update(cx, |view, cx| view.toggle_mic(cx))
350 })
351 }),
352 )
353 .child(
354 Button::new("prejoin-background")
355 .outline()
356 .label("Background")
357 .icon(IconName::ChevronDown)
358 .dropdown_menu(move |menu: PopupMenu, _, _| {
359 background_items(menu, &background_app, &backgrounds)
360 }),
361 )
362 }
363
364 fn select(
365 &self,
366 spec: DeviceSelect,
367 pick: impl Fn(&mut PrejoinView, DeviceChoice, &mut Context<PrejoinView>) + Clone + 'static,
368 cx: &mut Context<Self>,
369 ) -> Div {
370 let DeviceSelect {
371 id,
372 label,
373 entries,
374 current,
375 enabled,
376 } = spec;
377 let view = cx.entity();
378 let face = label_of(&entries, &current);
379 let items_entries = entries;
380 let items_current = current;
381 let button = Button::new(id)
382 .outline()
383 .w_full()
384 .label(face)
385 .icon(IconName::ChevronDown)
386 .disabled(!enabled)
387 .dropdown_menu(move |menu, _, _| {
388 let view = view.clone();
389 let pick = pick.clone();
390 device_items(items_entries.clone(), &items_current, move |choice, cx| {
391 let pick = pick.clone();
392 view.update(cx, |view, cx| pick(view, choice, cx));
393 })
394 .into_iter()
395 .fold(menu, |menu, item| menu.item(item))
396 });
397 v_flex()
398 .flex_1()
399 .min_w_0()
400 .max_w(px(SELECT_WIDTH))
401 .gap(px(4.))
402 .child(
403 div()
404 .text_size(px(12.))
405 .text_color(theme::text_muted())
406 .child(label),
407 )
408 .child(div().w_full().overflow_hidden().child(button))
409 }
410
411 fn audio_choice(&self, choice: AudioChoice, cx: &mut Context<Self>) -> Stateful<Div> {
412 let selected = self.options.audio == choice;
413 let view = cx.entity();
414 h_flex()
415 .id(match choice {
416 AudioChoice::Computer => "prejoin-audio-computer",
417 AudioChoice::NoAudio => "prejoin-audio-none",
418 })
419 .h(px(32.))
420 .px(px(14.))
421 .items_center()
422 .rounded(px(8.))
423 .border_1()
424 .border_color(if selected {
425 theme::accent()
426 } else {
427 theme::border_strong()
428 })
429 .when(selected, |option| option.bg(theme::surface_raised()))
430 .cursor_pointer()
431 .text_size(px(13.))
432 .text_color(theme::text())
433 .child(choice.label())
434 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.set_audio(choice, cx)))
435 }
436}
437
438fn centered_note(text: &str) -> AnyElement {
439 div()
440 .text_size(px(13.))
441 .text_color(theme::text_muted())
442 .child(text.to_owned())
443 .into_any_element()
444}
445
446impl Render for PrejoinView {
447 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
448 let title = self
449 .app
450 .read(cx)
451 .prejoin
452 .as_ref()
453 .map(|pending| pending.join.title.clone())
454 .unwrap_or_default();
455 let audio_on = self.options.audio == AudioChoice::Computer;
456 let (cameras, camera) = (self.cameras.clone(), self.camera.clone());
457 let (inputs, input) = (self.devices.input_entries(), self.options.input.clone());
458 let (outputs, output) = (self.devices.output_entries(), self.options.output.clone());
459 let devices = h_flex()
460 .debug_selector(|| "shell/islands/main/prejoin/devices".into())
461 .flex_none()
462 .w_full()
463 .gap(px(10.))
464 .child(self.select(
465 DeviceSelect {
466 id: "prejoin-camera-select",
467 label: "Camera",
468 entries: cameras,
469 current: camera,
470 enabled: true,
471 },
472 |view, choice, cx| view.pick_camera(choice, cx),
473 cx,
474 ))
475 .child(self.select(
476 DeviceSelect {
477 id: "prejoin-mic-select",
478 label: "Microphone",
479 entries: inputs,
480 current: input,
481 enabled: audio_on,
482 },
483 |view, choice, cx| view.pick_input(choice, cx),
484 cx,
485 ))
486 .child(self.select(
487 DeviceSelect {
488 id: "prejoin-speaker-select",
489 label: "Speaker",
490 entries: outputs,
491 current: output,
492 enabled: audio_on,
493 },
494 |view, choice, cx| view.pick_output(choice, cx),
495 cx,
496 ));
497 let audio_row = h_flex()
498 .debug_selector(|| "shell/islands/main/prejoin/audio".into())
499 .flex_none()
500 .flex_wrap()
501 .gap(px(8.))
502 .child(self.audio_choice(AudioChoice::Computer, cx))
503 .child(self.audio_choice(AudioChoice::NoAudio, cx));
504 let cancel_view = cx.entity();
505 let join_view = cx.entity();
506 let actions = h_flex()
507 .debug_selector(|| "shell/islands/main/prejoin/actions".into())
508 .flex_none()
509 .gap(px(8.))
510 .justify_end()
511 .child(
512 Button::new("prejoin-cancel")
513 .ghost()
514 .label("Cancel")
515 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
516 )
517 .child(
518 Button::new("prejoin-join")
519 .primary()
520 .label("Join now")
521 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
522 );
523 v_flex()
524 .debug_selector(|| "shell/islands/main".into())
525 .size_full()
526 .p(px(PANE_PADDING))
527 .items_center()
528 .justify_center()
529 .rounded(px(10.))
530 .bg(theme::surface())
531 .overflow_hidden()
532 .child(
533 v_flex()
534 .debug_selector(|| "shell/islands/main/prejoin".into())
535 .w(px(CONTENT_WIDTH))
536 .max_w_full()
537 .max_h_full()
538 .min_h_0()
539 .gap(px(SECTION_GAP))
540 .child(
541 v_flex()
542 .flex_none()
543 .gap(px(2.))
544 .child(
545 div()
546 .truncate()
547 .text_size(px(20.))
548 .font_weight(FontWeight::SEMIBOLD)
549 .text_color(theme::text_strong())
550 .child(title),
551 )
552 .child(
553 div()
554 .truncate()
555 .text_size(px(13.))
556 .text_color(theme::text_muted())
557 .child("Choose your video and audio settings, then join"),
558 ),
559 )
560 .child(self.preview_box(cx))
561 .child(self.controls(cx))
562 .child(devices)
563 .child(audio_row)
564 .child(actions),
565 )
566 }
567}
crates/app/src/views/shell.rs +30 −6
@@ -11,13 +11,14 @@ use super::conversation::{ConversationView, ReplyToHovered};
11 11 use super::dialog_overlay::render_task_dialog;
12 12 use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
13 13 use super::image_viewer::{ImageViewer, ImageViewerEvent};
14 use super::prejoin_view::PrejoinView;
14 15 use super::profile_card::{ProfileCard, ProfileCardEvent};
15 16 use super::rail::RailView;
16 17 use super::saved_panel::{SavedPanel, SavedPanelEvent};
17 18 use super::shortcuts::{
18 AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenCallsTab,
19 OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk, Scope,
20 ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
19 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
21 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
21 22 ToggleCallHand, ToggleCallShare,
22 23 };
23 24 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
@@ -83,6 +84,7 @@ pub struct AppShell {
83 84 sidebar: Entity<SidebarView>,
84 85 conversation: Entity<ConversationView>,
85 86 call_chat: Option<(String, Entity<ConversationView>)>,
87 prejoin: Option<Entity<PrejoinView>>,
86 88 switcher: Option<Entity<Switcher>>,
87 89 notifications: Entity<NotificationCenter>,
88 90 _call_windows: Entity<CallWindows>,
@@ -125,6 +127,19 @@ impl AppShell {
125 127 }
126 128 }
127 129
130 fn sync_prejoin(&mut self, window: &mut Window, cx: &mut Context<Self>) {
131 let wanted = self.state.read(cx).prejoin.clone();
132 let open = self.prejoin.as_ref().map(|view| view.read(cx).pending_id());
133 match (wanted, open) {
134 (Some(pending), Some(id)) if pending.id == id => {}
135 (Some(pending), _) => {
136 let app = self.state.clone();
137 self.prejoin = Some(cx.new(|cx| PrejoinView::new(app, &pending, window, cx)));
138 }
139 (None, _) => self.prejoin = None,
140 }
141 }
142
128 143 pub fn new(
129 144 state: Entity<AppState>,
130 145 open_target: Option<OpenTarget>,
@@ -229,6 +244,7 @@ impl AppShell {
229 244 sidebar,
230 245 conversation,
231 246 call_chat: None,
247 prejoin: None,
232 248 switcher: None,
233 249 notifications,
234 250 _call_windows: call_windows,
@@ -672,9 +688,12 @@ impl AppShell {
672 688 ),
673 689 ),
674 690 )
675 .child(match call_view {
676 Some(call_view) => call_view,
677 None => self
691 .child(match (call_view, self.prejoin.clone()) {
692 (Some(call_view), _) => call_view,
693 (None, Some(prejoin)) => prejoin
694 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
695 .into_any_element(),
696 (None, None) => self
678 697 .conversation
679 698 .clone()
680 699 .cached(
@@ -715,6 +734,7 @@ impl Render for AppShell {
715 734 }
716 735 let chat_thread = self.state.read(cx).call_chat_thread();
717 736 self.sync_call_chat(chat_thread, window, cx);
737 self.sync_prejoin(window, cx);
718 738 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
719 739 let state = self.state.read(cx);
720 740 let call_fullscreen = state.call_fullscreen();
@@ -818,6 +838,10 @@ impl Render for AppShell {
818 838 this.state
819 839 .update(cx, |state, cx| state.decline_ringing_call(cx));
820 840 }))
841 .on_action(cx.listener(|this, _: &JoinMeetingFromToast, _, cx| {
842 this.state
843 .update(cx, |state, cx| state.join_latest_meeting_toast(cx));
844 }))
821 845 .on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
822 846 this.state.update(cx, |state, cx| state.leave_call(cx));
823 847 }))
@@ -11,13 +11,14 @@ use super::conversation::{ConversationView, ReplyToHovered};
11use super::dialog_overlay::render_task_dialog;
11use super::dialog_overlay::render_task_dialog;
12use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
12use super::forward_dialog::{ForwardDialog, ForwardDialogEvent};
13use super::image_viewer::{ImageViewer, ImageViewerEvent};
13use super::image_viewer::{ImageViewer, ImageViewerEvent};
14use super::prejoin_view::PrejoinView;
14use super::profile_card::{ProfileCard, ProfileCardEvent};
15use super::profile_card::{ProfileCard, ProfileCardEvent};
15use super::rail::RailView;
16use super::rail::RailView;
16use super::saved_panel::{SavedPanel, SavedPanelEvent};
17use super::saved_panel::{SavedPanel, SavedPanelEvent};
17use super::shortcuts::{
18use super::shortcuts::{
18 AcceptCall, DeclineCall, HangUpCall, NextConversation, OpenActivity, OpenCallsTab,
19 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
19 OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk, Scope,
20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenLobbyList, OpenSaved, PreviousConversation, PushToTalk,
20 ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
21 Scope, ShowShortcuts, StartAudioCall, StartVideoCall, ToggleCallCamera, ToggleCallFullscreen,
21 ToggleCallHand, ToggleCallShare,
22 ToggleCallHand, ToggleCallShare,
22};
23};
23use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
24use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
@@ -83,6 +84,7 @@ pub struct AppShell {
83 sidebar: Entity<SidebarView>,
84 sidebar: Entity<SidebarView>,
84 conversation: Entity<ConversationView>,
85 conversation: Entity<ConversationView>,
85 call_chat: Option<(String, Entity<ConversationView>)>,
86 call_chat: Option<(String, Entity<ConversationView>)>,
87 prejoin: Option<Entity<PrejoinView>>,
86 switcher: Option<Entity<Switcher>>,
88 switcher: Option<Entity<Switcher>>,
87 notifications: Entity<NotificationCenter>,
89 notifications: Entity<NotificationCenter>,
88 _call_windows: Entity<CallWindows>,
90 _call_windows: Entity<CallWindows>,
@@ -125,6 +127,19 @@ impl AppShell {
125 }
127 }
126 }
128 }
127
129
130 fn sync_prejoin(&mut self, window: &mut Window, cx: &mut Context<Self>) {
131 let wanted = self.state.read(cx).prejoin.clone();
132 let open = self.prejoin.as_ref().map(|view| view.read(cx).pending_id());
133 match (wanted, open) {
134 (Some(pending), Some(id)) if pending.id == id => {}
135 (Some(pending), _) => {
136 let app = self.state.clone();
137 self.prejoin = Some(cx.new(|cx| PrejoinView::new(app, &pending, window, cx)));
138 }
139 (None, _) => self.prejoin = None,
140 }
141 }
142
128 pub fn new(
143 pub fn new(
129 state: Entity<AppState>,
144 state: Entity<AppState>,
130 open_target: Option<OpenTarget>,
145 open_target: Option<OpenTarget>,
@@ -229,6 +244,7 @@ impl AppShell {
229 sidebar,
244 sidebar,
230 conversation,
245 conversation,
231 call_chat: None,
246 call_chat: None,
247 prejoin: None,
232 switcher: None,
248 switcher: None,
233 notifications,
249 notifications,
234 _call_windows: call_windows,
250 _call_windows: call_windows,
@@ -672,9 +688,12 @@ impl AppShell {
672 ),
688 ),
673 ),
689 ),
674 )
690 )
675 .child(match call_view {
691 .child(match (call_view, self.prejoin.clone()) {
676 Some(call_view) => call_view,
692 (Some(call_view), _) => call_view,
677 None => self
693 (None, Some(prejoin)) => prejoin
694 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
695 .into_any_element(),
696 (None, None) => self
678 .conversation
697 .conversation
679 .clone()
698 .clone()
680 .cached(
699 .cached(
@@ -715,6 +734,7 @@ impl Render for AppShell {
715 }
734 }
716 let chat_thread = self.state.read(cx).call_chat_thread();
735 let chat_thread = self.state.read(cx).call_chat_thread();
717 self.sync_call_chat(chat_thread, window, cx);
736 self.sync_call_chat(chat_thread, window, cx);
737 self.sync_prejoin(window, cx);
718 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
738 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
719 let state = self.state.read(cx);
739 let state = self.state.read(cx);
720 let call_fullscreen = state.call_fullscreen();
740 let call_fullscreen = state.call_fullscreen();
@@ -818,6 +838,10 @@ impl Render for AppShell {
818 this.state
838 this.state
819 .update(cx, |state, cx| state.decline_ringing_call(cx));
839 .update(cx, |state, cx| state.decline_ringing_call(cx));
820 }))
840 }))
841 .on_action(cx.listener(|this, _: &JoinMeetingFromToast, _, cx| {
842 this.state
843 .update(cx, |state, cx| state.join_latest_meeting_toast(cx));
844 }))
821 .on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
845 .on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
822 this.state.update(cx, |state, cx| state.leave_call(cx));
846 this.state.update(cx, |state, cx| state.leave_call(cx));
823 }))
847 }))
crates/app/src/views/shortcuts.rs +2 −0
@@ -23,6 +23,7 @@ actions!(
23 23 NextConversation,
24 24 AcceptCall,
25 25 DeclineCall,
26 JoinMeetingFromToast,
26 27 HangUpCall,
27 28 ToggleCallCamera,
28 29 ToggleCallShare,
@@ -117,6 +118,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
117 118 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
118 119 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
119 120 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
121 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
120 122 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
121 123 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
122 124 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
@@ -23,6 +23,7 @@ actions!(
23 NextConversation,
23 NextConversation,
24 AcceptCall,
24 AcceptCall,
25 DeclineCall,
25 DeclineCall,
26 JoinMeetingFromToast,
26 HangUpCall,
27 HangUpCall,
27 ToggleCallCamera,
28 ToggleCallCamera,
28 ToggleCallShare,
29 ToggleCallShare,
@@ -117,6 +118,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
117 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
118 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
118 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
119 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
119 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
120 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
121 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
120 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
122 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
121 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
123 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
122 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
124 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
crates/calling/src/call.rs +15 −1
@@ -814,6 +814,7 @@ async fn drive(
814 814 let mut software_audio: Option<SoftwareAudio> = None;
815 815 let mut share_sound_wanted = false;
816 816 let mut mic_settings = MicSettings::default();
817 let mut audio_disabled = false;
817 818 let mut remote_audio: Option<RtcAudioTrack> = None;
818 819 let mut own_hand: Option<String> = None;
819 820 let mut depacketizer = Depacketizer::default();
@@ -1257,6 +1258,18 @@ async fn drive(
1257 1258 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
1258 1259 }
1259 1260 }
1261 Some(CallCommand::DisableAudio) => {
1262 let audio = live.audio.as_ref().expect("audio set above");
1263 if audio.uses_devices() {
1264 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
1265 factory.set_adm_recording_enabled(false);
1266 factory.set_adm_playout_enabled(false);
1267 }
1268 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
1269 audio_disabled = true;
1270 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, control, timeline);
1271 control.send(CallUpdate::ListenOnly(true));
1272 }
1260 1273 Some(CallCommand::SelectInput(choice)) => {
1261 1274 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1262 1275 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
@@ -1267,10 +1280,11 @@ async fn drive(
1267 1280 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1268 1281 }
1269 1282 }
1270 Some(CallCommand::SetMicSettings(settings)) => {
1283 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
1271 1284 mic_settings = settings;
1272 1285 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1273 1286 }
1287 Some(CallCommand::SetMicSettings(settings)) => mic_settings = settings,
1274 1288 Some(CallCommand::SelectOutput(choice)) => {
1275 1289 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1276 1290 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
@@ -814,6 +814,7 @@ async fn drive(
814 let mut software_audio: Option<SoftwareAudio> = None;
814 let mut software_audio: Option<SoftwareAudio> = None;
815 let mut share_sound_wanted = false;
815 let mut share_sound_wanted = false;
816 let mut mic_settings = MicSettings::default();
816 let mut mic_settings = MicSettings::default();
817 let mut audio_disabled = false;
817 let mut remote_audio: Option<RtcAudioTrack> = None;
818 let mut remote_audio: Option<RtcAudioTrack> = None;
818 let mut own_hand: Option<String> = None;
819 let mut own_hand: Option<String> = None;
819 let mut depacketizer = Depacketizer::default();
820 let mut depacketizer = Depacketizer::default();
@@ -1257,6 +1258,18 @@ async fn drive(
1257 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
1258 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
1258 }
1259 }
1259 }
1260 }
1261 Some(CallCommand::DisableAudio) => {
1262 let audio = live.audio.as_ref().expect("audio set above");
1263 if audio.uses_devices() {
1264 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
1265 factory.set_adm_recording_enabled(false);
1266 factory.set_adm_playout_enabled(false);
1267 }
1268 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
1269 audio_disabled = true;
1270 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, control, timeline);
1271 control.send(CallUpdate::ListenOnly(true));
1272 }
1260 Some(CallCommand::SelectInput(choice)) => {
1273 Some(CallCommand::SelectInput(choice)) => {
1261 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1274 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1262 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
1275 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
@@ -1267,10 +1280,11 @@ async fn drive(
1267 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1280 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1268 }
1281 }
1269 }
1282 }
1270 Some(CallCommand::SetMicSettings(settings)) => {
1283 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
1271 mic_settings = settings;
1284 mic_settings = settings;
1272 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1285 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1273 }
1286 }
1287 Some(CallCommand::SetMicSettings(settings)) => mic_settings = settings,
1274 Some(CallCommand::SelectOutput(choice)) => {
1288 Some(CallCommand::SelectOutput(choice)) => {
1275 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1289 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1276 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
1290 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
crates/calling/src/control.rs +1 −0
@@ -25,6 +25,7 @@ use crate::whiteboard::ContentShare;
25 25 #[derive(Debug, Clone, PartialEq, Eq)]
26 26 pub enum CallCommand {
27 27 Mute(MuteCommand),
28 DisableAudio,
28 29 SelectInput(DeviceChoice),
29 30 SelectOutput(DeviceChoice),
30 31 SetMicSettings(MicSettings),
@@ -25,6 +25,7 @@ use crate::whiteboard::ContentShare;
25#[derive(Debug, Clone, PartialEq, Eq)]
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum CallCommand {
26pub enum CallCommand {
27 Mute(MuteCommand),
27 Mute(MuteCommand),
28 DisableAudio,
28 SelectInput(DeviceChoice),
29 SelectInput(DeviceChoice),
29 SelectOutput(DeviceChoice),
30 SelectOutput(DeviceChoice),
30 SetMicSettings(MicSettings),
31 SetMicSettings(MicSettings),
crates/chatsvc/src/calendar.rs +35 −2
@@ -5,6 +5,12 @@ use session::{ApiResponse, Method, Request, Session};
5 5 use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
6 6 use crate::error::{Error, Result};
7 7
8 mod schedule;
9
10 pub use schedule::{
11 Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, parse_created_event,
12 };
13
8 14 const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
9 15 const NAIVE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f";
10 16
@@ -31,6 +37,7 @@ pub struct CalendarEvent {
31 37 pub thread_id: Option<String>,
32 38 pub organizer_name: Option<String>,
33 39 pub organizer_address: Option<String>,
40 pub ical_uid: Option<String>,
34 41 pub response: ResponseType,
35 42 }
36 43
@@ -100,7 +107,10 @@ impl<T: CardTransport> Calendar<T> {
100 107 });
101 108 let answer = self
102 109 .transport
103 .send(Request::with_body(Method::Post, &self.create_url, body), spaces_scope())
110 .send(
111 Request::with_body(Method::Post, &self.create_url, body),
112 spaces_scope(),
113 )
104 114 .await?;
105 115 if !answer.is_success() {
106 116 return Err(Error::Session(session::Error::api(
@@ -110,7 +120,11 @@ impl<T: CardTransport> Calendar<T> {
110 120 )));
111 121 }
112 122 meet_now_join_url(&answer.body).ok_or_else(|| {
113 Error::Session(session::Error::api(answer.status, &self.create_url, answer.body))
123 Error::Session(session::Error::api(
124 answer.status,
125 &self.create_url,
126 answer.body,
127 ))
114 128 })
115 129 }
116 130 }
@@ -166,6 +180,9 @@ fn thread_id(entry: &Value) -> Option<String> {
166 180 }
167 181
168 182 fn response_type(entry: &Value) -> ResponseType {
183 if flag(entry, "isOrganizer") {
184 return ResponseType::Organizer;
185 }
169 186 let label = text(entry, "myResponseType").or_else(|| {
170 187 let status = entry.get("responseStatus")?;
171 188 status
@@ -196,6 +213,7 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
196 213 thread_id: thread_id(entry),
197 214 organizer_name: text(entry, "organizerName"),
198 215 organizer_address: text(entry, "organizerAddress"),
216 ical_uid: text(entry, "iCalUid").or_else(|| text(entry, "iCalUId")),
199 217 response: response_type(entry),
200 218 })
201 219 }
@@ -287,6 +305,21 @@ mod tests {
287 305 assert!(events[3].cancelled);
288 306 }
289 307
308 #[test]
309 fn the_organizer_flag_and_calendar_uid_are_read() {
310 let body = serde_json::json!({"value": [{
311 "objectId": "a",
312 "startTime": "2026-10-12T08:30:00Z",
313 "endTime": "2026-10-12T09:00:00Z",
314 "isOrganizer": true,
315 "myResponseType": "Accepted",
316 "iCalUid": "uid-a"
317 }]});
318 let events = parse_calendar_events(&body);
319 assert_eq!(events[0].response, ResponseType::Organizer);
320 assert_eq!(events[0].ical_uid.as_deref(), Some("uid-a"));
321 }
322
290 323 #[test]
291 324 fn entries_without_an_id_or_times_are_skipped() {
292 325 let body =
@@ -5,6 +5,12 @@ use session::{ApiResponse, Method, Request, Session};
5use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
5use crate::cards::{CardTransport, DEFAULT_MT_REGION, SessionCardTransport, spaces_scope};
6use crate::error::{Error, Result};
6use crate::error::{Error, Result};
7
7
8mod schedule;
9
10pub use schedule::{
11 Attendee, CreatedEvent, NewEvent, Repeat, Reply, new_event_body, parse_created_event,
12};
13
8const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
14const QUERY_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%SZ";
9const NAIVE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f";
15const NAIVE_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S%.f";
10
16
@@ -31,6 +37,7 @@ pub struct CalendarEvent {
31 pub thread_id: Option<String>,
37 pub thread_id: Option<String>,
32 pub organizer_name: Option<String>,
38 pub organizer_name: Option<String>,
33 pub organizer_address: Option<String>,
39 pub organizer_address: Option<String>,
40 pub ical_uid: Option<String>,
34 pub response: ResponseType,
41 pub response: ResponseType,
35}
42}
36
43
@@ -100,7 +107,10 @@ impl<T: CardTransport> Calendar<T> {
100 });
107 });
101 let answer = self
108 let answer = self
102 .transport
109 .transport
103 .send(Request::with_body(Method::Post, &self.create_url, body), spaces_scope())
110 .send(
111 Request::with_body(Method::Post, &self.create_url, body),
112 spaces_scope(),
113 )
104 .await?;
114 .await?;
105 if !answer.is_success() {
115 if !answer.is_success() {
106 return Err(Error::Session(session::Error::api(
116 return Err(Error::Session(session::Error::api(
@@ -110,7 +120,11 @@ impl<T: CardTransport> Calendar<T> {
110 )));
120 )));
111 }
121 }
112 meet_now_join_url(&answer.body).ok_or_else(|| {
122 meet_now_join_url(&answer.body).ok_or_else(|| {
113 Error::Session(session::Error::api(answer.status, &self.create_url, answer.body))
123 Error::Session(session::Error::api(
124 answer.status,
125 &self.create_url,
126 answer.body,
127 ))
114 })
128 })
115 }
129 }
116}
130}
@@ -166,6 +180,9 @@ fn thread_id(entry: &Value) -> Option<String> {
166}
180}
167
181
168fn response_type(entry: &Value) -> ResponseType {
182fn response_type(entry: &Value) -> ResponseType {
183 if flag(entry, "isOrganizer") {
184 return ResponseType::Organizer;
185 }
169 let label = text(entry, "myResponseType").or_else(|| {
186 let label = text(entry, "myResponseType").or_else(|| {
170 let status = entry.get("responseStatus")?;
187 let status = entry.get("responseStatus")?;
171 status
188 status
@@ -196,6 +213,7 @@ fn parse_event(entry: &Value) -> Option<CalendarEvent> {
196 thread_id: thread_id(entry),
213 thread_id: thread_id(entry),
197 organizer_name: text(entry, "organizerName"),
214 organizer_name: text(entry, "organizerName"),
198 organizer_address: text(entry, "organizerAddress"),
215 organizer_address: text(entry, "organizerAddress"),
216 ical_uid: text(entry, "iCalUid").or_else(|| text(entry, "iCalUId")),
199 response: response_type(entry),
217 response: response_type(entry),
200 })
218 })
201}
219}
@@ -287,6 +305,21 @@ mod tests {
287 assert!(events[3].cancelled);
305 assert!(events[3].cancelled);
288 }
306 }
289
307
308 #[test]
309 fn the_organizer_flag_and_calendar_uid_are_read() {
310 let body = serde_json::json!({"value": [{
311 "objectId": "a",
312 "startTime": "2026-10-12T08:30:00Z",
313 "endTime": "2026-10-12T09:00:00Z",
314 "isOrganizer": true,
315 "myResponseType": "Accepted",
316 "iCalUid": "uid-a"
317 }]});
318 let events = parse_calendar_events(&body);
319 assert_eq!(events[0].response, ResponseType::Organizer);
320 assert_eq!(events[0].ical_uid.as_deref(), Some("uid-a"));
321 }
322
290 #[test]
323 #[test]
291 fn entries_without_an_id_or_times_are_skipped() {
324 fn entries_without_an_id_or_times_are_skipped() {
292 let body =
325 let body =
crates/chatsvc/src/calendar/schedule.rs added +440 −0
@@ -0,0 +1,440 @@
1 use chrono::{DateTime, Datelike, Utc, Weekday};
2 use serde_json::{Value, json};
3 use session::{GRAPH, Method, Request, Scope};
4
5 use super::Calendar;
6 use crate::cards::CardTransport;
7 use crate::error::{Error, Result};
8 use crate::messages::encode;
9
10 const CALENDARS_SCOPE: &str = "Calendars.ReadWrite";
11 const GRAPH_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
12 const GRAPH_DATE_FORMAT: &str = "%Y-%m-%d";
13 const TIME_ZONE: &str = "UTC";
14 const ONLINE_PROVIDER: &str = "teamsForBusiness";
15 const NOT_FOUND: u16 = 404;
16 const WORK_WEEK: [Weekday; 5] = [
17 Weekday::Mon,
18 Weekday::Tue,
19 Weekday::Wed,
20 Weekday::Thu,
21 Weekday::Fri,
22 ];
23
24 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25 pub enum Repeat {
26 #[default]
27 Never,
28 Daily,
29 Weekdays,
30 Weekly,
31 }
32
33 impl Repeat {
34 pub const ALL: [Repeat; 4] = [
35 Repeat::Never,
36 Repeat::Daily,
37 Repeat::Weekdays,
38 Repeat::Weekly,
39 ];
40
41 pub fn label(self) -> &'static str {
42 match self {
43 Repeat::Never => "Does not repeat",
44 Repeat::Daily => "Daily",
45 Repeat::Weekdays => "Weekdays",
46 Repeat::Weekly => "Weekly",
47 }
48 }
49 }
50
51 #[derive(Debug, Clone, PartialEq, Eq)]
52 pub struct Attendee {
53 pub name: String,
54 pub address: String,
55 }
56
57 #[derive(Debug, Clone, PartialEq, Eq)]
58 pub struct NewEvent {
59 pub subject: String,
60 pub start: DateTime<Utc>,
61 pub end: DateTime<Utc>,
62 pub attendees: Vec<Attendee>,
63 pub repeat: Repeat,
64 pub details: String,
65 }
66
67 #[derive(Debug, Clone, PartialEq, Eq)]
68 pub struct CreatedEvent {
69 pub id: String,
70 pub join_url: Option<String>,
71 }
72
73 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
74 pub enum Reply {
75 Accept,
76 Tentative,
77 Decline,
78 }
79
80 impl Reply {
81 fn action(self) -> &'static str {
82 match self {
83 Reply::Accept => "accept",
84 Reply::Tentative => "tentativelyAccept",
85 Reply::Decline => "decline",
86 }
87 }
88 }
89
90 fn day_name(weekday: Weekday) -> &'static str {
91 match weekday {
92 Weekday::Mon => "monday",
93 Weekday::Tue => "tuesday",
94 Weekday::Wed => "wednesday",
95 Weekday::Thu => "thursday",
96 Weekday::Fri => "friday",
97 Weekday::Sat => "saturday",
98 Weekday::Sun => "sunday",
99 }
100 }
101
102 fn graph_time(time: DateTime<Utc>) -> Value {
103 json!({
104 "dateTime": time.format(GRAPH_TIME_FORMAT).to_string(),
105 "timeZone": TIME_ZONE,
106 })
107 }
108
109 fn recurrence(repeat: Repeat, start: DateTime<Utc>) -> Option<Value> {
110 let (pattern_type, days): (&str, Vec<Weekday>) = match repeat {
111 Repeat::Never => return None,
112 Repeat::Daily => ("daily", Vec::new()),
113 Repeat::Weekdays => ("weekly", WORK_WEEK.to_vec()),
114 Repeat::Weekly => ("weekly", vec![start.weekday()]),
115 };
116 let mut pattern = json!({"type": pattern_type, "interval": 1});
117 if !days.is_empty() {
118 pattern["daysOfWeek"] = days.into_iter().map(day_name).collect();
119 pattern["firstDayOfWeek"] = json!("monday");
120 }
121 Some(json!({
122 "pattern": pattern,
123 "range": {
124 "type": "noEnd",
125 "startDate": start.format(GRAPH_DATE_FORMAT).to_string(),
126 },
127 }))
128 }
129
130 pub fn new_event_body(event: &NewEvent) -> Value {
131 let mut body = json!({
132 "subject": event.subject,
133 "start": graph_time(event.start),
134 "end": graph_time(event.end),
135 "attendees": event.attendees.iter().map(|attendee| json!({
136 "type": "required",
137 "emailAddress": {"address": attendee.address, "name": attendee.name},
138 })).collect::<Vec<_>>(),
139 "isOnlineMeeting": true,
140 "onlineMeetingProvider": ONLINE_PROVIDER,
141 });
142 if !event.details.trim().is_empty() {
143 body["body"] = json!({"contentType": "text", "content": event.details});
144 }
145 if let Some(recurrence) = recurrence(event.repeat, event.start) {
146 body["recurrence"] = recurrence;
147 }
148 body
149 }
150
151 pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {
152 Some(CreatedEvent {
153 id: body.get("id")?.as_str()?.to_owned(),
154 join_url: body
155 .pointer("/onlineMeeting/joinUrl")
156 .and_then(Value::as_str)
157 .map(str::to_owned),
158 })
159 }
160
161 fn events_url() -> String {
162 format!("{GRAPH}/v1.0/me/events")
163 }
164
165 fn reply_url(event_id: &str, reply: Reply) -> String {
166 format!("{}/{}/{}", events_url(), encode(event_id), reply.action())
167 }
168
169 fn lookup_url(ical_uid: &str) -> String {
170 format!(
171 "{}?$filter={}&$select=id&$top=1",
172 events_url(),
173 encode(&format!("iCalUId eq '{}'", ical_uid.replace('\'', "''")))
174 )
175 }
176
177 fn api_error(answer: session::ApiResponse, url: &str) -> Error {
178 Error::Session(session::Error::api(answer.status, url, answer.body))
179 }
180
181 impl<T: CardTransport> Calendar<T> {
182 pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
183 let url = events_url();
184 let request = Request::with_body(Method::Post, &url, new_event_body(event));
185 let answer = self
186 .transport
187 .send(request, Scope::graph(CALENDARS_SCOPE))
188 .await?;
189 if !answer.is_success() {
190 return Err(api_error(answer, &url));
191 }
192 parse_created_event(&answer.body).ok_or_else(|| api_error(answer, &url))
193 }
194
195 pub async fn respond(
196 &self,
197 event_id: &str,
198 ical_uid: Option<&str>,
199 reply: Reply,
200 send_response: bool,
201 ) -> Result<()> {
202 let answer = self.send_reply(event_id, reply, send_response).await?;
203 if answer.is_success() {
204 return Ok(());
205 }
206 let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {
207 return Err(api_error(answer, &reply_url(event_id, reply)));
208 };
209 let graph_id = self.graph_event_id(ical_uid).await?;
210 let retried = self.send_reply(&graph_id, reply, send_response).await?;
211 if retried.is_success() {
212 return Ok(());
213 }
214 Err(api_error(retried, &reply_url(&graph_id, reply)))
215 }
216
217 async fn send_reply(
218 &self,
219 event_id: &str,
220 reply: Reply,
221 send_response: bool,
222 ) -> Result<session::ApiResponse> {
223 let request = Request::with_body(
224 Method::Post,
225 reply_url(event_id, reply),
226 json!({"comment": "", "sendResponse": send_response}),
227 );
228 self.transport
229 .send(request, Scope::graph(CALENDARS_SCOPE))
230 .await
231 }
232
233 async fn graph_event_id(&self, ical_uid: &str) -> Result<String> {
234 let url = lookup_url(ical_uid);
235 let answer = self
236 .transport
237 .send(Request::get(&url), Scope::graph(CALENDARS_SCOPE))
238 .await?;
239 if !answer.is_success() {
240 return Err(api_error(answer, &url));
241 }
242 answer
243 .body
244 .pointer("/value/0/id")
245 .and_then(Value::as_str)
246 .map(str::to_owned)
247 .ok_or_else(|| api_error(answer, &url))
248 }
249 }
250
251 #[cfg(test)]
252 mod tests {
253 use std::sync::Mutex;
254
255 use chrono::TimeZone;
256
257 use super::*;
258 use crate::calendar::Calendar;
259
260 struct Scripted {
261 answers: Mutex<Vec<(u16, Value)>>,
262 sent: Mutex<Vec<(Method, String, Option<Value>)>>,
263 }
264
265 impl Scripted {
266 fn new(answers: Vec<(u16, Value)>) -> Self {
267 Scripted {
268 answers: Mutex::new(answers),
269 sent: Mutex::new(Vec::new()),
270 }
271 }
272 }
273
274 impl CardTransport for Scripted {
275 async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> {
276 assert_eq!(scope, Scope::graph(CALENDARS_SCOPE));
277 self.sent
278 .lock()
279 .unwrap()
280 .push((request.method, request.url, request.body));
281 let (status, body) = self.answers.lock().unwrap().remove(0);
282 Ok(session::ApiResponse {
283 status,
284 body,
285 retry_after: None,
286 })
287 }
288 }
289
290 fn event(repeat: Repeat) -> NewEvent {
291 NewEvent {
292 subject: "Planning".into(),
293 start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap(),
294 end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(),
295 attendees: vec![Attendee {
296 name: "Mara Lindqvist".into(),
297 address: "mara@example.invalid".into(),
298 }],
299 repeat,
300 details: String::new(),
301 }
302 }
303
304 #[test]
305 fn the_body_asks_for_a_teams_meeting_with_utc_times() {
306 let body = new_event_body(&event(Repeat::Never));
307 assert_eq!(body["subject"], "Planning");
308 assert_eq!(body["isOnlineMeeting"], true);
309 assert_eq!(body["onlineMeetingProvider"], "teamsForBusiness");
310 assert_eq!(body["start"]["dateTime"], "2026-10-14T09:30:00");
311 assert_eq!(body["start"]["timeZone"], "UTC");
312 assert_eq!(body["end"]["dateTime"], "2026-10-14T10:00:00");
313 assert_eq!(body["attendees"][0]["type"], "required");
314 assert_eq!(
315 body["attendees"][0]["emailAddress"]["address"],
316 "mara@example.invalid"
317 );
318 assert!(body.get("recurrence").is_none());
319 assert!(body.get("body").is_none());
320 }
321
322 #[test]
323 fn details_become_a_plain_text_body() {
324 let body = new_event_body(&NewEvent {
325 details: "Agenda: roadmap".into(),
326 ..event(Repeat::Never)
327 });
328 assert_eq!(body["body"]["contentType"], "text");
329 assert_eq!(body["body"]["content"], "Agenda: roadmap");
330 }
331
332 #[test]
333 fn recurrence_maps_to_graph_patterns() {
334 let daily = new_event_body(&event(Repeat::Daily));
335 assert_eq!(daily["recurrence"]["pattern"]["type"], "daily");
336 assert_eq!(daily["recurrence"]["pattern"]["interval"], 1);
337 assert_eq!(daily["recurrence"]["range"]["type"], "noEnd");
338 assert_eq!(daily["recurrence"]["range"]["startDate"], "2026-10-14");
339 let weekdays = new_event_body(&event(Repeat::Weekdays));
340 assert_eq!(weekdays["recurrence"]["pattern"]["type"], "weekly");
341 assert_eq!(
342 weekdays["recurrence"]["pattern"]["daysOfWeek"],
343 json!(["monday", "tuesday", "wednesday", "thursday", "friday"])
344 );
345 let weekly = new_event_body(&event(Repeat::Weekly));
346 assert_eq!(
347 weekly["recurrence"]["pattern"]["daysOfWeek"],
348 json!(["wednesday"])
349 );
350 }
351
352 #[test]
353 fn the_created_event_carries_its_id_and_join_link() {
354 let body =
355 json!({"id": "AAMk", "onlineMeeting": {"joinUrl": "https://example.invalid/join"}});
356 assert_eq!(
357 parse_created_event(&body),
358 Some(CreatedEvent {
359 id: "AAMk".into(),
360 join_url: Some("https://example.invalid/join".into()),
361 })
362 );
363 assert_eq!(parse_created_event(&json!({})), None);
364 }
365
366 #[tokio::test]
367 async fn create_event_posts_to_graph_events() {
368 let calendar =
369 Calendar::with_transport(Scripted::new(vec![(201, json!({"id": "AAMk"}))]), "emea");
370 let created = calendar.create_event(&event(Repeat::Never)).await.unwrap();
371 assert_eq!(created.id, "AAMk");
372 let sent = calendar.transport.sent.lock().unwrap();
373 assert_eq!(sent[0].0, Method::Post);
374 assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events");
375 }
376
377 #[tokio::test]
378 async fn create_event_failure_carries_the_service_message() {
379 let calendar = Calendar::with_transport(
380 Scripted::new(vec![(403, json!({"error": {"message": "Access denied"}}))]),
381 "emea",
382 );
383 let error = calendar
384 .create_event(&event(Repeat::Never))
385 .await
386 .unwrap_err();
387 assert!(error.to_string().contains("Access denied"));
388 }
389
390 #[tokio::test]
391 async fn respond_posts_the_reply_with_the_send_flag() {
392 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
393 calendar
394 .respond("AAMk=", None, Reply::Tentative, false)
395 .await
396 .unwrap();
397 let sent = calendar.transport.sent.lock().unwrap();
398 assert_eq!(
399 sent[0].1,
400 "https://graph.microsoft.com/v1.0/me/events/AAMk%3D/tentativelyAccept"
401 );
402 assert_eq!(
403 sent[0].2,
404 Some(json!({"comment": "", "sendResponse": false}))
405 );
406 }
407
408 #[tokio::test]
409 async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {
410 let calendar = Calendar::with_transport(
411 Scripted::new(vec![
412 (404, json!({"error": {"message": "not found"}})),
413 (200, json!({"value": [{"id": "graph-id"}]})),
414 (202, Value::Null),
415 ]),
416 "emea",
417 );
418 calendar
419 .respond("mt-id", Some("uid-1"), Reply::Decline, true)
420 .await
421 .unwrap();
422 let sent = calendar.transport.sent.lock().unwrap();
423 assert!(sent[1].1.contains("iCalUId%20eq%20'uid-1'"));
424 assert!(sent[2].1.ends_with("/graph-id/decline"));
425 }
426
427 #[tokio::test]
428 async fn a_missing_event_without_an_ical_uid_fails() {
429 let calendar = Calendar::with_transport(
430 Scripted::new(vec![(404, json!({"error": {"message": "not found"}}))]),
431 "emea",
432 );
433 assert!(
434 calendar
435 .respond("mt-id", None, Reply::Accept, true)
436 .await
437 .is_err()
438 );
439 }
440 }
@@ -0,0 +1,440 @@
1use chrono::{DateTime, Datelike, Utc, Weekday};
2use serde_json::{Value, json};
3use session::{GRAPH, Method, Request, Scope};
4
5use super::Calendar;
6use crate::cards::CardTransport;
7use crate::error::{Error, Result};
8use crate::messages::encode;
9
10const CALENDARS_SCOPE: &str = "Calendars.ReadWrite";
11const GRAPH_TIME_FORMAT: &str = "%Y-%m-%dT%H:%M:%S";
12const GRAPH_DATE_FORMAT: &str = "%Y-%m-%d";
13const TIME_ZONE: &str = "UTC";
14const ONLINE_PROVIDER: &str = "teamsForBusiness";
15const NOT_FOUND: u16 = 404;
16const WORK_WEEK: [Weekday; 5] = [
17 Weekday::Mon,
18 Weekday::Tue,
19 Weekday::Wed,
20 Weekday::Thu,
21 Weekday::Fri,
22];
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub enum Repeat {
26 #[default]
27 Never,
28 Daily,
29 Weekdays,
30 Weekly,
31}
32
33impl Repeat {
34 pub const ALL: [Repeat; 4] = [
35 Repeat::Never,
36 Repeat::Daily,
37 Repeat::Weekdays,
38 Repeat::Weekly,
39 ];
40
41 pub fn label(self) -> &'static str {
42 match self {
43 Repeat::Never => "Does not repeat",
44 Repeat::Daily => "Daily",
45 Repeat::Weekdays => "Weekdays",
46 Repeat::Weekly => "Weekly",
47 }
48 }
49}
50
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Attendee {
53 pub name: String,
54 pub address: String,
55}
56
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct NewEvent {
59 pub subject: String,
60 pub start: DateTime<Utc>,
61 pub end: DateTime<Utc>,
62 pub attendees: Vec<Attendee>,
63 pub repeat: Repeat,
64 pub details: String,
65}
66
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct CreatedEvent {
69 pub id: String,
70 pub join_url: Option<String>,
71}
72
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Reply {
75 Accept,
76 Tentative,
77 Decline,
78}
79
80impl Reply {
81 fn action(self) -> &'static str {
82 match self {
83 Reply::Accept => "accept",
84 Reply::Tentative => "tentativelyAccept",
85 Reply::Decline => "decline",
86 }
87 }
88}
89
90fn day_name(weekday: Weekday) -> &'static str {
91 match weekday {
92 Weekday::Mon => "monday",
93 Weekday::Tue => "tuesday",
94 Weekday::Wed => "wednesday",
95 Weekday::Thu => "thursday",
96 Weekday::Fri => "friday",
97 Weekday::Sat => "saturday",
98 Weekday::Sun => "sunday",
99 }
100}
101
102fn graph_time(time: DateTime<Utc>) -> Value {
103 json!({
104 "dateTime": time.format(GRAPH_TIME_FORMAT).to_string(),
105 "timeZone": TIME_ZONE,
106 })
107}
108
109fn recurrence(repeat: Repeat, start: DateTime<Utc>) -> Option<Value> {
110 let (pattern_type, days): (&str, Vec<Weekday>) = match repeat {
111 Repeat::Never => return None,
112 Repeat::Daily => ("daily", Vec::new()),
113 Repeat::Weekdays => ("weekly", WORK_WEEK.to_vec()),
114 Repeat::Weekly => ("weekly", vec![start.weekday()]),
115 };
116 let mut pattern = json!({"type": pattern_type, "interval": 1});
117 if !days.is_empty() {
118 pattern["daysOfWeek"] = days.into_iter().map(day_name).collect();
119 pattern["firstDayOfWeek"] = json!("monday");
120 }
121 Some(json!({
122 "pattern": pattern,
123 "range": {
124 "type": "noEnd",
125 "startDate": start.format(GRAPH_DATE_FORMAT).to_string(),
126 },
127 }))
128}
129
130pub fn new_event_body(event: &NewEvent) -> Value {
131 let mut body = json!({
132 "subject": event.subject,
133 "start": graph_time(event.start),
134 "end": graph_time(event.end),
135 "attendees": event.attendees.iter().map(|attendee| json!({
136 "type": "required",
137 "emailAddress": {"address": attendee.address, "name": attendee.name},
138 })).collect::<Vec<_>>(),
139 "isOnlineMeeting": true,
140 "onlineMeetingProvider": ONLINE_PROVIDER,
141 });
142 if !event.details.trim().is_empty() {
143 body["body"] = json!({"contentType": "text", "content": event.details});
144 }
145 if let Some(recurrence) = recurrence(event.repeat, event.start) {
146 body["recurrence"] = recurrence;
147 }
148 body
149}
150
151pub fn parse_created_event(body: &Value) -> Option<CreatedEvent> {
152 Some(CreatedEvent {
153 id: body.get("id")?.as_str()?.to_owned(),
154 join_url: body
155 .pointer("/onlineMeeting/joinUrl")
156 .and_then(Value::as_str)
157 .map(str::to_owned),
158 })
159}
160
161fn events_url() -> String {
162 format!("{GRAPH}/v1.0/me/events")
163}
164
165fn reply_url(event_id: &str, reply: Reply) -> String {
166 format!("{}/{}/{}", events_url(), encode(event_id), reply.action())
167}
168
169fn lookup_url(ical_uid: &str) -> String {
170 format!(
171 "{}?$filter={}&$select=id&$top=1",
172 events_url(),
173 encode(&format!("iCalUId eq '{}'", ical_uid.replace('\'', "''")))
174 )
175}
176
177fn api_error(answer: session::ApiResponse, url: &str) -> Error {
178 Error::Session(session::Error::api(answer.status, url, answer.body))
179}
180
181impl<T: CardTransport> Calendar<T> {
182 pub async fn create_event(&self, event: &NewEvent) -> Result<CreatedEvent> {
183 let url = events_url();
184 let request = Request::with_body(Method::Post, &url, new_event_body(event));
185 let answer = self
186 .transport
187 .send(request, Scope::graph(CALENDARS_SCOPE))
188 .await?;
189 if !answer.is_success() {
190 return Err(api_error(answer, &url));
191 }
192 parse_created_event(&answer.body).ok_or_else(|| api_error(answer, &url))
193 }
194
195 pub async fn respond(
196 &self,
197 event_id: &str,
198 ical_uid: Option<&str>,
199 reply: Reply,
200 send_response: bool,
201 ) -> Result<()> {
202 let answer = self.send_reply(event_id, reply, send_response).await?;
203 if answer.is_success() {
204 return Ok(());
205 }
206 let Some(ical_uid) = ical_uid.filter(|_| answer.status == NOT_FOUND) else {
207 return Err(api_error(answer, &reply_url(event_id, reply)));
208 };
209 let graph_id = self.graph_event_id(ical_uid).await?;
210 let retried = self.send_reply(&graph_id, reply, send_response).await?;
211 if retried.is_success() {
212 return Ok(());
213 }
214 Err(api_error(retried, &reply_url(&graph_id, reply)))
215 }
216
217 async fn send_reply(
218 &self,
219 event_id: &str,
220 reply: Reply,
221 send_response: bool,
222 ) -> Result<session::ApiResponse> {
223 let request = Request::with_body(
224 Method::Post,
225 reply_url(event_id, reply),
226 json!({"comment": "", "sendResponse": send_response}),
227 );
228 self.transport
229 .send(request, Scope::graph(CALENDARS_SCOPE))
230 .await
231 }
232
233 async fn graph_event_id(&self, ical_uid: &str) -> Result<String> {
234 let url = lookup_url(ical_uid);
235 let answer = self
236 .transport
237 .send(Request::get(&url), Scope::graph(CALENDARS_SCOPE))
238 .await?;
239 if !answer.is_success() {
240 return Err(api_error(answer, &url));
241 }
242 answer
243 .body
244 .pointer("/value/0/id")
245 .and_then(Value::as_str)
246 .map(str::to_owned)
247 .ok_or_else(|| api_error(answer, &url))
248 }
249}
250
251#[cfg(test)]
252mod tests {
253 use std::sync::Mutex;
254
255 use chrono::TimeZone;
256
257 use super::*;
258 use crate::calendar::Calendar;
259
260 struct Scripted {
261 answers: Mutex<Vec<(u16, Value)>>,
262 sent: Mutex<Vec<(Method, String, Option<Value>)>>,
263 }
264
265 impl Scripted {
266 fn new(answers: Vec<(u16, Value)>) -> Self {
267 Scripted {
268 answers: Mutex::new(answers),
269 sent: Mutex::new(Vec::new()),
270 }
271 }
272 }
273
274 impl CardTransport for Scripted {
275 async fn send(&self, request: Request, scope: Scope) -> Result<session::ApiResponse> {
276 assert_eq!(scope, Scope::graph(CALENDARS_SCOPE));
277 self.sent
278 .lock()
279 .unwrap()
280 .push((request.method, request.url, request.body));
281 let (status, body) = self.answers.lock().unwrap().remove(0);
282 Ok(session::ApiResponse {
283 status,
284 body,
285 retry_after: None,
286 })
287 }
288 }
289
290 fn event(repeat: Repeat) -> NewEvent {
291 NewEvent {
292 subject: "Planning".into(),
293 start: Utc.with_ymd_and_hms(2026, 10, 14, 9, 30, 0).unwrap(),
294 end: Utc.with_ymd_and_hms(2026, 10, 14, 10, 0, 0).unwrap(),
295 attendees: vec![Attendee {
296 name: "Mara Lindqvist".into(),
297 address: "mara@example.invalid".into(),
298 }],
299 repeat,
300 details: String::new(),
301 }
302 }
303
304 #[test]
305 fn the_body_asks_for_a_teams_meeting_with_utc_times() {
306 let body = new_event_body(&event(Repeat::Never));
307 assert_eq!(body["subject"], "Planning");
308 assert_eq!(body["isOnlineMeeting"], true);
309 assert_eq!(body["onlineMeetingProvider"], "teamsForBusiness");
310 assert_eq!(body["start"]["dateTime"], "2026-10-14T09:30:00");
311 assert_eq!(body["start"]["timeZone"], "UTC");
312 assert_eq!(body["end"]["dateTime"], "2026-10-14T10:00:00");
313 assert_eq!(body["attendees"][0]["type"], "required");
314 assert_eq!(
315 body["attendees"][0]["emailAddress"]["address"],
316 "mara@example.invalid"
317 );
318 assert!(body.get("recurrence").is_none());
319 assert!(body.get("body").is_none());
320 }
321
322 #[test]
323 fn details_become_a_plain_text_body() {
324 let body = new_event_body(&NewEvent {
325 details: "Agenda: roadmap".into(),
326 ..event(Repeat::Never)
327 });
328 assert_eq!(body["body"]["contentType"], "text");
329 assert_eq!(body["body"]["content"], "Agenda: roadmap");
330 }
331
332 #[test]
333 fn recurrence_maps_to_graph_patterns() {
334 let daily = new_event_body(&event(Repeat::Daily));
335 assert_eq!(daily["recurrence"]["pattern"]["type"], "daily");
336 assert_eq!(daily["recurrence"]["pattern"]["interval"], 1);
337 assert_eq!(daily["recurrence"]["range"]["type"], "noEnd");
338 assert_eq!(daily["recurrence"]["range"]["startDate"], "2026-10-14");
339 let weekdays = new_event_body(&event(Repeat::Weekdays));
340 assert_eq!(weekdays["recurrence"]["pattern"]["type"], "weekly");
341 assert_eq!(
342 weekdays["recurrence"]["pattern"]["daysOfWeek"],
343 json!(["monday", "tuesday", "wednesday", "thursday", "friday"])
344 );
345 let weekly = new_event_body(&event(Repeat::Weekly));
346 assert_eq!(
347 weekly["recurrence"]["pattern"]["daysOfWeek"],
348 json!(["wednesday"])
349 );
350 }
351
352 #[test]
353 fn the_created_event_carries_its_id_and_join_link() {
354 let body =
355 json!({"id": "AAMk", "onlineMeeting": {"joinUrl": "https://example.invalid/join"}});
356 assert_eq!(
357 parse_created_event(&body),
358 Some(CreatedEvent {
359 id: "AAMk".into(),
360 join_url: Some("https://example.invalid/join".into()),
361 })
362 );
363 assert_eq!(parse_created_event(&json!({})), None);
364 }
365
366 #[tokio::test]
367 async fn create_event_posts_to_graph_events() {
368 let calendar =
369 Calendar::with_transport(Scripted::new(vec![(201, json!({"id": "AAMk"}))]), "emea");
370 let created = calendar.create_event(&event(Repeat::Never)).await.unwrap();
371 assert_eq!(created.id, "AAMk");
372 let sent = calendar.transport.sent.lock().unwrap();
373 assert_eq!(sent[0].0, Method::Post);
374 assert_eq!(sent[0].1, "https://graph.microsoft.com/v1.0/me/events");
375 }
376
377 #[tokio::test]
378 async fn create_event_failure_carries_the_service_message() {
379 let calendar = Calendar::with_transport(
380 Scripted::new(vec![(403, json!({"error": {"message": "Access denied"}}))]),
381 "emea",
382 );
383 let error = calendar
384 .create_event(&event(Repeat::Never))
385 .await
386 .unwrap_err();
387 assert!(error.to_string().contains("Access denied"));
388 }
389
390 #[tokio::test]
391 async fn respond_posts_the_reply_with_the_send_flag() {
392 let calendar = Calendar::with_transport(Scripted::new(vec![(202, Value::Null)]), "emea");
393 calendar
394 .respond("AAMk=", None, Reply::Tentative, false)
395 .await
396 .unwrap();
397 let sent = calendar.transport.sent.lock().unwrap();
398 assert_eq!(
399 sent[0].1,
400 "https://graph.microsoft.com/v1.0/me/events/AAMk%3D/tentativelyAccept"
401 );
402 assert_eq!(
403 sent[0].2,
404 Some(json!({"comment": "", "sendResponse": false}))
405 );
406 }
407
408 #[tokio::test]
409 async fn an_unknown_id_is_looked_up_by_its_ical_uid_once() {
410 let calendar = Calendar::with_transport(
411 Scripted::new(vec![
412 (404, json!({"error": {"message": "not found"}})),
413 (200, json!({"value": [{"id": "graph-id"}]})),
414 (202, Value::Null),
415 ]),
416 "emea",
417 );
418 calendar
419 .respond("mt-id", Some("uid-1"), Reply::Decline, true)
420 .await
421 .unwrap();
422 let sent = calendar.transport.sent.lock().unwrap();
423 assert!(sent[1].1.contains("iCalUId%20eq%20'uid-1'"));
424 assert!(sent[2].1.ends_with("/graph-id/decline"));
425 }
426
427 #[tokio::test]
428 async fn a_missing_event_without_an_ical_uid_fails() {
429 let calendar = Calendar::with_transport(
430 Scripted::new(vec![(404, json!({"error": {"message": "not found"}}))]),
431 "emea",
432 );
433 assert!(
434 calendar
435 .respond("mt-id", None, Reply::Accept, true)
436 .await
437 .is_err()
438 );
439 }
440}
crates/chatsvc/src/lib.rs +4 −1
@@ -23,7 +23,10 @@ pub mod transcripts;
23 23 pub mod translate;
24 24 pub mod window;
25 25
26 pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
26 pub use calendar::{
27 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Repeat, Reply, ResponseType,
28 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
29 };
27 30 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
28 31 pub use cards::{
29 32 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -23,7 +23,10 @@ pub mod transcripts;
23pub mod translate;
23pub mod translate;
24pub mod window;
24pub mod window;
25
25
26pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
26pub use calendar::{
27 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Repeat, Reply, ResponseType,
28 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
29};
27pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
30pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
28pub use cards::{
31pub use cards::{
29 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
32 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
crates/graph/src/profile.rs +31 −0
@@ -60,6 +60,13 @@ impl Graph {
60 60 parse_profile_details(&requests[0].url, profile, manager, reports)
61 61 }
62 62
63 pub async fn user_mail(&self, user_id: &str) -> Result<Option<String>> {
64 let body = self
65 .get(&urls::user_mail(user_id), &Scope::graph(PROFILE_SCOPE))
66 .await?;
67 Ok(parse_mail(&body))
68 }
69
63 70 pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> {
64 71 let body = schedule_body(mail, Utc::now());
65 72 let answer = self
@@ -114,6 +121,15 @@ fn schedule_body(mail: &str, now: DateTime<Utc>) -> Value {
114 121 })
115 122 }
116 123
124 fn parse_mail(body: &Value) -> Option<String> {
125 ["mail", "userPrincipalName"]
126 .iter()
127 .filter_map(|key| body.get(key)?.as_str())
128 .map(str::trim)
129 .find(|address| !address.is_empty())
130 .map(str::to_owned)
131 }
132
117 133 fn parse_time_zone_name(body: &Value) -> Option<String> {
118 134 let name = body
119 135 .pointer("/value/0/workingHours/timeZone/name")?
@@ -140,6 +156,21 @@ mod tests {
140 156 Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
141 157 }
142 158
159 #[test]
160 fn the_mail_falls_back_to_the_user_principal_name() {
161 assert_eq!(
162 parse_mail(&json!({"mail": null, "userPrincipalName": "bea@example.invalid"})),
163 Some("bea@example.invalid".to_owned())
164 );
165 assert_eq!(
166 parse_mail(
167 &json!({"mail": "a@example.invalid", "userPrincipalName": "b@example.invalid"})
168 ),
169 Some("a@example.invalid".to_owned())
170 );
171 assert_eq!(parse_mail(&json!({"mail": " "})), None);
172 }
173
143 174 #[test]
144 175 fn profile_details_parse_fields_manager_and_reports() {
145 176 let profile = json!({
@@ -60,6 +60,13 @@ impl Graph {
60 parse_profile_details(&requests[0].url, profile, manager, reports)
60 parse_profile_details(&requests[0].url, profile, manager, reports)
61 }
61 }
62
62
63 pub async fn user_mail(&self, user_id: &str) -> Result<Option<String>> {
64 let body = self
65 .get(&urls::user_mail(user_id), &Scope::graph(PROFILE_SCOPE))
66 .await?;
67 Ok(parse_mail(&body))
68 }
69
63 pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> {
70 pub async fn time_zone_name(&self, mail: &str) -> Result<Option<String>> {
64 let body = schedule_body(mail, Utc::now());
71 let body = schedule_body(mail, Utc::now());
65 let answer = self
72 let answer = self
@@ -114,6 +121,15 @@ fn schedule_body(mail: &str, now: DateTime<Utc>) -> Value {
114 })
121 })
115}
122}
116
123
124fn parse_mail(body: &Value) -> Option<String> {
125 ["mail", "userPrincipalName"]
126 .iter()
127 .filter_map(|key| body.get(key)?.as_str())
128 .map(str::trim)
129 .find(|address| !address.is_empty())
130 .map(str::to_owned)
131}
132
117fn parse_time_zone_name(body: &Value) -> Option<String> {
133fn parse_time_zone_name(body: &Value) -> Option<String> {
118 let name = body
134 let name = body
119 .pointer("/value/0/workingHours/timeZone/name")?
135 .pointer("/value/0/workingHours/timeZone/name")?
@@ -140,6 +156,21 @@ mod tests {
140 Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
156 Utc.with_ymd_and_hms(2026, 10, 9, 12, 0, 0).unwrap()
141 }
157 }
142
158
159 #[test]
160 fn the_mail_falls_back_to_the_user_principal_name() {
161 assert_eq!(
162 parse_mail(&json!({"mail": null, "userPrincipalName": "bea@example.invalid"})),
163 Some("bea@example.invalid".to_owned())
164 );
165 assert_eq!(
166 parse_mail(
167 &json!({"mail": "a@example.invalid", "userPrincipalName": "b@example.invalid"})
168 ),
169 Some("a@example.invalid".to_owned())
170 );
171 assert_eq!(parse_mail(&json!({"mail": " "})), None);
172 }
173
143 #[test]
174 #[test]
144 fn profile_details_parse_fields_manager_and_reports() {
175 fn profile_details_parse_fields_manager_and_reports() {
145 let profile = json!({
176 let profile = json!({
crates/graph/src/urls.rs +7 −0
@@ -31,6 +31,13 @@ pub fn user_profile(user_id: &str) -> String {
31 31 )
32 32 }
33 33
34 pub fn user_mail(user_id: &str) -> String {
35 format!(
36 "{GRAPH}/v1.0/users/{}?$select=mail,userPrincipalName",
37 segment(user_id)
38 )
39 }
40
34 41 pub fn user_manager(user_id: &str) -> String {
35 42 format!(
36 43 "{GRAPH}/v1.0/users/{}/manager?$select=id,displayName,jobTitle",
@@ -31,6 +31,13 @@ pub fn user_profile(user_id: &str) -> String {
31 )
31 )
32}
32}
33
33
34pub fn user_mail(user_id: &str) -> String {
35 format!(
36 "{GRAPH}/v1.0/users/{}?$select=mail,userPrincipalName",
37 segment(user_id)
38 )
39}
40
34pub fn user_manager(user_id: &str) -> String {
41pub fn user_manager(user_id: &str) -> String {
35 format!(
42 format!(
36 "{GRAPH}/v1.0/users/{}/manager?$select=id,displayName,jobTitle",
43 "{GRAPH}/v1.0/users/{}/manager?$select=id,displayName,jobTitle",