BlueGit

ict rusty-teams

feat(meetings): schedule meetings, RSVP, start reminder and pre-join screen

- Calls tab "New meeting": title, people chips, date, start, end, repeat, details; Graph POST /me/events with a Teams meeting; errors inline
- Upcoming: Accept / Tentative / Decline menu with "Send a response" for invited meetings, "Organizer" for own ones
- Meeting reminder toast 5 min before and at the start, Dismiss and Join, Ctrl+Shift+J, quiet during Do not disturb and calls
- Pre-join screen in the chat pane: preview, camera and mic, background, devices, "Don't use audio" (new DisableAudio engine command)
- Demo data for all four; layout guard tags for the Calls actions and the pre-join regions

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

metis Daniel Däschle · pushed by metis

Authored 2026-10-13 · 7 weeks ago

Hash
e18f5738ffcfe5d42be3d522f25591aaa6030689
Parent
46ed3a3c
38 files changed +3053 −172
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, 14 partial, 4 missing of 99). 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) | 62 % | 4 | 13 | 0 |
21 | [Calls and meetings](#calls-and-meetings) | 60 % | 4 | 17 | 0 |
22 22
23 23 ## Next
24 24
@@ -138,7 +138,7 @@ Feature parity with the Microsoft Teams desktop client.
138 138 | Full-text search over cached messages | Done | |
139 139 | Jump to a message from search | Done | |
140 140 | Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
141 | 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 screen, M mute; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
141 | 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 screen, M mute, J join from a meeting reminder; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
142 142
143 143 ## Presence and people
144 144
@@ -179,6 +179,10 @@ Feature parity with the Microsoft Teams desktop client.
179 179 | 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 |
180 180 | 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) |
181 181 | 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 |
182 | 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 |
183 | 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 |
184 | 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) |
185 | 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 |
182 186
183 187 ## Agents
184 188
@@ -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, 14 partial, 4 missing of 99). 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) | 62 % | 4 | 13 | 0 |
21| [Calls and meetings](#calls-and-meetings) | 60 % | 4 | 17 | 0 |
22
22
23## Next
23## Next
24
24
@@ -138,7 +138,7 @@ Feature parity with the Microsoft Teams desktop client.
138| Full-text search over cached messages | Done | |
138| Full-text search over cached messages | Done | |
139| Jump to a message from search | Done | |
139| Jump to a message from search | Done | |
140| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
140| Esc closes the open conversation or editor | Done | Back to the channel keeps the feed position |
141| 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 screen, M mute; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
141| 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 screen, M mute, J join from a meeting reminder; Ctrl+. lists all shortcuts. Ctrl+5..9 not used |
142
142
143## Presence and people
143## Presence and people
144
144
@@ -179,6 +179,10 @@ Feature parity with the Microsoft Teams desktop client.
179| 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 |
179| 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 |
180| 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) |
180| 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) |
181| 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 |
181| 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 |
182| 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 |
183| 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 |
184| 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) |
185| 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 |
182
186
183## Agents
187## Agents
184
188
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)]
@@ -127,6 +128,12 @@ pub struct AppState {
127 128 pub call_background: crate::call::BackgroundPick,
128 129 pub call_camera: calling::DeviceChoice,
129 130 pub meet_now_pending: bool,
131 pub prejoin: Option<crate::call::PendingJoin>,
132 pub prejoin_count: u64,
133 pub join_options: crate::call::JoinOptions,
134 pub rsvp_send_response: bool,
135 pub meeting_toasts: crate::call::MeetingToasts,
136 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
130 137 pub call_backgrounds: crate::call::BackgroundLibrary,
131 138 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
132 139 pub rings: Rings,
@@ -224,6 +231,12 @@ impl AppState {
224 231 call_background: crate::call::BackgroundPick::None,
225 232 call_camera: calling::DeviceChoice::SystemDefault,
226 233 meet_now_pending: false,
234 prejoin: None,
235 prejoin_count: 0,
236 join_options: crate::call::JoinOptions::default(),
237 rsvp_send_response: true,
238 meeting_toasts: crate::call::MeetingToasts::default(),
239 demo_meetings: Vec::new(),
227 240 call_backgrounds: if mode.demo {
228 241 crate::call::demo_library()
229 242 } else {
@@ -241,6 +254,7 @@ impl AppState {
241 254 state.call_share_sound = crate::call::load_share_sound(&state.store);
242 255 state.call_background = crate::call::load_background(&state.store);
243 256 state.call_camera = crate::call::load_camera(&state.store);
257 state.join_options = crate::call::load_join_options(&state.store);
244 258 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
245 259 state.load_cached_translation_settings();
246 260 if !mode.demo {
@@ -656,6 +670,7 @@ impl AppState {
656 670
657 671 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
658 672 self.show_call(false, cx);
673 self.cancel_prejoin(cx);
659 674 let was_drafting = std::mem::take(&mut self.new_chat);
660 675 if !was_drafting && self.selection.as_ref() == Some(&selection) {
661 676 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)]
@@ -127,6 +128,12 @@ pub struct AppState {
127 pub call_background: crate::call::BackgroundPick,
128 pub call_background: crate::call::BackgroundPick,
128 pub call_camera: calling::DeviceChoice,
129 pub call_camera: calling::DeviceChoice,
129 pub meet_now_pending: bool,
130 pub meet_now_pending: bool,
131 pub prejoin: Option<crate::call::PendingJoin>,
132 pub prejoin_count: u64,
133 pub join_options: crate::call::JoinOptions,
134 pub rsvp_send_response: bool,
135 pub meeting_toasts: crate::call::MeetingToasts,
136 pub demo_meetings: Vec<chatsvc::CalendarEvent>,
130 pub call_backgrounds: crate::call::BackgroundLibrary,
137 pub call_backgrounds: crate::call::BackgroundLibrary,
131 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
138 pub transfer_picker: Option<Entity<crate::views::transfer_picker::TransferPicker>>,
132 pub rings: Rings,
139 pub rings: Rings,
@@ -224,6 +231,12 @@ impl AppState {
224 call_background: crate::call::BackgroundPick::None,
231 call_background: crate::call::BackgroundPick::None,
225 call_camera: calling::DeviceChoice::SystemDefault,
232 call_camera: calling::DeviceChoice::SystemDefault,
226 meet_now_pending: false,
233 meet_now_pending: false,
234 prejoin: None,
235 prejoin_count: 0,
236 join_options: crate::call::JoinOptions::default(),
237 rsvp_send_response: true,
238 meeting_toasts: crate::call::MeetingToasts::default(),
239 demo_meetings: Vec::new(),
227 call_backgrounds: if mode.demo {
240 call_backgrounds: if mode.demo {
228 crate::call::demo_library()
241 crate::call::demo_library()
229 } else {
242 } else {
@@ -241,6 +254,7 @@ impl AppState {
241 state.call_share_sound = crate::call::load_share_sound(&state.store);
254 state.call_share_sound = crate::call::load_share_sound(&state.store);
242 state.call_background = crate::call::load_background(&state.store);
255 state.call_background = crate::call::load_background(&state.store);
243 state.call_camera = crate::call::load_camera(&state.store);
256 state.call_camera = crate::call::load_camera(&state.store);
257 state.join_options = crate::call::load_join_options(&state.store);
244 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
258 state.call_backgrounds.customs = crate::call::load_custom_backgrounds(&state.store);
245 state.load_cached_translation_settings();
259 state.load_cached_translation_settings();
246 if !mode.demo {
260 if !mode.demo {
@@ -656,6 +670,7 @@ impl AppState {
656
670
657 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
671 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
658 self.show_call(false, cx);
672 self.show_call(false, cx);
673 self.cancel_prejoin(cx);
659 let was_drafting = std::mem::take(&mut self.new_chat);
674 let was_drafting = std::mem::take(&mut self.new_chat);
660 if !was_drafting && self.selection.as_ref() == Some(&selection) {
675 if !was_drafting && self.selection.as_ref() == Some(&selection) {
661 return;
676 return;
crates/app/src/call/actions.rs +15 −16
@@ -17,6 +17,7 @@ use super::demo::{
17 17 use super::features::room_closed_move;
18 18 use super::media::CallMedia;
19 19 use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
20 use super::prejoin::{DemoMeeting, MeetingJoin};
20 21 use super::ring::{MissedCall, RingOutcome};
21 22 use super::target::{is_organizer, plan_for_chat};
22 23 use crate::app_state::{AppEvent, AppState, Selection, chat_title};
@@ -143,28 +144,26 @@ impl AppState {
143 144 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
144 145 return;
145 146 };
146 let guests = if conversation_id == DEMO_LOBBY_MEETING {
147 DEMO_SMALL_MEETING
148 } else {
149 DEMO_CROWD
150 };
151 let demo = DemoCall::Meeting {
152 guests: demo_guests(guests),
147 let demo = DemoMeeting {
148 guests: if conversation_id == DEMO_LOBBY_MEETING {
149 DEMO_SMALL_MEETING
150 } else {
151 DEMO_CROWD
152 },
153 153 lobby: conversation_id == DEMO_LOBBY_MEETING,
154 154 organizer: conversation_id != DEMO_LOBBY_MEETING,
155 155 };
156 let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, false, cx)
157 else {
158 return;
159 };
160 156 let title = selection_for(&self.sidebar, conversation_id)
161 157 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
162 158 .unwrap_or_else(|| "Meeting".to_owned());
163 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
164 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
165 if let Some(call) = self.call.as_mut() {
166 call.meeting_target = Some(target);
167 }
159 let join = MeetingJoin {
160 organizer: is_organizer(&meeting, self.directory.me.as_ref()),
161 conversation_id: Some(conversation_id.to_owned()),
162 target,
163 title,
164 demo,
165 };
166 self.stage_meeting_join(join, cx);
168 167 }
169 168
170 169 pub(super) fn place_call(
@@ -17,6 +17,7 @@ use super::demo::{
17use super::features::room_closed_move;
17use super::features::room_closed_move;
18use super::media::CallMedia;
18use super::media::CallMedia;
19use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
19use super::model::{ActiveCall, CallKind, CallModel, ended_notice};
20use super::prejoin::{DemoMeeting, MeetingJoin};
20use super::ring::{MissedCall, RingOutcome};
21use super::ring::{MissedCall, RingOutcome};
21use super::target::{is_organizer, plan_for_chat};
22use super::target::{is_organizer, plan_for_chat};
22use crate::app_state::{AppEvent, AppState, Selection, chat_title};
23use crate::app_state::{AppEvent, AppState, Selection, chat_title};
@@ -143,28 +144,26 @@ impl AppState {
143 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
144 self.raise_notice(MEETING_UNAVAILABLE_NOTICE.to_owned(), None, cx);
144 return;
145 return;
145 };
146 };
146 let guests = if conversation_id == DEMO_LOBBY_MEETING {
147 let demo = DemoMeeting {
147 DEMO_SMALL_MEETING
148 guests: if conversation_id == DEMO_LOBBY_MEETING {
148 } else {
149 DEMO_SMALL_MEETING
149 DEMO_CROWD
150 } else {
150 };
151 DEMO_CROWD
151 let demo = DemoCall::Meeting {
152 },
152 guests: demo_guests(guests),
153 lobby: conversation_id == DEMO_LOBBY_MEETING,
153 lobby: conversation_id == DEMO_LOBBY_MEETING,
154 organizer: conversation_id != DEMO_LOBBY_MEETING,
154 organizer: conversation_id != DEMO_LOBBY_MEETING,
155 };
155 };
156 let Some(handle) = self.place_call(CallSpec::Meeting(target.clone()), demo, false, cx)
157 else {
158 return;
159 };
160 let title = selection_for(&self.sidebar, conversation_id)
156 let title = selection_for(&self.sidebar, conversation_id)
161 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
157 .map(|selection| crate::app_state::selection_title(&self.sidebar, &selection))
162 .unwrap_or_else(|| "Meeting".to_owned());
158 .unwrap_or_else(|| "Meeting".to_owned());
163 let model = CallModel::meeting(&title, is_organizer(&meeting, self.directory.me.as_ref()));
159 let join = MeetingJoin {
164 self.begin_call(handle, model, Some(conversation_id.to_owned()), cx);
160 organizer: is_organizer(&meeting, self.directory.me.as_ref()),
165 if let Some(call) = self.call.as_mut() {
161 conversation_id: Some(conversation_id.to_owned()),
166 call.meeting_target = Some(target);
162 target,
167 }
163 title,
164 demo,
165 };
166 self.stage_meeting_join(join, cx);
168 }
167 }
169
168
170 pub(super) fn place_call(
169 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
@@ -458,6 +458,10 @@ async fn speak_until_hangup(
458 458 muted = command.target(muted);
459 459 control.send(CallUpdate::Muted(muted));
460 460 }
461 Some(CallCommand::DisableAudio) => {
462 muted = true;
463 control.send(CallUpdate::Muted(muted));
464 }
461 465 Some(CallCommand::SelectInput(choice)) => {
462 466 input = choice;
463 467 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
@@ -458,6 +458,10 @@ async fn speak_until_hangup(
458 muted = command.target(muted);
458 muted = command.target(muted);
459 control.send(CallUpdate::Muted(muted));
459 control.send(CallUpdate::Muted(muted));
460 }
460 }
461 Some(CallCommand::DisableAudio) => {
462 muted = true;
463 control.send(CallUpdate::Muted(muted));
464 }
461 Some(CallCommand::SelectInput(choice)) => {
465 Some(CallCommand::SelectInput(choice)) => {
462 input = choice;
466 input = choice;
463 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
467 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
@@ -14,12 +14,15 @@ mod model;
14 14 mod overlay;
15 15 mod overlay_layout;
16 16 mod pictures;
17 mod prejoin;
17 18 mod preview;
19 mod reminder;
18 20 mod ring;
21 mod schedule;
19 22 mod target;
20 23
21 24 pub use actions::{load_camera, load_share_sound};
22 pub use agenda::{AgendaRow, fetch_window, join_available};
25 pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
23 26 pub use background::{
24 27 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
25 28 load_custom_backgrounds,
@@ -38,6 +41,9 @@ pub use model::{
38 41 REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size,
39 42 };
40 43 pub use overlay::CallWindows;
44 pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
41 45 pub use preview::{CameraPreview, preview_backgrounds};
46 pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
42 47 pub use ring::{MissedCall, RingEntry, Rings};
48 pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
43 49 pub use target::plan_for_chat;
@@ -14,12 +14,15 @@ mod model;
14mod overlay;
14mod overlay;
15mod overlay_layout;
15mod overlay_layout;
16mod pictures;
16mod pictures;
17mod prejoin;
17mod preview;
18mod preview;
19mod reminder;
18mod ring;
20mod ring;
21mod schedule;
19mod target;
22mod target;
20
23
21pub use actions::{load_camera, load_share_sound};
24pub use actions::{load_camera, load_share_sound};
22pub use agenda::{AgendaRow, fetch_window, join_available};
25pub use agenda::{AgendaRow, fetch_window, join_available, response_label};
23pub use background::{
26pub use background::{
24 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
27 BackgroundLibrary, BackgroundPick, default_cache_directory, demo_library, load_background,
25 load_custom_backgrounds,
28 load_custom_backgrounds,
@@ -38,6 +41,9 @@ pub use model::{
38 REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size,
41 REACTION_SHOWN, Tile, TileSize, TileState, grid_layout, tile_size,
39};
42};
40pub use overlay::CallWindows;
43pub use overlay::CallWindows;
44pub use prejoin::{AudioChoice, JoinOptions, PendingJoin, load_join_options};
41pub use preview::{CameraPreview, preview_backgrounds};
45pub use preview::{CameraPreview, preview_backgrounds};
46pub use reminder::{MeetingToasts, subtitle as meeting_subtitle};
42pub use ring::{MissedCall, RingEntry, Rings};
47pub use ring::{MissedCall, RingEntry, Rings};
48pub use schedule::{FormValues, Invitee, default_window, draft_from_form};
43pub use target::plan_for_chat;
49pub use target::plan_for_chat;
crates/app/src/call/model.rs +10 −1
@@ -252,6 +252,7 @@ pub struct CallModel {
252 252 pub progress: Option<Progress>,
253 253 pub muted: bool,
254 254 pub listen_only: bool,
255 pub audio_off: bool,
255 256 pub lobby: bool,
256 257 pub can_end_meeting: bool,
257 258 pub incoming: bool,
@@ -301,6 +302,7 @@ impl CallModel {
301 302 progress: None,
302 303 muted: false,
303 304 listen_only: false,
305 audio_off: false,
304 306 lobby: false,
305 307 can_end_meeting: false,
306 308 incoming: false,
@@ -882,7 +884,7 @@ impl CallModel {
882 884 }
883 885
884 886 pub fn can_unmute(&self) -> bool {
885 !self.listen_only
887 !self.listen_only && !self.audio_off
886 888 }
887 889 }
888 890
@@ -1098,6 +1100,13 @@ mod tests {
1098 1100 assert!(!model.can_unmute());
1099 1101 }
1100 1102
1103 #[test]
1104 fn a_call_without_audio_blocks_unmuting() {
1105 let mut model = connected_model();
1106 model.audio_off = true;
1107 assert!(!model.can_unmute());
1108 }
1109
1101 1110 #[test]
1102 1111 fn callees_start_invited_and_follow_the_progress() {
1103 1112 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
@@ -252,6 +252,7 @@ pub struct CallModel {
252 pub progress: Option<Progress>,
252 pub progress: Option<Progress>,
253 pub muted: bool,
253 pub muted: bool,
254 pub listen_only: bool,
254 pub listen_only: bool,
255 pub audio_off: bool,
255 pub lobby: bool,
256 pub lobby: bool,
256 pub can_end_meeting: bool,
257 pub can_end_meeting: bool,
257 pub incoming: bool,
258 pub incoming: bool,
@@ -301,6 +302,7 @@ impl CallModel {
301 progress: None,
302 progress: None,
302 muted: false,
303 muted: false,
303 listen_only: false,
304 listen_only: false,
305 audio_off: false,
304 lobby: false,
306 lobby: false,
305 can_end_meeting: false,
307 can_end_meeting: false,
306 incoming: false,
308 incoming: false,
@@ -882,7 +884,7 @@ impl CallModel {
882 }
884 }
883
885
884 pub fn can_unmute(&self) -> bool {
886 pub fn can_unmute(&self) -> bool {
885 !self.listen_only
887 !self.listen_only && !self.audio_off
886 }
888 }
887}
889}
888
890
@@ -1098,6 +1100,13 @@ mod tests {
1098 assert!(!model.can_unmute());
1100 assert!(!model.can_unmute());
1099 }
1101 }
1100
1102
1103 #[test]
1104 fn a_call_without_audio_blocks_unmuting() {
1105 let mut model = connected_model();
1106 model.audio_off = true;
1107 assert!(!model.can_unmute());
1108 }
1109
1101 #[test]
1110 #[test]
1102 fn callees_start_invited_and_follow_the_progress() {
1111 fn callees_start_invited_and_follow_the_progress() {
1103 let mut model = CallModel::people("Bea", &[("8:orgid:b".into(), "Bea".into())]);
1112 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, DeviceChoice, VideoHub, VideoKey};
11 12 use gpui_kit::*;
12 13 use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
@@ -74,6 +75,14 @@ impl CameraPreview {
74 75 }
75 76 }
76 77
78 pub fn publish_demo_frame(&self, tick: u32) {
79 if let Some(picture) =
80 picture_from_i420(pattern_frame(PatternKind::Camera, tick), PREVIEW_MAX_WIDTH)
81 {
82 self.hub.publish(VideoKey::LocalCamera, picture);
83 }
84 }
85
77 86 pub fn set_background(&self, choice: BackgroundChoice) {
78 87 let mut latest = self
79 88 .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, DeviceChoice, VideoHub, VideoKey};
11use calling::{BackgroundChoice, CallUpdate, DeviceChoice, VideoHub, VideoKey};
11use gpui_kit::*;
12use gpui_kit::*;
12use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
13use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
@@ -74,6 +75,14 @@ impl CameraPreview {
74 }
75 }
75 }
76 }
76
77
78 pub fn publish_demo_frame(&self, tick: u32) {
79 if let Some(picture) =
80 picture_from_i420(pattern_frame(PatternKind::Camera, tick), PREVIEW_MAX_WIDTH)
81 {
82 self.hub.publish(VideoKey::LocalCamera, picture);
83 }
84 }
85
77 pub fn set_background(&self, choice: BackgroundChoice) {
86 pub fn set_background(&self, choice: BackgroundChoice) {
78 let mut latest = self
87 let mut latest = self
79 .background_request
88 .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
@@ -120,7 +120,7 @@ mod frames {
120 120 };
121 121 use store::Store;
122 122
123 use crate::app_state::{AppState, Mode};
123 use crate::app_state::{AppHandle, AppState, Mode};
124 124 use crate::demo;
125 125 use crate::user_activity::UserInput;
126 126 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
@@ -138,6 +138,20 @@ mod frames {
138 138 "shell/islands/main",
139 139 "shell/status-bar",
140 140 ];
141 const CALLS_TAGS: &[&str] = &[
142 "shell/islands/sidebar/calls-actions",
143 "shell/islands/sidebar/calls-actions/meet-now",
144 "shell/islands/sidebar/calls-actions/new-meeting",
145 ];
146 const PREJOIN_TAGS: &[&str] = &[
147 "shell/islands/main/prejoin",
148 "shell/islands/main/prejoin/preview",
149 "shell/islands/main/prejoin/controls",
150 "shell/islands/main/prejoin/devices",
151 "shell/islands/main/prejoin/audio",
152 "shell/islands/main/prejoin/actions",
153 ];
154 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";
141 155 const MENU: &str = "popup-menu";
142 156 const OWN_STATUS: &str = "shell/title-bar/own-status";
143 157 const SIZES: [(f32, f32); 2] = [(640., 480.), (1920., 1080.)];
@@ -149,6 +163,7 @@ mod frames {
149 163 enum Screen {
150 164 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
151 165 StatusMenu,
166 Prejoin,
152 167 }
153 168
154 169 fn parent_of(path: &str) -> Option<&str> {
@@ -263,6 +278,8 @@ mod frames {
263 278 }
264 279 GUARDED
265 280 .iter()
281 .chain(CALLS_TAGS)
282 .chain(PREJOIN_TAGS)
266 283 .chain([&MENU])
267 284 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
268 285 .collect()
@@ -351,6 +368,7 @@ mod frames {
351 368 ),
352 369 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
353 370 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
371 Screen::Prejoin,
354 372 Screen::StatusMenu,
355 373 ];
356 374 for screen in screens {
@@ -361,6 +379,13 @@ mod frames {
361 379 }
362 380 (name, false)
363 381 }
382 Screen::Prejoin => {
383 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
384 visual.update(|_, cx| {
385 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
386 });
387 ("prejoin", false)
388 }
364 389 Screen::StatusMenu => {
365 390 let tags = collect(&mut visual, None);
366 391 let button = tags
@@ -377,6 +402,11 @@ mod frames {
377 402 if status_menu {
378 403 expected.push(MENU);
379 404 }
405 match screen_name {
406 "calls" => expected.extend(CALLS_TAGS),
407 "prejoin" => expected.extend(PREJOIN_TAGS),
408 _ => {}
409 }
380 410 let mut found = violations(&tags, window, &expected);
381 411 if status_menu {
382 412 let menu = tags
@@ -402,6 +432,10 @@ mod frames {
402 432 visual.simulate_keystrokes("escape");
403 433 visual.run_until_parked();
404 434 }
435 if screen_name == "prejoin" {
436 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
437 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
438 }
405 439 for (key, message) in found {
406 440 let full_key = format!("{screen_name}@{width}x{height}:{key}");
407 441 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
@@ -120,7 +120,7 @@ mod frames {
120 };
120 };
121 use store::Store;
121 use store::Store;
122
122
123 use crate::app_state::{AppState, Mode};
123 use crate::app_state::{AppHandle, AppState, Mode};
124 use crate::demo;
124 use crate::demo;
125 use crate::user_activity::UserInput;
125 use crate::user_activity::UserInput;
126 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
126 use crate::views::shell::{AppShell, Startup, bind_keys, install_globals};
@@ -138,6 +138,20 @@ mod frames {
138 "shell/islands/main",
138 "shell/islands/main",
139 "shell/status-bar",
139 "shell/status-bar",
140 ];
140 ];
141 const CALLS_TAGS: &[&str] = &[
142 "shell/islands/sidebar/calls-actions",
143 "shell/islands/sidebar/calls-actions/meet-now",
144 "shell/islands/sidebar/calls-actions/new-meeting",
145 ];
146 const PREJOIN_TAGS: &[&str] = &[
147 "shell/islands/main/prejoin",
148 "shell/islands/main/prejoin/preview",
149 "shell/islands/main/prejoin/controls",
150 "shell/islands/main/prejoin/devices",
151 "shell/islands/main/prejoin/audio",
152 "shell/islands/main/prejoin/actions",
153 ];
154 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";
141 const MENU: &str = "popup-menu";
155 const MENU: &str = "popup-menu";
142 const OWN_STATUS: &str = "shell/title-bar/own-status";
156 const OWN_STATUS: &str = "shell/title-bar/own-status";
143 const SIZES: [(f32, f32); 2] = [(640., 480.), (1920., 1080.)];
157 const SIZES: [(f32, f32); 2] = [(640., 480.), (1920., 1080.)];
@@ -149,6 +163,7 @@ mod frames {
149 enum Screen {
163 enum Screen {
150 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
164 Tab(&'static str, Option<fn(&mut VisualTestContext)>),
151 StatusMenu,
165 StatusMenu,
166 Prejoin,
152 }
167 }
153
168
154 fn parent_of(path: &str) -> Option<&str> {
169 fn parent_of(path: &str) -> Option<&str> {
@@ -263,6 +278,8 @@ mod frames {
263 }
278 }
264 GUARDED
279 GUARDED
265 .iter()
280 .iter()
281 .chain(CALLS_TAGS)
282 .chain(PREJOIN_TAGS)
266 .chain([&MENU])
283 .chain([&MENU])
267 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
284 .filter_map(|path| visual.debug_bounds(path).map(|bounds| (*path, bounds)))
268 .collect()
285 .collect()
@@ -351,6 +368,7 @@ mod frames {
351 ),
368 ),
352 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
369 Screen::Tab("saved", Some(|visual| visual.dispatch_action(OpenSaved))),
353 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
370 Screen::Tab("calls", Some(|visual| visual.dispatch_action(OpenCallsTab))),
371 Screen::Prejoin,
354 Screen::StatusMenu,
372 Screen::StatusMenu,
355 ];
373 ];
356 for screen in screens {
374 for screen in screens {
@@ -361,6 +379,13 @@ mod frames {
361 }
379 }
362 (name, false)
380 (name, false)
363 }
381 }
382 Screen::Prejoin => {
383 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
384 visual.update(|_, cx| {
385 state.update(cx, |state, cx| state.join_meeting_link(PREJOIN_LINK, cx))
386 });
387 ("prejoin", false)
388 }
364 Screen::StatusMenu => {
389 Screen::StatusMenu => {
365 let tags = collect(&mut visual, None);
390 let tags = collect(&mut visual, None);
366 let button = tags
391 let button = tags
@@ -377,6 +402,11 @@ mod frames {
377 if status_menu {
402 if status_menu {
378 expected.push(MENU);
403 expected.push(MENU);
379 }
404 }
405 match screen_name {
406 "calls" => expected.extend(CALLS_TAGS),
407 "prejoin" => expected.extend(PREJOIN_TAGS),
408 _ => {}
409 }
380 let mut found = violations(&tags, window, &expected);
410 let mut found = violations(&tags, window, &expected);
381 if status_menu {
411 if status_menu {
382 let menu = tags
412 let menu = tags
@@ -402,6 +432,10 @@ mod frames {
402 visual.simulate_keystrokes("escape");
432 visual.simulate_keystrokes("escape");
403 visual.run_until_parked();
433 visual.run_until_parked();
404 }
434 }
435 if screen_name == "prejoin" {
436 let state = visual.update(|_, cx| cx.global::<AppHandle>().0.clone());
437 visual.update(|_, cx| state.update(cx, |state, cx| state.cancel_prejoin(cx)));
438 }
405 for (key, message) in found {
439 for (key, message) in found {
406 let full_key = format!("{screen_name}@{width}x{height}:{key}");
440 let full_key = format!("{screen_name}@{width}x{height}:{key}");
407 if KNOWN_VIOLATIONS.contains(&full_key.as_str()) {
441 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,
@@ -411,14 +417,19 @@ impl NotificationCenter {
411 417 }
412 418 }
413 419
414 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
420 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
415 421 let state = self.app.read(cx);
416 422 let in_call = state.call.is_some();
417 state
423 let rings = state
418 424 .rings
419 425 .ringing()
420 .map(|entry| (entry.ring.ring_id, in_call))
421 .collect()
426 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
427 let meetings = state
428 .meeting_toasts
429 .entries()
430 .iter()
431 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
432 rings.chain(meetings).collect()
422 433 }
423 434
424 435 fn sync_windows(&mut self, cx: &mut Context<Self>) {
@@ -432,15 +443,15 @@ impl NotificationCenter {
432 443 for id in stale {
433 444 self.close_window(id, cx);
434 445 }
435 let rings = self.ringing_ids(cx);
436 let stale_rings: Vec<u64> = self
437 .ring_windows
446 let call_toasts = self.call_toasts(cx);
447 let stale_call_toasts: Vec<CallToast> = self
448 .call_windows
438 449 .keys()
439 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
450 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
440 451 .copied()
441 452 .collect();
442 for id in stale_rings {
443 self.close_ring_window(id, cx);
453 for key in stale_call_toasts {
454 self.close_call_window(key, cx);
444 455 }
445 456 let area = self.work_area(cx);
446 457 let mut heights: Vec<f32> = self
@@ -455,21 +466,30 @@ impl NotificationCenter {
455 466 layout::toast_height(toast, lines)
456 467 })
457 468 .collect();
458 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
469 heights.extend(call_toasts.iter().map(|(_, height)| *height));
459 470 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
460 471 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
461 472 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
462 473 self.place_toast(*id, *slot, area, cx);
463 474 }
464 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
465 self.place_ring(*ring_id, *slot, area, cx);
475 for ((key, _), slot) in call_toasts
476 .iter()
477 .zip(slots.toasts.iter().skip(visible.len()))
478 {
479 self.place_call_toast(*key, *slot, area, cx);
466 480 }
467 481 self.sync_pill(slots.pill, area, cx);
468 482 }
469 483
470 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
471 let Some(window) = self.ring_windows.get(&ring_id) else {
472 self.open_ring_window(ring_id, slot, area, cx);
484 fn place_call_toast(
485 &mut self,
486 key: CallToast,
487 slot: Slot,
488 area: WorkArea,
489 cx: &mut Context<Self>,
490 ) {
491 let Some(window) = self.call_windows.get(&key) else {
492 self.open_call_window(key, slot, area, cx);
473 493 return;
474 494 };
475 495 if let Some(native) = window.native {
@@ -478,39 +498,69 @@ impl NotificationCenter {
478 498 }
479 499 }
480 500
481 fn open_ring_window(
501 fn open_call_window(
482 502 &mut self,
483 ring_id: u64,
503 key: CallToast,
484 504 slot: Slot,
485 505 area: WorkArea,
486 506 cx: &mut Context<Self>,
487 507 ) {
488 if !self.ring_opening.insert(ring_id) {
508 if !self.call_opening.insert(key) {
489 509 return;
490 510 }
491 511 open_popup(
492 512 popup_options(slot, area),
493 513 cx,
494 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
514 move |center, _, cx| match key {
515 CallToast::Ring(ring_id) => {
516 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
517 }
518 CallToast::Meeting(toast_id) => {
519 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
520 }
521 },
495 522 move |this, window| {
496 this.ring_opening.remove(&ring_id);
523 this.call_opening.remove(&key);
497 524 if let Some(window) = window {
498 this.ring_windows.insert(ring_id, window);
525 this.call_windows.insert(key, window);
499 526 }
500 527 },
501 528 );
502 529 }
503 530
504 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
505 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
531 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
532 let closed = self.call_windows.get(&key).is_some_and(|window| {
506 533 window
507 534 .handle
508 535 .update(cx, |_, window, _| window.remove_window())
509 536 .is_ok()
510 537 });
511 538 if closed {
512 self.ring_windows.remove(&ring_id);
539 self.call_windows.remove(&key);
540 }
541 }
542
543 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
544 if !self.app.read(cx).meeting_toasts.is_empty()
545 && !self.main_window_active(cx)
546 && let Some(native) = self.main_native
547 {
548 platform::flash(native);
513 549 }
550 self.sync_windows(cx);
551 cx.notify();
552 }
553
554 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
555 self.raise_main_window(cx);
556 self.app
557 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
558 }
559
560 fn reminders_quiet(&self, cx: &App) -> bool {
561 self.settings.do_not_disturb
562 || platform::system_quiet()
563 || own_do_not_disturb(self.app.read(cx))
514 564 }
515 565
516 566 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
@@ -686,10 +736,20 @@ impl NotificationCenter {
686 736 if !self.app.read(cx).rings.is_empty() {
687 737 self.app.update(cx, |state, cx| state.tick_rings(cx));
688 738 }
739 if self
740 .app
741 .read(cx)
742 .meeting_toasts
743 .is_due_for_check(Utc::now())
744 {
745 let show = !self.reminders_quiet(cx);
746 self.app
747 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
748 }
689 749 if !self.stack.is_empty()
690 750 || !self.windows.is_empty()
691 751 || self.pill.is_some()
692 || !self.ring_windows.is_empty()
752 || !self.call_windows.is_empty()
693 753 {
694 754 self.sync_windows(cx);
695 755 cx.notify();
@@ -999,10 +1059,10 @@ impl NotificationCenter {
999 1059
1000 1060 /// Opens a window outside the current update: `open_window` draws right away, and every
1001 1061 /// notification view reads the center while rendering.
1002 fn open_popup<V: Render>(
1062 fn open_popup<V: Into<AnyView>>(
1003 1063 options: WindowOptions,
1004 1064 cx: &mut Context<NotificationCenter>,
1005 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
1065 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1006 1066 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1007 1067 ) {
1008 1068 let center = cx.entity();
@@ -1032,6 +1092,12 @@ fn open_popup<V: Render>(
1032 1092 });
1033 1093 }
1034 1094
1095 fn own_do_not_disturb(state: &AppState) -> bool {
1096 state.directory.me.as_ref().is_some_and(|me| {
1097 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
1098 })
1099 }
1100
1035 1101 fn demo_scene() -> Option<DemoScene> {
1036 1102 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1037 1103 }
@@ -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,
@@ -411,14 +417,19 @@ impl NotificationCenter {
411 }
417 }
412 }
418 }
413
419
414 fn ringing_ids(&self, cx: &App) -> Vec<(u64, bool)> {
420 fn call_toasts(&self, cx: &App) -> Vec<(CallToast, f32)> {
415 let state = self.app.read(cx);
421 let state = self.app.read(cx);
416 let in_call = state.call.is_some();
422 let in_call = state.call.is_some();
417 state
423 let rings = state
418 .rings
424 .rings
419 .ringing()
425 .ringing()
420 .map(|entry| (entry.ring.ring_id, in_call))
426 .map(|entry| (CallToast::Ring(entry.ring.ring_id), ring_height(in_call)));
421 .collect()
427 let meetings = state
428 .meeting_toasts
429 .entries()
430 .iter()
431 .map(|toast| (CallToast::Meeting(toast.id), MEETING_HEIGHT));
432 rings.chain(meetings).collect()
422 }
433 }
423
434
424 fn sync_windows(&mut self, cx: &mut Context<Self>) {
435 fn sync_windows(&mut self, cx: &mut Context<Self>) {
@@ -432,15 +443,15 @@ impl NotificationCenter {
432 for id in stale {
443 for id in stale {
433 self.close_window(id, cx);
444 self.close_window(id, cx);
434 }
445 }
435 let rings = self.ringing_ids(cx);
446 let call_toasts = self.call_toasts(cx);
436 let stale_rings: Vec<u64> = self
447 let stale_call_toasts: Vec<CallToast> = self
437 .ring_windows
448 .call_windows
438 .keys()
449 .keys()
439 .filter(|id| !rings.iter().any(|(ring_id, _)| ring_id == *id))
450 .filter(|key| !call_toasts.iter().any(|(toast, _)| toast == *key))
440 .copied()
451 .copied()
441 .collect();
452 .collect();
442 for id in stale_rings {
453 for key in stale_call_toasts {
443 self.close_ring_window(id, cx);
454 self.close_call_window(key, cx);
444 }
455 }
445 let area = self.work_area(cx);
456 let area = self.work_area(cx);
446 let mut heights: Vec<f32> = self
457 let mut heights: Vec<f32> = self
@@ -455,21 +466,30 @@ impl NotificationCenter {
455 layout::toast_height(toast, lines)
466 layout::toast_height(toast, lines)
456 })
467 })
457 .collect();
468 .collect();
458 heights.extend(rings.iter().map(|(_, in_call)| ring_height(*in_call)));
469 heights.extend(call_toasts.iter().map(|(_, height)| *height));
459 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
470 let with_hide_all = visible.len() > 1 || self.stack.queued_count() > 0;
460 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
471 let slots = layout::stack_slots(area, self.settings.corner, &heights, with_hide_all);
461 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
472 for (id, slot) in visible.iter().zip(slots.toasts.iter()) {
462 self.place_toast(*id, *slot, area, cx);
473 self.place_toast(*id, *slot, area, cx);
463 }
474 }
464 for ((ring_id, _), slot) in rings.iter().zip(slots.toasts.iter().skip(visible.len())) {
475 for ((key, _), slot) in call_toasts
465 self.place_ring(*ring_id, *slot, area, cx);
476 .iter()
477 .zip(slots.toasts.iter().skip(visible.len()))
478 {
479 self.place_call_toast(*key, *slot, area, cx);
466 }
480 }
467 self.sync_pill(slots.pill, area, cx);
481 self.sync_pill(slots.pill, area, cx);
468 }
482 }
469
483
470 fn place_ring(&mut self, ring_id: u64, slot: Slot, area: WorkArea, cx: &mut Context<Self>) {
484 fn place_call_toast(
471 let Some(window) = self.ring_windows.get(&ring_id) else {
485 &mut self,
472 self.open_ring_window(ring_id, slot, area, cx);
486 key: CallToast,
487 slot: Slot,
488 area: WorkArea,
489 cx: &mut Context<Self>,
490 ) {
491 let Some(window) = self.call_windows.get(&key) else {
492 self.open_call_window(key, slot, area, cx);
473 return;
493 return;
474 };
494 };
475 if let Some(native) = window.native {
495 if let Some(native) = window.native {
@@ -478,39 +498,69 @@ impl NotificationCenter {
478 }
498 }
479 }
499 }
480
500
481 fn open_ring_window(
501 fn open_call_window(
482 &mut self,
502 &mut self,
483 ring_id: u64,
503 key: CallToast,
484 slot: Slot,
504 slot: Slot,
485 area: WorkArea,
505 area: WorkArea,
486 cx: &mut Context<Self>,
506 cx: &mut Context<Self>,
487 ) {
507 ) {
488 if !self.ring_opening.insert(ring_id) {
508 if !self.call_opening.insert(key) {
489 return;
509 return;
490 }
510 }
491 open_popup(
511 open_popup(
492 popup_options(slot, area),
512 popup_options(slot, area),
493 cx,
513 cx,
494 move |center, _, cx| cx.new(|cx| RingView::new(center, ring_id, cx)),
514 move |center, _, cx| match key {
515 CallToast::Ring(ring_id) => {
516 AnyView::from(cx.new(|cx| RingView::new(center, ring_id, cx)))
517 }
518 CallToast::Meeting(toast_id) => {
519 AnyView::from(cx.new(|cx| MeetingToastView::new(center, toast_id, cx)))
520 }
521 },
495 move |this, window| {
522 move |this, window| {
496 this.ring_opening.remove(&ring_id);
523 this.call_opening.remove(&key);
497 if let Some(window) = window {
524 if let Some(window) = window {
498 this.ring_windows.insert(ring_id, window);
525 this.call_windows.insert(key, window);
499 }
526 }
500 },
527 },
501 );
528 );
502 }
529 }
503
530
504 fn close_ring_window(&mut self, ring_id: u64, cx: &mut Context<Self>) {
531 fn close_call_window(&mut self, key: CallToast, cx: &mut Context<Self>) {
505 let closed = self.ring_windows.get(&ring_id).is_some_and(|window| {
532 let closed = self.call_windows.get(&key).is_some_and(|window| {
506 window
533 window
507 .handle
534 .handle
508 .update(cx, |_, window, _| window.remove_window())
535 .update(cx, |_, window, _| window.remove_window())
509 .is_ok()
536 .is_ok()
510 });
537 });
511 if closed {
538 if closed {
512 self.ring_windows.remove(&ring_id);
539 self.call_windows.remove(&key);
540 }
541 }
542
543 fn on_meeting_reminder(&mut self, cx: &mut Context<Self>) {
544 if !self.app.read(cx).meeting_toasts.is_empty()
545 && !self.main_window_active(cx)
546 && let Some(native) = self.main_native
547 {
548 platform::flash(native);
513 }
549 }
550 self.sync_windows(cx);
551 cx.notify();
552 }
553
554 pub fn join_meeting_toast(&mut self, id: u64, cx: &mut Context<Self>) {
555 self.raise_main_window(cx);
556 self.app
557 .update(cx, |state, cx| state.join_meeting_toast(id, cx));
558 }
559
560 fn reminders_quiet(&self, cx: &App) -> bool {
561 self.settings.do_not_disturb
562 || platform::system_quiet()
563 || own_do_not_disturb(self.app.read(cx))
514 }
564 }
515
565
516 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
566 fn on_rings_changed(&mut self, cx: &mut Context<Self>) {
@@ -686,10 +736,20 @@ impl NotificationCenter {
686 if !self.app.read(cx).rings.is_empty() {
736 if !self.app.read(cx).rings.is_empty() {
687 self.app.update(cx, |state, cx| state.tick_rings(cx));
737 self.app.update(cx, |state, cx| state.tick_rings(cx));
688 }
738 }
739 if self
740 .app
741 .read(cx)
742 .meeting_toasts
743 .is_due_for_check(Utc::now())
744 {
745 let show = !self.reminders_quiet(cx);
746 self.app
747 .update(cx, |state, cx| state.tick_meeting_reminders(show, cx));
748 }
689 if !self.stack.is_empty()
749 if !self.stack.is_empty()
690 || !self.windows.is_empty()
750 || !self.windows.is_empty()
691 || self.pill.is_some()
751 || self.pill.is_some()
692 || !self.ring_windows.is_empty()
752 || !self.call_windows.is_empty()
693 {
753 {
694 self.sync_windows(cx);
754 self.sync_windows(cx);
695 cx.notify();
755 cx.notify();
@@ -999,10 +1059,10 @@ impl NotificationCenter {
999
1059
1000/// Opens a window outside the current update: `open_window` draws right away, and every
1060/// Opens a window outside the current update: `open_window` draws right away, and every
1001/// notification view reads the center while rendering.
1061/// notification view reads the center while rendering.
1002fn open_popup<V: Render>(
1062fn open_popup<V: Into<AnyView>>(
1003 options: WindowOptions,
1063 options: WindowOptions,
1004 cx: &mut Context<NotificationCenter>,
1064 cx: &mut Context<NotificationCenter>,
1005 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> Entity<V> + 'static,
1065 build: impl FnOnce(Entity<NotificationCenter>, &mut Window, &mut App) -> V + 'static,
1006 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1066 opened: impl FnOnce(&mut NotificationCenter, Option<OpenWindow>) + 'static,
1007) {
1067) {
1008 let center = cx.entity();
1068 let center = cx.entity();
@@ -1032,6 +1092,12 @@ fn open_popup<V: Render>(
1032 });
1092 });
1033}
1093}
1034
1094
1095fn own_do_not_disturb(state: &AppState) -> bool {
1096 state.directory.me.as_ref().is_some_and(|me| {
1097 state.directory.presence_of(&me.user_id).kind() == PresenceKind::DoNotDisturb
1098 })
1099}
1100
1035fn demo_scene() -> Option<DemoScene> {
1101fn demo_scene() -> Option<DemoScene> {
1036 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1102 DemoScene::from_name(&std::env::var(DEMO_CALL_ENV).ok()?)
1037}
1103}
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 @@ 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";
@@ -363,10 +364,15 @@ pub fn mute_button(
363 364 };
364 365 let button = round_control(id, glyph, background, foreground).size(px(size));
365 366 if !model.can_unmute() {
367 let hint = if model.audio_off {
368 AUDIO_OFF_HINT
369 } else {
370 NO_MICROPHONE_HINT
371 };
366 372 return button
367 373 .opacity(DISABLED_OPACITY)
368 374 .cursor_default()
369 .tooltip(|window, cx| Tooltip::new(NO_MICROPHONE_HINT).build(window, cx));
375 .tooltip(move |window, cx| Tooltip::new(hint).build(window, cx));
370 376 }
371 377 let app = app.clone();
372 378 button.on_click(move |_, _, cx| {
@@ -774,6 +780,9 @@ pub(super) fn device_items(
774 780 }
775 781
776 782 fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
783 if model.audio_off {
784 return popup.item(PopupMenuItem::new(AUDIO_OFF_HINT).disabled(true));
785 }
777 786 let input_app = app.clone();
778 787 let output_app = app.clone();
779 788 let inputs = device_items(
@@ -60,6 +60,7 @@ 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";
@@ -363,10 +364,15 @@ pub fn mute_button(
363 };
364 };
364 let button = round_control(id, glyph, background, foreground).size(px(size));
365 let button = round_control(id, glyph, background, foreground).size(px(size));
365 if !model.can_unmute() {
366 if !model.can_unmute() {
367 let hint = if model.audio_off {
368 AUDIO_OFF_HINT
369 } else {
370 NO_MICROPHONE_HINT
371 };
366 return button
372 return button
367 .opacity(DISABLED_OPACITY)
373 .opacity(DISABLED_OPACITY)
368 .cursor_default()
374 .cursor_default()
369 .tooltip(|window, cx| Tooltip::new(NO_MICROPHONE_HINT).build(window, cx));
375 .tooltip(move |window, cx| Tooltip::new(hint).build(window, cx));
370 }
376 }
371 let app = app.clone();
377 let app = app.clone();
372 button.on_click(move |_, _, cx| {
378 button.on_click(move |_, _, cx| {
@@ -774,6 +780,9 @@ pub(super) fn device_items(
774}
780}
775
781
776fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
782fn devices_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> PopupMenu {
783 if model.audio_off {
784 return popup.item(PopupMenuItem::new(AUDIO_OFF_HINT).disabled(true));
785 }
777 let input_app = app.clone();
786 let input_app = app.clone();
778 let output_app = app.clone();
787 let output_app = app.clone();
779 let inputs = device_items(
788 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
@@ -609,6 +609,7 @@ impl ConversationView {
609 609 | AppEvent::CallHistory
610 610 | AppEvent::Ring
611 611 | AppEvent::MissedCall(_)
612 | AppEvent::MeetingReminder
612 613 | AppEvent::Call => {}
613 614 AppEvent::LiveMeeting => cx.notify(),
614 615 AppEvent::Saved => cx.notify(),
@@ -609,6 +609,7 @@ impl ConversationView {
609 | AppEvent::CallHistory
609 | AppEvent::CallHistory
610 | AppEvent::Ring
610 | AppEvent::Ring
611 | AppEvent::MissedCall(_)
611 | AppEvent::MissedCall(_)
612 | AppEvent::MeetingReminder
612 | AppEvent::Call => {}
613 | AppEvent::Call => {}
613 AppEvent::LiveMeeting => cx.notify(),
614 AppEvent::LiveMeeting => cx.notify(),
614 AppEvent::Saved => cx.notify(),
615 AppEvent::Saved => cx.notify(),
crates/app/src/views/mod.rs +2 −0
@@ -34,8 +34,10 @@ pub mod link_preview;
34 34 pub mod message_actions;
35 35 pub mod message_row;
36 36 pub mod new_chat;
37 pub mod new_meeting_dialog;
37 38 pub mod pin_banner;
38 39 pub mod post_card;
40 pub mod prejoin_view;
39 41 pub mod profile_card;
40 42 pub mod proposal_card;
41 43 pub mod rail;
@@ -34,8 +34,10 @@ pub mod link_preview;
34pub mod message_actions;
34pub mod message_actions;
35pub mod message_row;
35pub mod message_row;
36pub mod new_chat;
36pub mod new_chat;
37pub mod new_meeting_dialog;
37pub mod pin_banner;
38pub mod pin_banner;
38pub mod post_card;
39pub mod post_card;
40pub mod prejoin_view;
39pub mod profile_card;
41pub mod profile_card;
40pub mod proposal_card;
42pub mod proposal_card;
41pub mod rail;
43pub 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 +566 −0
@@ -0,0 +1,566 @@
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::{BackgroundMenu, 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 let demo = state.mode.demo;
98 let mut options = state.join_options.clone();
99 options.camera_on = options.camera_on && !state.mode.read_only;
100 let camera = state.call_camera.clone();
101 let mut view = PrejoinView {
102 pending_id: pending.id,
103 demo,
104 preview,
105 options,
106 cameras: camera_entries(&[]),
107 devices: if demo {
108 demo_devices()
109 } else {
110 DeviceLists::default()
111 },
112 camera,
113 applied_background: crate::call::BackgroundPick::None,
114 tick: 0,
115 _subscription: subscription,
116 _release: release,
117 app,
118 };
119 cx.spawn(async move |this, cx| {
120 while updates.recv().await.is_some() {
121 if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
122 return;
123 }
124 }
125 })
126 .detach();
127 cx.spawn(async move |this, cx| {
128 loop {
129 cx.background_executor().timer(FPS_TICK).await;
130 if this
131 .update(cx, |view, cx| {
132 view.preview.tick(Instant::now());
133 cx.notify();
134 })
135 .is_err()
136 {
137 break;
138 }
139 }
140 })
141 .detach();
142 if demo {
143 cx.spawn(async move |this, cx| {
144 loop {
145 cx.background_executor().timer(FRAME_TICK).await;
146 if this.update(cx, |view, cx| view.demo_frame(cx)).is_err() {
147 break;
148 }
149 }
150 })
151 .detach();
152 } else {
153 view.load_devices(cx);
154 }
155 view.sync_background(cx);
156 view.restart_preview();
157 view
158 }
159
160 pub fn pending_id(&self) -> u64 {
161 self.pending_id
162 }
163
164 fn take_frames(&mut self, cx: &mut Context<Self>) {
165 self.preview.take_frames(cx);
166 cx.notify();
167 }
168
169 fn demo_frame(&mut self, cx: &mut Context<Self>) {
170 if self.options.camera_on {
171 self.tick = self.tick.wrapping_add(1);
172 self.preview.publish_demo_frame(self.tick);
173 self.take_frames(cx);
174 }
175 }
176
177 fn load_devices(&mut self, cx: &mut Context<Self>) {
178 cx.spawn(async move |this, cx| {
179 let (cameras, devices) = cx
180 .background_executor()
181 .spawn(async { (list_cameras(), list_devices(&shared_factory())) })
182 .await;
183 this.update(cx, |view, cx| {
184 view.cameras = camera_entries(&cameras);
185 view.devices = devices;
186 cx.notify();
187 })
188 .ok();
189 })
190 .detach();
191 }
192
193 fn restart_preview(&mut self) {
194 if self.options.camera_on && !self.demo {
195 self.preview.start(&self.camera);
196 }
197 }
198
199 fn sync_background(&mut self, cx: &mut Context<Self>) {
200 let state = self.app.read(cx);
201 let pick = state.call_background.clone();
202 if pick == self.applied_background {
203 return;
204 }
205 if let Some(choice) = state.call_backgrounds.choice_for(&pick) {
206 self.preview.set_background(choice);
207 self.applied_background = pick;
208 }
209 cx.notify();
210 }
211
212 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
213 self.options.camera_on = !self.options.camera_on;
214 if self.options.camera_on {
215 self.restart_preview();
216 } else {
217 self.preview.stop(cx);
218 }
219 cx.notify();
220 }
221
222 fn toggle_mic(&mut self, cx: &mut Context<Self>) {
223 self.options.mic_on = !self.options.mic_on;
224 cx.notify();
225 }
226
227 fn set_audio(&mut self, audio: AudioChoice, cx: &mut Context<Self>) {
228 self.options.audio = audio;
229 cx.notify();
230 }
231
232 fn pick_camera(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
233 self.camera = choice.clone();
234 self.app
235 .update(cx, |state, cx| state.select_call_camera(choice, cx));
236 self.restart_preview();
237 cx.notify();
238 }
239
240 fn pick_input(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
241 self.options.input = choice;
242 cx.notify();
243 }
244
245 fn pick_output(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
246 self.options.output = choice;
247 cx.notify();
248 }
249
250 fn join(&mut self, cx: &mut Context<Self>) {
251 self.preview.stop(cx);
252 let options = self.options.clone();
253 self.app
254 .update(cx, |state, cx| state.confirm_prejoin(options, cx));
255 }
256
257 fn cancel(&mut self, cx: &mut Context<Self>) {
258 self.app.update(cx, |state, cx| state.cancel_prejoin(cx));
259 }
260
261 fn preview_status(&self) -> String {
262 match self.preview.failure() {
263 Some(reason) => format!("Camera could not start: {reason}"),
264 None => "Starting camera...".to_owned(),
265 }
266 }
267
268 fn preview_box(&self, cx: &mut Context<Self>) -> Div {
269 let state = self.app.read(cx);
270 let image = self
271 .options
272 .camera_on
273 .then(|| self.preview.image(Instant::now()))
274 .flatten();
275 let me = state.directory.me.clone();
276 let face = match (&image, self.options.camera_on) {
277 (Some(image), _) => img(ImageSource::Render(image.clone()))
278 .size_full()
279 .object_fit(ObjectFit::Cover)
280 .into_any_element(),
281 (None, true) => centered_note(&self.preview_status()),
282 (None, false) => v_flex()
283 .items_center()
284 .gap(px(10.))
285 .child(person_avatar(
286 &state.directory,
287 me.as_ref().map(|me| me.user_id.as_str()),
288 me.as_ref().map_or("You", |me| me.display_name.as_str()),
289 AVATAR_SIZE,
290 ))
291 .child(
292 div()
293 .text_size(px(13.))
294 .text_color(theme::text_muted())
295 .child(CAMERA_OFF_TEXT),
296 )
297 .into_any_element(),
298 };
299 div()
300 .debug_selector(|| "shell/islands/main/prejoin/preview".into())
301 .relative()
302 .w_full()
303 .h(px(PREVIEW_HEIGHT))
304 .flex_shrink(1.)
305 .min_h(px(PREVIEW_MIN_HEIGHT))
306 .flex()
307 .items_center()
308 .justify_center()
309 .overflow_hidden()
310 .rounded(px(PREVIEW_RADIUS))
311 .bg(theme::background())
312 .child(face)
313 }
314
315 fn controls(&self, cx: &mut Context<Self>) -> impl IntoElement {
316 let view = cx.entity();
317 let camera_view = view.clone();
318 let mic_view = view.clone();
319 let (camera_glyph, camera_bg, camera_fg) = if self.options.camera_on {
320 (IconName::Video, theme::accent(), theme::on_accent())
321 } else {
322 (IconName::VideoOff, theme::surface_raised(), theme::text())
323 };
324 let (mic_glyph, mic_bg, mic_fg) = if self.options.mic_on {
325 (IconName::Mic, theme::surface_raised(), theme::text())
326 } else {
327 (IconName::MicOff, theme::red(), theme::white())
328 };
329 let audio_on = self.options.audio == AudioChoice::Computer;
330 let backgrounds = BackgroundMenu::of(self.app.read(cx));
331 let background_app = self.app.clone();
332 h_flex()
333 .debug_selector(|| "shell/islands/main/prejoin/controls".into())
334 .flex_none()
335 .gap(px(10.))
336 .items_center()
337 .justify_center()
338 .child(
339 round_control("prejoin-camera", camera_glyph, camera_bg, camera_fg).on_click(
340 move |_, _, cx| camera_view.update(cx, |view, cx| view.toggle_camera(cx)),
341 ),
342 )
343 .child(
344 round_control("prejoin-mic", mic_glyph, mic_bg, mic_fg)
345 .when(!audio_on, |button| button.opacity(0.4).cursor_default())
346 .when(audio_on, |button| {
347 button.on_click(move |_, _, cx| {
348 mic_view.update(cx, |view, cx| view.toggle_mic(cx))
349 })
350 }),
351 )
352 .child(
353 Button::new("prejoin-background")
354 .outline()
355 .label("Background")
356 .icon(IconName::ChevronDown)
357 .dropdown_menu(move |menu: PopupMenu, _, _| {
358 background_items(menu, &background_app, &backgrounds)
359 }),
360 )
361 }
362
363 fn select(
364 &self,
365 spec: DeviceSelect,
366 pick: impl Fn(&mut PrejoinView, DeviceChoice, &mut Context<PrejoinView>) + Clone + 'static,
367 cx: &mut Context<Self>,
368 ) -> Div {
369 let DeviceSelect {
370 id,
371 label,
372 entries,
373 current,
374 enabled,
375 } = spec;
376 let view = cx.entity();
377 let face = label_of(&entries, &current);
378 let items_entries = entries;
379 let items_current = current;
380 let button = Button::new(id)
381 .outline()
382 .w_full()
383 .label(face)
384 .icon(IconName::ChevronDown)
385 .disabled(!enabled)
386 .dropdown_menu(move |menu, _, _| {
387 let view = view.clone();
388 let pick = pick.clone();
389 device_items(items_entries.clone(), &items_current, move |choice, cx| {
390 let pick = pick.clone();
391 view.update(cx, |view, cx| pick(view, choice, cx));
392 })
393 .into_iter()
394 .fold(menu, |menu, item| menu.item(item))
395 });
396 v_flex()
397 .flex_1()
398 .min_w_0()
399 .max_w(px(SELECT_WIDTH))
400 .gap(px(4.))
401 .child(
402 div()
403 .text_size(px(12.))
404 .text_color(theme::text_muted())
405 .child(label),
406 )
407 .child(div().w_full().overflow_hidden().child(button))
408 }
409
410 fn audio_choice(&self, choice: AudioChoice, cx: &mut Context<Self>) -> Stateful<Div> {
411 let selected = self.options.audio == choice;
412 let view = cx.entity();
413 h_flex()
414 .id(match choice {
415 AudioChoice::Computer => "prejoin-audio-computer",
416 AudioChoice::NoAudio => "prejoin-audio-none",
417 })
418 .h(px(32.))
419 .px(px(14.))
420 .items_center()
421 .rounded(px(8.))
422 .border_1()
423 .border_color(if selected {
424 theme::accent()
425 } else {
426 theme::border_strong()
427 })
428 .when(selected, |option| option.bg(theme::surface_raised()))
429 .cursor_pointer()
430 .text_size(px(13.))
431 .text_color(theme::text())
432 .child(choice.label())
433 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.set_audio(choice, cx)))
434 }
435 }
436
437 fn centered_note(text: &str) -> AnyElement {
438 div()
439 .text_size(px(13.))
440 .text_color(theme::text_muted())
441 .child(text.to_owned())
442 .into_any_element()
443 }
444
445 impl Render for PrejoinView {
446 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
447 let title = self
448 .app
449 .read(cx)
450 .prejoin
451 .as_ref()
452 .map(|pending| pending.join.title.clone())
453 .unwrap_or_default();
454 let audio_on = self.options.audio == AudioChoice::Computer;
455 let (cameras, camera) = (self.cameras.clone(), self.camera.clone());
456 let (inputs, input) = (self.devices.input_entries(), self.options.input.clone());
457 let (outputs, output) = (self.devices.output_entries(), self.options.output.clone());
458 let devices = h_flex()
459 .debug_selector(|| "shell/islands/main/prejoin/devices".into())
460 .flex_none()
461 .w_full()
462 .gap(px(10.))
463 .child(self.select(
464 DeviceSelect {
465 id: "prejoin-camera-select",
466 label: "Camera",
467 entries: cameras,
468 current: camera,
469 enabled: true,
470 },
471 |view, choice, cx| view.pick_camera(choice, cx),
472 cx,
473 ))
474 .child(self.select(
475 DeviceSelect {
476 id: "prejoin-mic-select",
477 label: "Microphone",
478 entries: inputs,
479 current: input,
480 enabled: audio_on,
481 },
482 |view, choice, cx| view.pick_input(choice, cx),
483 cx,
484 ))
485 .child(self.select(
486 DeviceSelect {
487 id: "prejoin-speaker-select",
488 label: "Speaker",
489 entries: outputs,
490 current: output,
491 enabled: audio_on,
492 },
493 |view, choice, cx| view.pick_output(choice, cx),
494 cx,
495 ));
496 let audio_row = h_flex()
497 .debug_selector(|| "shell/islands/main/prejoin/audio".into())
498 .flex_none()
499 .flex_wrap()
500 .gap(px(8.))
501 .child(self.audio_choice(AudioChoice::Computer, cx))
502 .child(self.audio_choice(AudioChoice::NoAudio, cx));
503 let cancel_view = cx.entity();
504 let join_view = cx.entity();
505 let actions = h_flex()
506 .debug_selector(|| "shell/islands/main/prejoin/actions".into())
507 .flex_none()
508 .gap(px(8.))
509 .justify_end()
510 .child(
511 Button::new("prejoin-cancel")
512 .ghost()
513 .label("Cancel")
514 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
515 )
516 .child(
517 Button::new("prejoin-join")
518 .primary()
519 .label("Join now")
520 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
521 );
522 v_flex()
523 .debug_selector(|| "shell/islands/main".into())
524 .size_full()
525 .p(px(PANE_PADDING))
526 .items_center()
527 .justify_center()
528 .rounded(px(10.))
529 .bg(theme::surface())
530 .overflow_hidden()
531 .child(
532 v_flex()
533 .debug_selector(|| "shell/islands/main/prejoin".into())
534 .w(px(CONTENT_WIDTH))
535 .max_w_full()
536 .max_h_full()
537 .min_h_0()
538 .gap(px(SECTION_GAP))
539 .child(
540 v_flex()
541 .flex_none()
542 .gap(px(2.))
543 .child(
544 div()
545 .truncate()
546 .text_size(px(20.))
547 .font_weight(FontWeight::SEMIBOLD)
548 .text_color(theme::text_strong())
549 .child(title),
550 )
551 .child(
552 div()
553 .truncate()
554 .text_size(px(13.))
555 .text_color(theme::text_muted())
556 .child("Choose your video and audio settings, then join"),
557 ),
558 )
559 .child(self.preview_box(cx))
560 .child(self.controls(cx))
561 .child(devices)
562 .child(audio_row)
563 .child(actions),
564 )
565 }
566 }
@@ -0,0 +1,566 @@
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::{BackgroundMenu, 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 let demo = state.mode.demo;
98 let mut options = state.join_options.clone();
99 options.camera_on = options.camera_on && !state.mode.read_only;
100 let camera = state.call_camera.clone();
101 let mut view = PrejoinView {
102 pending_id: pending.id,
103 demo,
104 preview,
105 options,
106 cameras: camera_entries(&[]),
107 devices: if demo {
108 demo_devices()
109 } else {
110 DeviceLists::default()
111 },
112 camera,
113 applied_background: crate::call::BackgroundPick::None,
114 tick: 0,
115 _subscription: subscription,
116 _release: release,
117 app,
118 };
119 cx.spawn(async move |this, cx| {
120 while updates.recv().await.is_some() {
121 if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
122 return;
123 }
124 }
125 })
126 .detach();
127 cx.spawn(async move |this, cx| {
128 loop {
129 cx.background_executor().timer(FPS_TICK).await;
130 if this
131 .update(cx, |view, cx| {
132 view.preview.tick(Instant::now());
133 cx.notify();
134 })
135 .is_err()
136 {
137 break;
138 }
139 }
140 })
141 .detach();
142 if demo {
143 cx.spawn(async move |this, cx| {
144 loop {
145 cx.background_executor().timer(FRAME_TICK).await;
146 if this.update(cx, |view, cx| view.demo_frame(cx)).is_err() {
147 break;
148 }
149 }
150 })
151 .detach();
152 } else {
153 view.load_devices(cx);
154 }
155 view.sync_background(cx);
156 view.restart_preview();
157 view
158 }
159
160 pub fn pending_id(&self) -> u64 {
161 self.pending_id
162 }
163
164 fn take_frames(&mut self, cx: &mut Context<Self>) {
165 self.preview.take_frames(cx);
166 cx.notify();
167 }
168
169 fn demo_frame(&mut self, cx: &mut Context<Self>) {
170 if self.options.camera_on {
171 self.tick = self.tick.wrapping_add(1);
172 self.preview.publish_demo_frame(self.tick);
173 self.take_frames(cx);
174 }
175 }
176
177 fn load_devices(&mut self, cx: &mut Context<Self>) {
178 cx.spawn(async move |this, cx| {
179 let (cameras, devices) = cx
180 .background_executor()
181 .spawn(async { (list_cameras(), list_devices(&shared_factory())) })
182 .await;
183 this.update(cx, |view, cx| {
184 view.cameras = camera_entries(&cameras);
185 view.devices = devices;
186 cx.notify();
187 })
188 .ok();
189 })
190 .detach();
191 }
192
193 fn restart_preview(&mut self) {
194 if self.options.camera_on && !self.demo {
195 self.preview.start(&self.camera);
196 }
197 }
198
199 fn sync_background(&mut self, cx: &mut Context<Self>) {
200 let state = self.app.read(cx);
201 let pick = state.call_background.clone();
202 if pick == self.applied_background {
203 return;
204 }
205 if let Some(choice) = state.call_backgrounds.choice_for(&pick) {
206 self.preview.set_background(choice);
207 self.applied_background = pick;
208 }
209 cx.notify();
210 }
211
212 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
213 self.options.camera_on = !self.options.camera_on;
214 if self.options.camera_on {
215 self.restart_preview();
216 } else {
217 self.preview.stop(cx);
218 }
219 cx.notify();
220 }
221
222 fn toggle_mic(&mut self, cx: &mut Context<Self>) {
223 self.options.mic_on = !self.options.mic_on;
224 cx.notify();
225 }
226
227 fn set_audio(&mut self, audio: AudioChoice, cx: &mut Context<Self>) {
228 self.options.audio = audio;
229 cx.notify();
230 }
231
232 fn pick_camera(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
233 self.camera = choice.clone();
234 self.app
235 .update(cx, |state, cx| state.select_call_camera(choice, cx));
236 self.restart_preview();
237 cx.notify();
238 }
239
240 fn pick_input(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
241 self.options.input = choice;
242 cx.notify();
243 }
244
245 fn pick_output(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
246 self.options.output = choice;
247 cx.notify();
248 }
249
250 fn join(&mut self, cx: &mut Context<Self>) {
251 self.preview.stop(cx);
252 let options = self.options.clone();
253 self.app
254 .update(cx, |state, cx| state.confirm_prejoin(options, cx));
255 }
256
257 fn cancel(&mut self, cx: &mut Context<Self>) {
258 self.app.update(cx, |state, cx| state.cancel_prejoin(cx));
259 }
260
261 fn preview_status(&self) -> String {
262 match self.preview.failure() {
263 Some(reason) => format!("Camera could not start: {reason}"),
264 None => "Starting camera...".to_owned(),
265 }
266 }
267
268 fn preview_box(&self, cx: &mut Context<Self>) -> Div {
269 let state = self.app.read(cx);
270 let image = self
271 .options
272 .camera_on
273 .then(|| self.preview.image(Instant::now()))
274 .flatten();
275 let me = state.directory.me.clone();
276 let face = match (&image, self.options.camera_on) {
277 (Some(image), _) => img(ImageSource::Render(image.clone()))
278 .size_full()
279 .object_fit(ObjectFit::Cover)
280 .into_any_element(),
281 (None, true) => centered_note(&self.preview_status()),
282 (None, false) => v_flex()
283 .items_center()
284 .gap(px(10.))
285 .child(person_avatar(
286 &state.directory,
287 me.as_ref().map(|me| me.user_id.as_str()),
288 me.as_ref().map_or("You", |me| me.display_name.as_str()),
289 AVATAR_SIZE,
290 ))
291 .child(
292 div()
293 .text_size(px(13.))
294 .text_color(theme::text_muted())
295 .child(CAMERA_OFF_TEXT),
296 )
297 .into_any_element(),
298 };
299 div()
300 .debug_selector(|| "shell/islands/main/prejoin/preview".into())
301 .relative()
302 .w_full()
303 .h(px(PREVIEW_HEIGHT))
304 .flex_shrink(1.)
305 .min_h(px(PREVIEW_MIN_HEIGHT))
306 .flex()
307 .items_center()
308 .justify_center()
309 .overflow_hidden()
310 .rounded(px(PREVIEW_RADIUS))
311 .bg(theme::background())
312 .child(face)
313 }
314
315 fn controls(&self, cx: &mut Context<Self>) -> impl IntoElement {
316 let view = cx.entity();
317 let camera_view = view.clone();
318 let mic_view = view.clone();
319 let (camera_glyph, camera_bg, camera_fg) = if self.options.camera_on {
320 (IconName::Video, theme::accent(), theme::on_accent())
321 } else {
322 (IconName::VideoOff, theme::surface_raised(), theme::text())
323 };
324 let (mic_glyph, mic_bg, mic_fg) = if self.options.mic_on {
325 (IconName::Mic, theme::surface_raised(), theme::text())
326 } else {
327 (IconName::MicOff, theme::red(), theme::white())
328 };
329 let audio_on = self.options.audio == AudioChoice::Computer;
330 let backgrounds = BackgroundMenu::of(self.app.read(cx));
331 let background_app = self.app.clone();
332 h_flex()
333 .debug_selector(|| "shell/islands/main/prejoin/controls".into())
334 .flex_none()
335 .gap(px(10.))
336 .items_center()
337 .justify_center()
338 .child(
339 round_control("prejoin-camera", camera_glyph, camera_bg, camera_fg).on_click(
340 move |_, _, cx| camera_view.update(cx, |view, cx| view.toggle_camera(cx)),
341 ),
342 )
343 .child(
344 round_control("prejoin-mic", mic_glyph, mic_bg, mic_fg)
345 .when(!audio_on, |button| button.opacity(0.4).cursor_default())
346 .when(audio_on, |button| {
347 button.on_click(move |_, _, cx| {
348 mic_view.update(cx, |view, cx| view.toggle_mic(cx))
349 })
350 }),
351 )
352 .child(
353 Button::new("prejoin-background")
354 .outline()
355 .label("Background")
356 .icon(IconName::ChevronDown)
357 .dropdown_menu(move |menu: PopupMenu, _, _| {
358 background_items(menu, &background_app, &backgrounds)
359 }),
360 )
361 }
362
363 fn select(
364 &self,
365 spec: DeviceSelect,
366 pick: impl Fn(&mut PrejoinView, DeviceChoice, &mut Context<PrejoinView>) + Clone + 'static,
367 cx: &mut Context<Self>,
368 ) -> Div {
369 let DeviceSelect {
370 id,
371 label,
372 entries,
373 current,
374 enabled,
375 } = spec;
376 let view = cx.entity();
377 let face = label_of(&entries, &current);
378 let items_entries = entries;
379 let items_current = current;
380 let button = Button::new(id)
381 .outline()
382 .w_full()
383 .label(face)
384 .icon(IconName::ChevronDown)
385 .disabled(!enabled)
386 .dropdown_menu(move |menu, _, _| {
387 let view = view.clone();
388 let pick = pick.clone();
389 device_items(items_entries.clone(), &items_current, move |choice, cx| {
390 let pick = pick.clone();
391 view.update(cx, |view, cx| pick(view, choice, cx));
392 })
393 .into_iter()
394 .fold(menu, |menu, item| menu.item(item))
395 });
396 v_flex()
397 .flex_1()
398 .min_w_0()
399 .max_w(px(SELECT_WIDTH))
400 .gap(px(4.))
401 .child(
402 div()
403 .text_size(px(12.))
404 .text_color(theme::text_muted())
405 .child(label),
406 )
407 .child(div().w_full().overflow_hidden().child(button))
408 }
409
410 fn audio_choice(&self, choice: AudioChoice, cx: &mut Context<Self>) -> Stateful<Div> {
411 let selected = self.options.audio == choice;
412 let view = cx.entity();
413 h_flex()
414 .id(match choice {
415 AudioChoice::Computer => "prejoin-audio-computer",
416 AudioChoice::NoAudio => "prejoin-audio-none",
417 })
418 .h(px(32.))
419 .px(px(14.))
420 .items_center()
421 .rounded(px(8.))
422 .border_1()
423 .border_color(if selected {
424 theme::accent()
425 } else {
426 theme::border_strong()
427 })
428 .when(selected, |option| option.bg(theme::surface_raised()))
429 .cursor_pointer()
430 .text_size(px(13.))
431 .text_color(theme::text())
432 .child(choice.label())
433 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.set_audio(choice, cx)))
434 }
435}
436
437fn centered_note(text: &str) -> AnyElement {
438 div()
439 .text_size(px(13.))
440 .text_color(theme::text_muted())
441 .child(text.to_owned())
442 .into_any_element()
443}
444
445impl Render for PrejoinView {
446 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
447 let title = self
448 .app
449 .read(cx)
450 .prejoin
451 .as_ref()
452 .map(|pending| pending.join.title.clone())
453 .unwrap_or_default();
454 let audio_on = self.options.audio == AudioChoice::Computer;
455 let (cameras, camera) = (self.cameras.clone(), self.camera.clone());
456 let (inputs, input) = (self.devices.input_entries(), self.options.input.clone());
457 let (outputs, output) = (self.devices.output_entries(), self.options.output.clone());
458 let devices = h_flex()
459 .debug_selector(|| "shell/islands/main/prejoin/devices".into())
460 .flex_none()
461 .w_full()
462 .gap(px(10.))
463 .child(self.select(
464 DeviceSelect {
465 id: "prejoin-camera-select",
466 label: "Camera",
467 entries: cameras,
468 current: camera,
469 enabled: true,
470 },
471 |view, choice, cx| view.pick_camera(choice, cx),
472 cx,
473 ))
474 .child(self.select(
475 DeviceSelect {
476 id: "prejoin-mic-select",
477 label: "Microphone",
478 entries: inputs,
479 current: input,
480 enabled: audio_on,
481 },
482 |view, choice, cx| view.pick_input(choice, cx),
483 cx,
484 ))
485 .child(self.select(
486 DeviceSelect {
487 id: "prejoin-speaker-select",
488 label: "Speaker",
489 entries: outputs,
490 current: output,
491 enabled: audio_on,
492 },
493 |view, choice, cx| view.pick_output(choice, cx),
494 cx,
495 ));
496 let audio_row = h_flex()
497 .debug_selector(|| "shell/islands/main/prejoin/audio".into())
498 .flex_none()
499 .flex_wrap()
500 .gap(px(8.))
501 .child(self.audio_choice(AudioChoice::Computer, cx))
502 .child(self.audio_choice(AudioChoice::NoAudio, cx));
503 let cancel_view = cx.entity();
504 let join_view = cx.entity();
505 let actions = h_flex()
506 .debug_selector(|| "shell/islands/main/prejoin/actions".into())
507 .flex_none()
508 .gap(px(8.))
509 .justify_end()
510 .child(
511 Button::new("prejoin-cancel")
512 .ghost()
513 .label("Cancel")
514 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
515 )
516 .child(
517 Button::new("prejoin-join")
518 .primary()
519 .label("Join now")
520 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
521 );
522 v_flex()
523 .debug_selector(|| "shell/islands/main".into())
524 .size_full()
525 .p(px(PANE_PADDING))
526 .items_center()
527 .justify_center()
528 .rounded(px(10.))
529 .bg(theme::surface())
530 .overflow_hidden()
531 .child(
532 v_flex()
533 .debug_selector(|| "shell/islands/main/prejoin".into())
534 .w(px(CONTENT_WIDTH))
535 .max_w_full()
536 .max_h_full()
537 .min_h_0()
538 .gap(px(SECTION_GAP))
539 .child(
540 v_flex()
541 .flex_none()
542 .gap(px(2.))
543 .child(
544 div()
545 .truncate()
546 .text_size(px(20.))
547 .font_weight(FontWeight::SEMIBOLD)
548 .text_color(theme::text_strong())
549 .child(title),
550 )
551 .child(
552 div()
553 .truncate()
554 .text_size(px(13.))
555 .text_color(theme::text_muted())
556 .child("Choose your video and audio settings, then join"),
557 ),
558 )
559 .child(self.preview_box(cx))
560 .child(self.controls(cx))
561 .child(devices)
562 .child(audio_row)
563 .child(actions),
564 )
565 }
566}
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, OpenSaved, PreviousConversation, Scope, ShowShortcuts,
20 ToggleCallCamera, ToggleCallShare,
19 AcceptCall, DeclineCall, HangUpCall, JoinMeetingFromToast, NextConversation, OpenActivity,
20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope,
21 ShowShortcuts, ToggleCallCamera, ToggleCallShare,
21 22 };
22 23 use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
23 24 use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
@@ -81,6 +82,7 @@ pub struct AppShell {
81 82 sidebar: Entity<SidebarView>,
82 83 conversation: Entity<ConversationView>,
83 84 call_chat: Option<(String, Entity<ConversationView>)>,
85 prejoin: Option<Entity<PrejoinView>>,
84 86 switcher: Option<Entity<Switcher>>,
85 87 notifications: Entity<NotificationCenter>,
86 88 _call_windows: Entity<CallWindows>,
@@ -121,6 +123,19 @@ impl AppShell {
121 123 }
122 124 }
123 125
126 fn sync_prejoin(&mut self, window: &mut Window, cx: &mut Context<Self>) {
127 let wanted = self.state.read(cx).prejoin.clone();
128 let open = self.prejoin.as_ref().map(|view| view.read(cx).pending_id());
129 match (wanted, open) {
130 (Some(pending), Some(id)) if pending.id == id => {}
131 (Some(pending), _) => {
132 let app = self.state.clone();
133 self.prejoin = Some(cx.new(|cx| PrejoinView::new(app, &pending, window, cx)));
134 }
135 (None, _) => self.prejoin = None,
136 }
137 }
138
124 139 pub fn new(
125 140 state: Entity<AppState>,
126 141 open_target: Option<OpenTarget>,
@@ -222,6 +237,7 @@ impl AppShell {
222 237 sidebar,
223 238 conversation,
224 239 call_chat: None,
240 prejoin: None,
225 241 switcher: None,
226 242 notifications,
227 243 _call_windows: call_windows,
@@ -638,9 +654,12 @@ impl AppShell {
638 654 ),
639 655 ),
640 656 )
641 .child(match call_view {
642 Some(call_view) => call_view,
643 None => self
657 .child(match (call_view, self.prejoin.clone()) {
658 (Some(call_view), _) => call_view,
659 (None, Some(prejoin)) => prejoin
660 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
661 .into_any_element(),
662 (None, None) => self
644 663 .conversation
645 664 .clone()
646 665 .cached(
@@ -681,6 +700,7 @@ impl Render for AppShell {
681 700 }
682 701 let chat_thread = self.state.read(cx).call_chat_thread();
683 702 self.sync_call_chat(chat_thread, window, cx);
703 self.sync_prejoin(window, cx);
684 704 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
685 705 let state = self.state.read(cx);
686 706 let call_view =
@@ -762,6 +782,10 @@ impl Render for AppShell {
762 782 this.state
763 783 .update(cx, |state, cx| state.decline_ringing_call(cx));
764 784 }))
785 .on_action(cx.listener(|this, _: &JoinMeetingFromToast, _, cx| {
786 this.state
787 .update(cx, |state, cx| state.join_latest_meeting_toast(cx));
788 }))
765 789 .on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
766 790 this.state.update(cx, |state, cx| state.leave_call(cx));
767 791 }))
@@ -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, OpenSaved, PreviousConversation, Scope, ShowShortcuts,
20 OpenCallsTab, OpenChannelsTab, OpenChatsTab, OpenSaved, PreviousConversation, Scope,
20 ToggleCallCamera, ToggleCallShare,
21 ShowShortcuts, ToggleCallCamera, ToggleCallShare,
21};
22};
22use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
23use super::shortcuts_dialog::{ShortcutsDialog, ShortcutsDialogEvent};
23use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
24use super::sidebar::{SIDEBAR_WIDTH, SidebarView};
@@ -81,6 +82,7 @@ pub struct AppShell {
81 sidebar: Entity<SidebarView>,
82 sidebar: Entity<SidebarView>,
82 conversation: Entity<ConversationView>,
83 conversation: Entity<ConversationView>,
83 call_chat: Option<(String, Entity<ConversationView>)>,
84 call_chat: Option<(String, Entity<ConversationView>)>,
85 prejoin: Option<Entity<PrejoinView>>,
84 switcher: Option<Entity<Switcher>>,
86 switcher: Option<Entity<Switcher>>,
85 notifications: Entity<NotificationCenter>,
87 notifications: Entity<NotificationCenter>,
86 _call_windows: Entity<CallWindows>,
88 _call_windows: Entity<CallWindows>,
@@ -121,6 +123,19 @@ impl AppShell {
121 }
123 }
122 }
124 }
123
125
126 fn sync_prejoin(&mut self, window: &mut Window, cx: &mut Context<Self>) {
127 let wanted = self.state.read(cx).prejoin.clone();
128 let open = self.prejoin.as_ref().map(|view| view.read(cx).pending_id());
129 match (wanted, open) {
130 (Some(pending), Some(id)) if pending.id == id => {}
131 (Some(pending), _) => {
132 let app = self.state.clone();
133 self.prejoin = Some(cx.new(|cx| PrejoinView::new(app, &pending, window, cx)));
134 }
135 (None, _) => self.prejoin = None,
136 }
137 }
138
124 pub fn new(
139 pub fn new(
125 state: Entity<AppState>,
140 state: Entity<AppState>,
126 open_target: Option<OpenTarget>,
141 open_target: Option<OpenTarget>,
@@ -222,6 +237,7 @@ impl AppShell {
222 sidebar,
237 sidebar,
223 conversation,
238 conversation,
224 call_chat: None,
239 call_chat: None,
240 prejoin: None,
225 switcher: None,
241 switcher: None,
226 notifications,
242 notifications,
227 _call_windows: call_windows,
243 _call_windows: call_windows,
@@ -638,9 +654,12 @@ impl AppShell {
638 ),
654 ),
639 ),
655 ),
640 )
656 )
641 .child(match call_view {
657 .child(match (call_view, self.prejoin.clone()) {
642 Some(call_view) => call_view,
658 (Some(call_view), _) => call_view,
643 None => self
659 (None, Some(prejoin)) => prejoin
660 .cached(StyleRefinement::default().flex_1().min_w_0().h_full())
661 .into_any_element(),
662 (None, None) => self
644 .conversation
663 .conversation
645 .clone()
664 .clone()
646 .cached(
665 .cached(
@@ -681,6 +700,7 @@ impl Render for AppShell {
681 }
700 }
682 let chat_thread = self.state.read(cx).call_chat_thread();
701 let chat_thread = self.state.read(cx).call_chat_thread();
683 self.sync_call_chat(chat_thread, window, cx);
702 self.sync_call_chat(chat_thread, window, cx);
703 self.sync_prejoin(window, cx);
684 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
704 let chat_panel = self.call_chat.as_ref().map(|(_, view)| view.clone());
685 let state = self.state.read(cx);
705 let state = self.state.read(cx);
686 let call_view =
706 let call_view =
@@ -762,6 +782,10 @@ impl Render for AppShell {
762 this.state
782 this.state
763 .update(cx, |state, cx| state.decline_ringing_call(cx));
783 .update(cx, |state, cx| state.decline_ringing_call(cx));
764 }))
784 }))
785 .on_action(cx.listener(|this, _: &JoinMeetingFromToast, _, cx| {
786 this.state
787 .update(cx, |state, cx| state.join_latest_meeting_toast(cx));
788 }))
765 .on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
789 .on_action(cx.listener(|this, _: &HangUpCall, _, cx| {
766 this.state.update(cx, |state, cx| state.leave_call(cx));
790 this.state.update(cx, |state, cx| state.leave_call(cx));
767 }))
791 }))
crates/app/src/views/shortcuts.rs +2 −0
@@ -22,6 +22,7 @@ actions!(
22 22 NextConversation,
23 23 AcceptCall,
24 24 DeclineCall,
25 JoinMeetingFromToast,
25 26 HangUpCall,
26 27 ToggleCallCamera,
27 28 ToggleCallShare,
@@ -109,6 +110,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
109 110 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
110 111 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
111 112 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
113 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
112 114 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
113 115 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
114 116 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
@@ -22,6 +22,7 @@ actions!(
22 NextConversation,
22 NextConversation,
23 AcceptCall,
23 AcceptCall,
24 DeclineCall,
24 DeclineCall,
25 JoinMeetingFromToast,
25 HangUpCall,
26 HangUpCall,
26 ToggleCallCamera,
27 ToggleCallCamera,
27 ToggleCallShare,
28 ToggleCallShare,
@@ -109,6 +110,7 @@ pub const SHORTCUTS: &[Shortcut] = &[
109 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
110 shortcut!(Composer, Composer, "Schedule send", "ctrl-shift-enter", None, ScheduleSend),
110 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
111 shortcut!(Calls, GlobalOverTextFields, "Accept incoming call", "ctrl-shift-a", Some("cmd-shift-a"), AcceptCall),
111 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
112 shortcut!(Calls, GlobalOverTextFields, "Decline incoming call", "ctrl-shift-d", Some("cmd-shift-d"), DeclineCall),
113 shortcut!(Calls, GlobalOverTextFields, "Join the meeting from its reminder", "ctrl-shift-j", Some("cmd-shift-j"), JoinMeetingFromToast),
112 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
114 shortcut!(Calls, GlobalOverTextFields, "Hang up or leave", "ctrl-shift-h", Some("cmd-shift-h"), HangUpCall),
113 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
115 shortcut!(Calls, GlobalOverTextFields, "Mute or unmute", "ctrl-shift-m", None, ToggleCallMute),
114 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
116 shortcut!(Calls, GlobalOverTextFields, "Turn camera on or off", "ctrl-shift-o", Some("cmd-shift-o"), ToggleCallCamera),
crates/calling/src/call.rs +10 −0
@@ -1248,6 +1248,16 @@ async fn drive(
1248 1248 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
1249 1249 }
1250 1250 }
1251 Some(CallCommand::DisableAudio) => {
1252 let audio = live.audio.as_ref().expect("audio set above");
1253 if audio.uses_devices() {
1254 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
1255 factory.set_adm_recording_enabled(false);
1256 factory.set_adm_playout_enabled(false);
1257 }
1258 muted = apply_mute(MuteCommand::Mute, muted, audio, share_audio.as_ref(), &remote, control);
1259 control.send(CallUpdate::ListenOnly(true));
1260 }
1251 1261 Some(CallCommand::SelectInput(choice)) => {
1252 1262 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1253 1263 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
@@ -1248,6 +1248,16 @@ async fn drive(
1248 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
1248 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control);
1249 }
1249 }
1250 }
1250 }
1251 Some(CallCommand::DisableAudio) => {
1252 let audio = live.audio.as_ref().expect("audio set above");
1253 if audio.uses_devices() {
1254 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
1255 factory.set_adm_recording_enabled(false);
1256 factory.set_adm_playout_enabled(false);
1257 }
1258 muted = apply_mute(MuteCommand::Mute, muted, audio, share_audio.as_ref(), &remote, control);
1259 control.send(CallUpdate::ListenOnly(true));
1260 }
1251 Some(CallCommand::SelectInput(choice)) => {
1261 Some(CallCommand::SelectInput(choice)) => {
1252 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1262 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1253 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
1263 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
crates/calling/src/control.rs +1 −0
@@ -22,6 +22,7 @@ use crate::whiteboard::ContentShare;
22 22 #[derive(Debug, Clone, PartialEq, Eq)]
23 23 pub enum CallCommand {
24 24 Mute(MuteCommand),
25 DisableAudio,
25 26 SelectInput(DeviceChoice),
26 27 SelectOutput(DeviceChoice),
27 28 RefreshDevices,
@@ -22,6 +22,7 @@ use crate::whiteboard::ContentShare;
22#[derive(Debug, Clone, PartialEq, Eq)]
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub enum CallCommand {
23pub enum CallCommand {
24 Mute(MuteCommand),
24 Mute(MuteCommand),
25 DisableAudio,
25 SelectInput(DeviceChoice),
26 SelectInput(DeviceChoice),
26 SelectOutput(DeviceChoice),
27 SelectOutput(DeviceChoice),
27 RefreshDevices,
28 RefreshDevices,
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
@@ -21,7 +21,10 @@ pub mod settings;
21 21 pub mod transcripts;
22 22 pub mod translate;
23 23
24 pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
24 pub use calendar::{
25 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Repeat, Reply, ResponseType,
26 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
27 };
25 28 pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
26 29 pub use cards::{
27 30 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
@@ -21,7 +21,10 @@ pub mod settings;
21pub mod transcripts;
21pub mod transcripts;
22pub mod translate;
22pub mod translate;
23
23
24pub use calendar::{Calendar, CalendarEvent, ResponseType, meet_now_join_url, parse_calendar_events};
24pub use calendar::{
25 Attendee, Calendar, CalendarEvent, CreatedEvent, NewEvent, Repeat, Reply, ResponseType,
26 meet_now_join_url, new_event_body, parse_calendar_events, parse_created_event,
27};
25pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
28pub use calllog::{CallDirection, CallLogEntry, CallOutcome};
26pub use cards::{
29pub use cards::{
27 CardActions, ChatApp, InvokeRequest, InvokeResponse, TaskContent, TaskContinue, TaskResponse,
30 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",