BlueGit

ict rusty-teams

feat(ui): English and German UI locale with OS default

Add rust-i18n catalog, persisted language preference, localized chrome/
settings/calls notices/tray, and OpenSpec ui-locale capability.

metis Joachim Mild · pushed by metis

Authored 2026-11-12 · 2 weeks ago

Hash
e41f9c9b68b04d68b0a6127dd2a4de2cd24536fd
Parent
b07109fc
75 files changed +6807 −1624
CHANGELOG.md added +68 −0
@@ -0,0 +1,68 @@
1 # Changelog
2
3 ## [0.3.0-joe.5] - 2026-11-12
4
5 ### Added
6
7 - UI language: English and German (Germany), with OS locale on first start
8 (`de*` → German, otherwise English) and a persisted override under Appearance.
9 - `rust-i18n` catalog for app chrome, settings, calls notices, tray, and agents;
10 missing keys fall back to English.
11
12 ### Changed
13
14 - Call notices use stable i18n keys (optional detail payload) and are localized
15 at the UI boundary instead of shipping English literals from calling.
16
17 ## [0.3.0-joe.4] - 2026-11-12
18
19 ### Fixed
20
21 - Camera capture prefers MJPEG 1080p/720p at 30 fps on USB 2.0 webcams (e.g. C930e)
22 instead of falling back to YUYV 1080p at 5 fps; opens under 30 fps are rejected
23 when a faster format exists.
24 - MJPEG frames decode locally (zune-jpeg → I420) with reusable buffers.
25 - UVC best-effort: disable exposure dynamic framerate and set 50 Hz power-line
26 frequency; call reports log the chosen format plus capture fps / decode time.
27
28 ## [0.3.0-joe.3] - 2026-11-12
29
30 ### Fixed
31
32 - 1:1 escalation answers no longer emit an extra folded gallery m-line (`mid 3-0`),
33 which triggered Teams `InvalidNumberOfMedia` / «Incorrect number of media».
34 - Same-peer renegotiation keeps a short grace after the answer timeout so a late
35 camera answer (`recvonly`) can still be applied instead of rolling back send.
36 - Camera open survives UVC `CameraFormat` property failures (Closest NV12 first;
37 AbsoluteHighest only as last resort).
38
39 ## [0.3.0-joe.2] - 2026-11-12
40
41 ### Added
42
43 - Camera video quality setting: Auto, 720p, or 1080p (no 4K), in call and prejoin
44 camera menus; choice persists and applies to capture plus stage receive limits.
45
46 ### Changed
47
48 - Auto / 1080p prefer 1080p capture and advertise matching send capabilities;
49 stage receive uses 1080p-class budgets when allowed.
50 - CI tests run on Forgejo only; GitHub Actions are mirror stubs.
51
52 ## [0.3.0-joe.1] - 2026-11-12
53
54 ### Added
55
56 - Forgejo as source of truth (`devops-geek/rusty-teams`) with push mirror to GitHub.
57 - Linux release packages: `.deb`, `.rpm`, Arch `.pkg.tar.zst`, Flatpak bundle.
58 - Forgejo Actions builds for Windows amd64, Windows ARM64, and macOS universal.
59 - Local share preview window in the meeting chat (and in the mini call window).
60
61 ### Fixed
62
63 - Wayland screen share via xdg-desktop-portal (KDE, GNOME, Hyprland) without the
64 «shared source is gone» toast after confirming the desktop dialog.
65
66 ## [0.3.0] - 2026-11-10
67
68 Upstream-aligned baseline on the fork before Forgejo SoT cutover.
@@ -0,0 +1,68 @@
1# Changelog
2
3## [0.3.0-joe.5] - 2026-11-12
4
5### Added
6
7- UI language: English and German (Germany), with OS locale on first start
8 (`de*` → German, otherwise English) and a persisted override under Appearance.
9- `rust-i18n` catalog for app chrome, settings, calls notices, tray, and agents;
10 missing keys fall back to English.
11
12### Changed
13
14- Call notices use stable i18n keys (optional detail payload) and are localized
15 at the UI boundary instead of shipping English literals from calling.
16
17## [0.3.0-joe.4] - 2026-11-12
18
19### Fixed
20
21- Camera capture prefers MJPEG 1080p/720p at 30 fps on USB 2.0 webcams (e.g. C930e)
22 instead of falling back to YUYV 1080p at 5 fps; opens under 30 fps are rejected
23 when a faster format exists.
24- MJPEG frames decode locally (zune-jpeg → I420) with reusable buffers.
25- UVC best-effort: disable exposure dynamic framerate and set 50 Hz power-line
26 frequency; call reports log the chosen format plus capture fps / decode time.
27
28## [0.3.0-joe.3] - 2026-11-12
29
30### Fixed
31
32- 1:1 escalation answers no longer emit an extra folded gallery m-line (`mid 3-0`),
33 which triggered Teams `InvalidNumberOfMedia` / «Incorrect number of media».
34- Same-peer renegotiation keeps a short grace after the answer timeout so a late
35 camera answer (`recvonly`) can still be applied instead of rolling back send.
36- Camera open survives UVC `CameraFormat` property failures (Closest NV12 first;
37 AbsoluteHighest only as last resort).
38
39## [0.3.0-joe.2] - 2026-11-12
40
41### Added
42
43- Camera video quality setting: Auto, 720p, or 1080p (no 4K), in call and prejoin
44 camera menus; choice persists and applies to capture plus stage receive limits.
45
46### Changed
47
48- Auto / 1080p prefer 1080p capture and advertise matching send capabilities;
49 stage receive uses 1080p-class budgets when allowed.
50- CI tests run on Forgejo only; GitHub Actions are mirror stubs.
51
52## [0.3.0-joe.1] - 2026-11-12
53
54### Added
55
56- Forgejo as source of truth (`devops-geek/rusty-teams`) with push mirror to GitHub.
57- Linux release packages: `.deb`, `.rpm`, Arch `.pkg.tar.zst`, Flatpak bundle.
58- Forgejo Actions builds for Windows amd64, Windows ARM64, and macOS universal.
59- Local share preview window in the meeting chat (and in the mini call window).
60
61### Fixed
62
63- Wayland screen share via xdg-desktop-portal (KDE, GNOME, Hyprland) without the
64 «shared source is gone» toast after confirming the desktop dialog.
65
66## [0.3.0] - 2026-11-10
67
68Upstream-aligned baseline on the fork before Forgejo SoT cutover.
Cargo.lock +1 −0
@@ -322,6 +322,7 @@ dependencies = [
322 322 "raw-window-handle",
323 323 "resvg 0.46.0",
324 324 "rodio",
325 "rust-i18n",
325 326 "serde",
326 327 "serde_json",
327 328 "session",
@@ -322,6 +322,7 @@ dependencies = [
322 "raw-window-handle",
322 "raw-window-handle",
323 "resvg 0.46.0",
323 "resvg 0.46.0",
324 "rodio",
324 "rodio",
325 "rust-i18n",
325 "serde",
326 "serde",
326 "serde_json",
327 "serde_json",
327 "session",
328 "session",
crates/app-base/Cargo.toml +1 −0
@@ -30,6 +30,7 @@ image = { version = "0.25", default-features = false, features = ["bmp", "gif",
30 30 raw-window-handle = "0.6"
31 31 sha2 = "0.10"
32 32 sys-locale = "0.3"
33 rust-i18n = "4.2"
33 34 resvg = { version = "0.46", default-features = false, features = ["text"] }
34 35
35 36 [target.'cfg(target_os = "linux")'.dependencies]
@@ -30,6 +30,7 @@ image = { version = "0.25", default-features = false, features = ["bmp", "gif",
30raw-window-handle = "0.6"
30raw-window-handle = "0.6"
31sha2 = "0.10"
31sha2 = "0.10"
32sys-locale = "0.3"
32sys-locale = "0.3"
33rust-i18n = "4.2"
33resvg = { version = "0.46", default-features = false, features = ["text"] }
34resvg = { version = "0.46", default-features = false, features = ["text"] }
34
35
35[target.'cfg(target_os = "linux")'.dependencies]
36[target.'cfg(target_os = "linux")'.dependencies]
crates/app-base/locales/app.yml added +1168 −0
@@ -0,0 +1,1168 @@
1 _version: 2
2 common:
3 cancel:
4 en: Cancel
5 de: Abbrechen
6 save:
7 en: Save
8 de: Speichern
9 close:
10 en: Close
11 de: Schließen
12 delete:
13 en: Delete
14 de: Löschen
15 ok:
16 en: OK
17 de: OK
18 add:
19 en: Add
20 de: Hinzufügen
21 remove:
22 en: Remove
23 de: Entfernen
24 join:
25 en: Join
26 de: Beitreten
27 leave:
28 en: Leave
29 de: Verlassen
30 retry:
31 en: Retry
32 de: Erneut versuchen
33 invite:
34 en: Invite
35 de: Einladen
36 admit:
37 en: Admit
38 de: Zulassen
39 deny:
40 en: Deny
41 de: Ablehnen
42 stop:
43 en: Stop
44 de: Stoppen
45 resume:
46 en: Resume
47 de: Fortsetzen
48 done:
49 en: Done
50 de: Fertig
51 send:
52 en: Send
53 de: Senden
54 sending:
55 en: Sending...
56 de: Wird gesendet...
57 you:
58 en: You
59 de: Sie
60 create:
61 en: Create
62 de: Erstellen
63 attach:
64 en: Attach
65 de: Anhängen
66 chat:
67 en: Chat
68 de: Chat
69 call:
70 en: Call
71 de: Anruf
72 settings:
73 en: Settings
74 de: Einstellungen
75 open:
76 en: Open
77 de: Öffnen
78 quit:
79 en: Quit
80 de: Beenden
81 notice:
82 generic_detail:
83 en: "Something went wrong: %{detail}"
84 de: "Etwas ist schiefgelaufen: %{detail}"
85 settings:
86 search:
87 no_results:
88 en: No settings found
89 de: Keine Einstellungen gefunden
90 nav:
91 general:
92 en: General
93 de: Allgemein
94 notifications:
95 en: Notifications and activity
96 de: Benachrichtigungen und Aktivität
97 appearance:
98 en: Appearance and accessibility
99 de: Darstellung und Barrierefreiheit
100 chats:
101 en: Chats and channels
102 de: Chats und Kanäle
103 calls:
104 en: Calls
105 de: Anrufe
106 calendar:
107 en: Calendar
108 de: Kalender
109 devices:
110 en: Devices
111 de: Geräte
112 agents:
113 en: Agents
114 de: Agents
115 mcp:
116 en: MCP
117 de: MCP
118 about:
119 en: About
120 de: Info
121 caption:
122 system:
123 en: SYSTEM
124 de: SYSTEM
125 compose_box:
126 en: COMPOSE BOX
127 de: EINGABEFELD
128 translation:
129 en: TRANSLATION
130 de: ÜBERSETZUNG
131 language:
132 en: LANGUAGE
133 de: SPRACHE
134 theme:
135 en: THEME
136 de: DESIGN
137 app_icon:
138 en: APP ICON
139 de: APP-SYMBOL
140 appearance_and_sound:
141 en: APPEARANCE AND SOUND
142 de: DARSTELLUNG UND TON
143 sound:
144 en: SOUND
145 de: TON
146 general:
147 auto_start:
148 en: Auto-start Teams
149 de: Teams automatisch starten
150 open_in_background:
151 en: Open application in background
152 de: Anwendung im Hintergrund starten
153 close_to_tray:
154 en: On close, keep the application running
155 de: Beim Schließen Anwendung weiterlaufen lassen
156 close_to_tray_detail:
157 en: The title bar X hides the window to the tray
158 de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
159 up_arrow:
160 en: Up arrow key behaviour in compose box
161 de: Verhalten der Aufwärtspfeil-Taste im Eingabefeld
162 up_arrow_detail:
163 en: Choose what happens when you press Up arrow at the beginning of the compose box.
164 de: Legen Sie fest, was passiert, wenn Sie am Anfang des Eingabefelds die Aufwärtspfeil-Taste drücken.
165 translation_not_loaded:
166 en: Translation settings not loaded yet
167 de: Übersetzungseinstellungen noch nicht geladen
168 translation_title:
169 en: Translation
170 de: Übersetzung
171 translate_into:
172 en: Translate messages into this language
173 de: Nachrichten in diese Sprache übersetzen
174 behavior_title:
175 en: How to handle messages in other languages
176 de: Umgang mit Nachrichten in anderen Sprachen
177 behavior_ask:
178 en: Ask me before translating
179 de: Vor dem Übersetzen nachfragen
180 behavior_auto:
181 en: Auto-translate all messages
182 de: Alle Nachrichten automatisch übersetzen
183 behavior_never:
184 en: Never translate
185 de: Nie übersetzen
186 never_translate:
187 en: Never translate messages in these languages
188 de: Nachrichten in diesen Sprachen nie übersetzen
189 notifications:
190 flash_taskbar:
191 en: Flash taskbar when notifications are received
192 de: Taskleiste bei Benachrichtigungen blinken lassen
193 flash_taskbar_detail:
194 en: On new messages, until you open the window
195 de: Bei neuen Nachrichten, bis Sie das Fenster öffnen
196 play_sounds:
197 en: Play sounds with notifications
198 de: Töne bei Benachrichtigungen abspielen
199 urgent_sounds:
200 en: Play sounds with urgent and priority contact notifications
201 de: Töne bei dringenden und Prioritätskontakt-Benachrichtigungen
202 call_sounds:
203 en: Play sounds with incoming calls, requests to join, and meeting start notifications
204 de: Töne bei eingehenden Anrufen, Beitrittsanfragen und Besprechungsstarts
205 busy_sounds:
206 en: Play sounds when I'm busy or in a meeting
207 de: Töne abspielen, wenn ich beschäftigt bin oder in einer Besprechung
208 hide_in_calls:
209 en: Hide notifications during calls and meetings
210 de: Benachrichtigungen während Anrufen und Besprechungen ausblenden
211 hide_in_calls_detail:
212 en: No message toasts while a call is active
213 de: Keine Nachrichten-Toasts während ein Anruf aktiv ist
214 position:
215 en: Position on the screen
216 de: Position auf dem Bildschirm
217 position_detail:
218 en: Corner of the main screen
219 de: Ecke des Hauptbildschirms
220 test:
221 en: Test notification
222 de: Testbenachrichtigung
223 test_detail:
224 en: Shows a toast with the settings above
225 de: Zeigt einen Toast mit den obigen Einstellungen
226 send_test:
227 en: Send test notification
228 de: Testbenachrichtigung senden
229 notification_sound:
230 en: Notification sound
231 de: Benachrichtigungston
232 urgent_sound:
233 en: Urgent sound
234 de: Dringlichkeitston
235 chat_messages:
236 en: Chat message notifications
237 de: Chatnachrichten-Benachrichtigungen
238 meeting_chats:
239 en: Meeting chat notifications
240 de: Besprechungschat-Benachrichtigungen
241 likes_reactions:
242 en: Likes and reactions
243 de: Likes und Reaktionen
244 teams_channels:
245 en: Teams and channels
246 de: Teams und Kanäle
247 show_preview:
248 en: Show message preview
249 de: Nachrichtenvorschau anzeigen
250 appearance:
251 color_scheme:
252 en: Color scheme
253 de: Farbschema
254 color_scheme_detail:
255 en: The colors to use for Rusty Teams
256 de: Die Farben für Rusty Teams
257 theme:
258 en: Theme
259 de: Design
260 theme_detail:
261 en: The theme to use for Teams
262 de: Das Design für Teams
263 theme_follow_os:
264 en: Follow operating system theme
265 de: Systemdesign folgen
266 theme_light:
267 en: Light
268 de: Hell
269 theme_dark:
270 en: Dark
271 de: Dunkel
272 theme_high_contrast:
273 en: High contrast
274 de: Hoher Kontrast
275 app_icon:
276 en: App icon
277 de: App-Symbol
278 app_icon_detail_windows:
279 en: Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe
280 de: In Titelleiste, Taskleiste und Infobereich. Angeheftete Verknüpfungen behalten das Symbol der .exe
281 app_icon_detail:
282 en: Shown in the title bar, taskbar and tray
283 de: In Titelleiste, Taskleiste und Infobereich
284 language:
285 title:
286 en: Language
287 de: Sprache
288 detail:
289 en: Language for Rusty Teams and controls
290 de: Sprache für Rusty Teams und Steuerelemente
291 follow_system:
292 en: Follow system
293 de: Systemeinstellung folgen
294 english:
295 en: English
296 de: Englisch
297 german:
298 en: Deutsch
299 de: Deutsch
300 chats:
301 density:
302 en: Message density
303 de: Nachrichtendichte
304 read_receipts:
305 en: Read receipts
306 de: Lesebestätigungen
307 message_actions:
308 en: Show message actions on right click
309 de: Nachrichtenaktionen per Rechtsklick anzeigen
310 muted_section:
311 en: Show muted items in their own section
312 de: Stummgeschaltete Einträge in eigenem Abschnitt anzeigen
313 enter_to:
314 en: When writing a message, press Enter to
315 de: Beim Schreiben einer Nachricht führt Eingabetaste zu
316 markdown:
317 en: Format messages using mark-down
318 de: Nachrichten mit Mark-down formatieren
319 markdown_detail:
320 en: Use mark-down language to define the structure and appearance of messages. Your formatting will take effect once you send your message. When this is on, the formatting options menu won't be visible.
321 de: Verwenden Sie Mark-down, um Struktur und Darstellung von Nachrichten festzulegen. Die Formatierung gilt nach dem Senden. Ist diese Option aktiv, ist das Formatierungsmenü ausgeblendet.
322 calls:
323 ringtones:
324 en: Ringtones
325 de: Klingeltöne
326 rail:
327 activity:
328 en: Activity
329 de: Aktivität
330 chat:
331 en: Chat
332 de: Chat
333 teams:
334 en: Teams
335 de: Teams
336 calendar:
337 en: Calendar
338 de: Kalender
339 calls:
340 en: Calls
341 de: Anrufe
342 agents:
343 en: Agents
344 de: Agents
345 shortcut_activity:
346 en: Open Activity
347 de: Aktivität öffnen
348 shortcut_chats:
349 en: Show Chats
350 de: Chats anzeigen
351 shortcut_channels:
352 en: Show Channels
353 de: Kanäle anzeigen
354 shortcut_calendar:
355 en: Open Calendar
356 de: Kalender öffnen
357 shortcut_calls:
358 en: Show Calls
359 de: Anrufe anzeigen
360 shortcut_agents:
361 en: Open Agents
362 de: Agents öffnen
363 tray:
364 open:
365 en: Open
366 de: Öffnen
367 quit:
368 en: Quit
369 de: Beenden
370 do_not_disturb:
371 en: Do not disturb
372 de: Nicht stören
373 notifications:
374 en: Notifications
375 de: Benachrichtigungen
376 mute_sound:
377 en: Mute sound
378 de: Ton stumm schalten
379 calls:
380 notice:
381 not_connected:
382 en: Not connected to Teams yet
383 de: Noch nicht mit Teams verbunden
384 read_only:
385 en: Calls are off in read-only mode
386 de: Anrufe sind im Nur-Lesen-Modus deaktiviert
387 not_callable:
388 en: This chat cannot be called
389 de: Dieser Chat kann nicht angerufen werden
390 meeting_unavailable:
391 en: This meeting cannot be joined
392 de: Dieser Besprechung kann nicht beigetreten werden
393 answer_failed:
394 en: Could not answer the call
395 de: Anruf konnte nicht angenommen werden
396 consult_ended:
397 en: The consultation ended
398 de: Die Rücksprache ist beendet
399 report_saved:
400 en: Test report saved
401 de: Testbericht gespeichert
402 response_failed:
403 en: Could not send your response
404 de: Ihre Antwort konnte nicht gesendet werden
405 delete_failed:
406 en: Could not delete the meeting
407 de: Besprechung konnte nicht gelöscht werden
408 delete_read_only:
409 en: Meetings cannot be deleted in read-only mode.
410 de: Besprechungen können im Nur-Lesen-Modus nicht gelöscht werden.
411 no_meeting_chat:
412 en: This meeting chat is not available
413 de: Dieser Besprechungschat ist nicht verfügbar
414 invite_failed:
415 en: Could not add that person
416 de: Diese Person konnte nicht hinzugefügt werden
417 no_peer:
418 en: This call cannot be extended
419 de: Dieser Anruf kann nicht erweitert werden
420 missed:
421 en: Call missed
422 de: Anruf verpasst
423 not_found:
424 en: Could not find that meeting
425 de: Diese Besprechung wurde nicht gefunden
426 meet_now_failed:
427 en: Could not start the meeting
428 de: Besprechung konnte nicht gestartet werden
429 consent_first:
430 en: Accept the recording notice first
431 de: Bitte zuerst den Aufzeichnungshinweis bestätigen
432 on_hold:
433 en: Resume the call first
434 de: Setzen Sie den Anruf zuerst fort
435 change_running:
436 en: Another change is still running, try again in a moment
437 de: Eine andere Änderung läuft noch, versuchen Sie es gleich erneut
438 video_failed:
439 en: Video could not start, the call stays audio only
440 de: Video konnte nicht starten, der Anruf bleibt nur Audio
441 share_queued:
442 en: Sharing starts in a moment
443 de: Freigabe startet gleich
444 share_refused:
445 en: The other side did not accept the screen share
446 de: Die Gegenseite hat die Bildschirmfreigabe nicht akzeptiert
447 portal_unavailable:
448 en: Screen sharing needs a desktop portal on this system
449 de: Bildschirmfreigabe benötigt auf diesem System ein Desktop-Portal
450 files_later:
451 en: Files can be added once the chat exists.
452 de: Dateien können hinzugefügt werden, sobald der Chat existiert.
453 calendar_load_failed:
454 en: We couldn't load your calendar.
455 de: Ihr Kalender konnte nicht geladen werden.
456 no_calls:
457 en: No calls yet
458 de: Noch keine Anrufe
459 video_starts_once_connected:
460 en: Video starts once the call is connected
461 de: Video startet, sobald der Anruf verbunden ist
462 call_transferred:
463 en: Call transferred
464 de: Anruf weitergeleitet
465 transfer_failed:
466 en: The transfer did not go through
467 de: Die Weiterleitung ist fehlgeschlagen
468 recording_join_failed:
469 en: The recording service could not join
470 de: Der Aufzeichnungsdienst konnte nicht beitreten
471 captions_join_failed:
472 en: The captions service could not join
473 de: Der Untertitel-Dienst konnte nicht beitreten
474 caption_language_failed:
475 en: Could not change the spoken language
476 de: Gesprochene Sprache konnte nicht geändert werden
477 camera_start:
478 en: "Camera could not start: %{detail}"
479 de: "Kamera konnte nicht starten: %{detail}"
480 camera_restart:
481 en: "Camera could not restart: %{detail}"
482 de: "Kamera konnte nicht neu starten: %{detail}"
483 sharing_start:
484 en: "Sharing could not start: %{detail}"
485 de: "Freigabe konnte nicht starten: %{detail}"
486 raise_hand_failed:
487 en: Could not raise your hand
488 de: Hand heben ist fehlgeschlagen
489 lower_hand_failed:
490 en: Could not lower your hand
491 de: Hand senken ist fehlgeschlagen
492 lower_that_hand_failed:
493 en: Could not lower that hand
494 de: Diese Hand konnte nicht gesenkt werden
495 lower_all_hands_failed:
496 en: Could not lower all hands
497 de: Alle Hände konnten nicht gesenkt werden
498 confirm_recording_failed:
499 en: Could not confirm the recording notice
500 de: Aufzeichnungshinweis konnte nicht bestätigt werden
501 hold_failed:
502 en: Could not put the call on hold
503 de: Anruf konnte nicht gehalten werden
504 resume_failed:
505 en: Could not resume the call
506 de: Anruf konnte nicht fortgesetzt werden
507 transfer_not_allowed:
508 en: This call cannot be transferred
509 de: Dieser Anruf kann nicht weitergeleitet werden
510 transfer_call_failed:
511 en: Could not transfer the call
512 de: Anruf konnte nicht weitergeleitet werden
513 transferring:
514 en: "Transferring to %{detail}..."
515 de: "Weiterleitung an %{detail}..."
516 whiteboards_meetings_only:
517 en: Whiteboards belong to meetings
518 de: Whiteboards gehören zu Besprechungen
519 whiteboard_open_failed:
520 en: The whiteboard could not be opened
521 de: Das Whiteboard konnte nicht geöffnet werden
522 reaction_failed:
523 en: Could not send the reaction
524 de: Reaktion konnte nicht gesendet werden
525 recording_not_started:
526 en: The recording did not start
527 de: Die Aufzeichnung hat nicht gestartet
528 recording_start_failed:
529 en: The recording could not start
530 de: Die Aufzeichnung konnte nicht starten
531 captions_start_failed:
532 en: Captions could not start
533 de: Untertitel konnten nicht starten
534 hold_change_failed:
535 en: The hold did not go through
536 de: Halten ist fehlgeschlagen
537 recording_stop_failed:
538 en: The recording could not be stopped
539 de: Die Aufzeichnung konnte nicht gestoppt werden
540 background_image_failed:
541 en: That background image could not be used
542 de: Dieses Hintergrundbild konnte nicht verwendet werden
543 camera_stopped:
544 en: "Camera stopped: %{detail}"
545 de: "Kamera gestoppt: %{detail}"
546 screen_share_stopped:
547 en: "Screen share stopped: %{detail}"
548 de: "Bildschirmfreigabe gestoppt: %{detail}"
549 admit_failed:
550 en: Could not admit that person
551 de: Diese Person konnte nicht zugelassen werden
552 admit_all_failed:
553 en: Could not admit everyone
554 de: Nicht alle konnten zugelassen werden
555 deny_failed:
556 en: Could not deny that person
557 de: Diese Person konnte nicht abgewiesen werden
558 remove_participant_failed:
559 en: Could not remove that person
560 de: Diese Person konnte nicht entfernt werden
561 mute_participant_failed:
562 en: Could not mute that person
563 de: Diese Person konnte nicht stummgeschaltet werden
564 mute_all_failed:
565 en: Could not mute everyone
566 de: Nicht alle konnten stummgeschaltet werden
567 meeting_lock_failed:
568 en: Could not change the meeting lock
569 de: Besprechungssperre konnte nicht geändert werden
570 change_role_failed:
571 en: Could not change that role
572 de: Diese Rolle konnte nicht geändert werden
573 mic_setting_failed:
574 en: Could not change that microphone setting
575 de: Diese Mikrofoneinstellung konnte nicht geändert werden
576 camera_setting_failed:
577 en: Could not change that camera setting
578 de: Diese Kameraeinstellung konnte nicht geändert werden
579 attendee_settings_failed:
580 en: Could not change the attendee settings
581 de: Teilnehmereinstellungen konnten nicht geändert werden
582 invite_person_failed:
583 en: Could not invite that person
584 de: Diese Person konnte nicht eingeladen werden
585 spotlight_failed:
586 en: Could not spotlight that person
587 de: Diese Person konnte nicht hervorgehoben werden
588 stop_spotlight_failed:
589 en: Could not stop the spotlight
590 de: Hervorhebung konnte nicht beendet werden
591 page:
592 title:
593 en: Calls
594 de: Anrufe
595 history:
596 en: History
597 de: Verlauf
598 speed_dial:
599 en: Speed dial
600 de: Kurzwahl
601 speed_dial_empty:
602 en: Add people to speed dial for quick access.
603 de: Personen zur Kurzwahl hinzufügen für schnellen Zugriff.
604 speed_dial_add:
605 en: Add to speed dial
606 de: Zur Kurzwahl hinzufügen
607 pick_one:
608 en: Pick one person to call
609 de: Eine Person zum Anrufen wählen
610 chrome:
611 video_call:
612 en: Video call
613 de: Videoanruf
614 audio_call:
615 en: Audio call
616 de: Audioanruf
617 call_options:
618 en: Call options
619 de: Anrufoptionen
620 meet_now:
621 en: Meet now
622 de: Jetzt besprechen
623 stop_sharing:
624 en: Stop sharing
625 de: Freigabe beenden
626 raise_hand:
627 en: Raise hand
628 de: Hand heben
629 lower_hand:
630 en: Lower hand
631 de: Hand senken
632 lower_all_hands:
633 en: Lower all hands
634 de: Alle Hände senken
635 end_meeting_for_all:
636 en: End meeting for everyone
637 de: Besprechung für alle beenden
638 open_chat:
639 en: Open the chat
640 de: Chat öffnen
641 close_chat:
642 en: Close the chat
643 de: Chat schließen
644 share_entire_screen:
645 en: Share entire screen
646 de: Gesamten Bildschirm freigeben
647 share_screen_n:
648 en: "Share screen %{n}"
649 de: "Bildschirm %{n} freigeben"
650 share_window:
651 en: Share a window
652 de: Fenster freigeben
653 share_window_ellipsis:
654 en: Share a window...
655 de: Fenster freigeben...
656 computer_sound_on:
657 en: Computer sound on
658 de: Computerton ein
659 computer_sound_off:
660 en: Computer sound off
661 de: Computerton aus
662 sharing_label:
663 en: "You are sharing: %{label}"
664 de: "Sie geben frei: %{label}"
665 no_microphone:
666 en: No microphone found
667 de: Kein Mikrofon gefunden
668 audio_off_meeting:
669 en: Audio is off for this meeting
670 de: Audio ist für diese Besprechung aus
671 no_camera:
672 en: No camera found
673 de: Keine Kamera gefunden
674 sharing_when_connected:
675 en: Sharing starts once the call is connected
676 de: Freigabe startet, sobald der Anruf verbunden ist
677 no_windows:
678 en: No windows found
679 de: Keine Fenster gefunden
680 lobby_waiting:
681 en: Waiting in the lobby...
682 de: Warten in der Lobby...
683 include_computer_sound:
684 en: Include computer sound
685 de: Computerton einbeziehen
686 optimize_motion:
687 en: Optimize for motion
688 de: Für Bewegung optimieren
689 show_me_over_content:
690 en: Show me over my content
691 de: Mich über meinen Inhalt anzeigen
692 camera_on_first:
693 en: Turn your camera on first
694 de: Kamera zuerst einschalten
695 noise_suppression:
696 en: Noise suppression
697 de: Rauschunterdrückung
698 music_mode:
699 en: Music mode
700 de: Musikmodus
701 push_to_talk:
702 en: Unmuted - release Ctrl+Space to mute
703 de: Entstummt – Strg+Leertaste loslassen zum Stummschalten
704 hand_raised:
705 en: Hand raised
706 de: Hand gehoben
707 hand_position:
708 en: "Hand %{position}"
709 de: "Hand %{position}"
710 reconnecting:
711 en: Reconnecting...
712 de: Verbindung wird wiederhergestellt...
713 microphone:
714 en: Microphone
715 de: Mikrofon
716 speaker:
717 en: Speaker
718 de: Lautsprecher
719 return_main:
720 en: Return to main meeting
721 de: Zur Hauptbesprechung zurück
722 breakout_room:
723 en: Breakout room
724 de: Breakout-Raum
725 on_hold:
726 en: On hold
727 de: Gehalten
728 you_on_hold:
729 en: You're on hold
730 de: Sie sind in der Warteschleife
731 open_in_browser:
732 en: Open in browser
733 de: Im Browser öffnen
734 recording_notice:
735 en: This meeting is being recorded
736 de: Diese Besprechung wird aufgezeichnet
737 recording_accept_hint:
738 en: Your microphone and camera stay off until you accept.
739 de: Mikrofon und Kamera bleiben aus, bis Sie zustimmen.
740 transfer:
741 en: Transfer
742 de: Weiterleiten
743 resume_person:
744 en: "Resume %{name}"
745 de: "%{name} fortsetzen"
746 video_quality:
747 en: Video quality
748 de: Videoqualität
749 auto:
750 en: Auto
751 de: Auto
752 effects:
753 en: Effects
754 de: Effekte
755 mirror_video:
756 en: Mirror my video
757 de: Video spiegeln
758 auto_framing:
759 en: Auto framing
760 de: Automatischer Bildausschnitt
761 adjust_brightness:
762 en: Adjust brightness
763 de: Helligkeit anpassen
764 soft_focus:
765 en: Soft focus
766 de: Weichzeichner
767 background:
768 en: Background
769 de: Hintergrund
770 background_none:
771 en: None
772 de: Keiner
773 background_blur:
774 en: Blur
775 de: Unscharf
776 add_image:
777 en: Add image...
778 de: Bild hinzufügen...
779 prejoin:
780 camera_off:
781 en: Your camera is off
782 de: Ihre Kamera ist aus
783 default_device:
784 en: Default device
785 de: Standardgerät
786 starting_camera:
787 en: Starting camera...
788 de: Kamera wird gestartet...
789 camera_failed:
790 en: "Camera could not start: %{detail}"
791 de: "Kamera konnte nicht starten: %{detail}"
792 background:
793 en: Background
794 de: Hintergrund
795 camera:
796 en: Camera
797 de: Kamera
798 microphone:
799 en: Microphone
800 de: Mikrofon
801 speaker:
802 en: Speaker
803 de: Lautsprecher
804 join_now:
805 en: Join now
806 de: Jetzt beitreten
807 choose_av:
808 en: Choose your video and audio settings, then join
809 de: Video- und Audioeinstellungen wählen, dann beitreten
810 join_dialog:
811 title:
812 en: Join with a meeting ID
813 de: Mit Besprechungs-ID beitreten
814 meeting_id:
815 en: Meeting ID
816 de: Besprechungs-ID
817 passcode:
818 en: Passcode
819 de: Kenncode
820 passcode_placeholder:
821 en: Passcode (if the invitation has one)
822 de: Kenncode (falls in der Einladung angegeben)
823 meeting:
824 new_title:
825 en: New meeting
826 de: Neue Besprechung
827 title_label:
828 en: Title
829 de: Titel
830 title_placeholder:
831 en: Add a title
832 de: Titel hinzufügen
833 people:
834 en: People
835 de: Personen
836 date:
837 en: Date
838 de: Datum
839 start:
840 en: Start
841 de: Beginn
842 end:
843 en: End
844 de: Ende
845 repeat:
846 en: Repeat
847 de: Wiederholen
848 details:
849 en: Details
850 de: Details
851 details_placeholder:
852 en: Add details
853 de: Details hinzufügen
854 teams_link_added:
855 en: Teams meeting link is added
856 de: Teams-Besprechungslink wird hinzugefügt
857 agents:
858 start:
859 new_session:
860 en: New session
861 de: Neue Sitzung
862 recent_sessions:
863 en: Recent sessions
864 de: Letzte Sitzungen
865 other_sessions:
866 en: Other sessions
867 de: Weitere Sitzungen
868 recent:
869 en: Recent
870 de: Zuletzt
871 browse:
872 en: Browse...
873 de: Durchsuchen...
874 session:
875 en: Session
876 de: Sitzung
877 working_dir:
878 en: Working dir
879 de: Arbeitsverzeichnis
880 message_to_session:
881 en: Message to the session
882 de: Nachricht an die Sitzung
883 extra_instructions:
884 en: Extra instructions (optional)
885 de: Zusätzliche Anweisungen (optional)
886 show_prompt:
887 en: Show prompt
888 de: Prompt anzeigen
889 send:
890 en: Send
891 de: Senden
892 allow_and_start:
893 en: Allow and start
894 de: Erlauben und starten
895 start:
896 en: Start
897 de: Starten
898 message_placeholder:
899 en: Type the message to send
900 de: Nachricht zum Senden eingeben
901 chat_invisible:
902 en: Agents can't see this chat yet.
903 de: Agents sehen diesen Chat noch nicht.
904 settings:
905 note:
906 en: Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.
907 de: Agents erhalten die Nachricht, den Absender und bis zu 20 frühere Nachrichten. Ohne Sie wird nichts an Teams gesendet.
908 on_this_computer:
909 en: ON THIS COMPUTER
910 de: AUF DIESEM COMPUTER
911 scan_again:
912 en: Scan again
913 de: Erneut suchen
914 no_cli_found:
915 en: No Claude, Copilot, Codex, Cursor or Antigravity CLI is waiting to be added.
916 de: Keine Claude-, Copilot-, Codex-, Cursor- oder Antigravity-CLI wartet auf Hinzufügen.
917 agents_header:
918 en: AGENTS
919 de: AGENTS
920 actions_header:
921 en: ACTIONS - IN THIS ORDER IN THE MENU
922 de: AKTIONEN – IN DIESER REIHENFOLGE IM MENÜ
923 write_with:
924 en: Write with
925 de: Schreiben mit
926 rewrite_hint:
927 en: Rewrite in the composer and the chat assistant island. Microsoft Copilot needs the licence.
928 de: Umschreiben im Editor und im Chat-Assistenten-Insel. Microsoft Copilot benötigt die Lizenz.
929 answer_with:
930 en: "Answer with %{name}"
931 de: "Antworten mit %{name}"
932 new_action:
933 en: New action
934 de: Neue Aktion
935 custom_agent:
936 en: Custom agent
937 de: Eigener Agent
938 unknown_agent:
939 en: Unknown agent
940 de: Unbekannter Agent
941 auth:
942 sign_in:
943 en: Sign in
944 de: Anmelden
945 shell:
946 settings_and_more:
947 en: Settings and more
948 de: Einstellungen und mehr
949 status_menu:
950 view_account:
951 en: View account
952 de: Konto anzeigen
953 set_status_message:
954 en: Set status message
955 de: Statusmeldung festlegen
956 resume_notifications:
957 en: Resume notifications
958 de: Benachrichtigungen fortsetzen
959 chat_list:
960 en: Chat list
961 de: Chatliste
962 translation:
963 en: Translation
964 de: Übersetzung
965 notification_settings:
966 en: Notification settings
967 de: Benachrichtigungseinstellungen
968 test_call:
969 en: Make a test call
970 de: Testanruf starten
971 simulate_incoming:
972 en: Simulate incoming call
973 de: Eingehenden Anruf simulieren
974 duration:
975 en: Duration
976 de: Dauer
977 reset_status:
978 en: Reset status
979 de: Status zurücksetzen
980 work_location_today:
981 en: Set work location for today
982 de: Arbeitsort für heute festlegen
983 office:
984 en: Office
985 de: Büro
986 remote:
987 en: Remote
988 de: Remote
989 clear_work_location:
990 en: Clear work location
991 de: Arbeitsort löschen
992 sidebar:
993 pinned:
994 en: Pinned
995 de: Angepinnt
996 quick_views:
997 en: Quick views
998 de: Schnellansichten
999 teams:
1000 en: Teams
1001 de: Teams
1002 mark_all_read:
1003 en: Mark all as read
1004 de: Alle als gelesen markieren
1005 collapse_all:
1006 en: Collapse all sections
1007 de: Alle Abschnitte einklappen
1008 hidden_teams:
1009 en: Hidden teams
1010 de: Ausgeblendete Teams
1011 see_all_channels:
1012 en: See all channels
1013 de: Alle Kanäle anzeigen
1014 see_fewer_channels:
1015 en: See fewer channels
1016 de: Weniger Kanäle anzeigen
1017 loading_older:
1018 en: Loading older chats
1019 de: Ältere Chats werden geladen
1020 new_chat:
1021 en: New chat
1022 de: Neuer Chat
1023 new_chat_shortcut:
1024 en: New chat (Ctrl+N)
1025 de: Neuer Chat (Strg+N)
1026 more_options:
1027 en: More options
1028 de: Weitere Optionen
1029 draft:
1030 en: Draft
1031 de: Entwurf
1032 draft_prefix:
1033 en: "Draft:"
1034 de: "Entwurf:"
1035 not_sent:
1036 en: Not sent
1037 de: Nicht gesendet
1038 see_more:
1039 en: "See more (%{count})"
1040 de: "Mehr anzeigen (%{count})"
1041 see_less:
1042 en: See less
1043 de: Weniger anzeigen
1044 new_section:
1045 en: New section
1046 de: Neuer Abschnitt
1047 rename_section:
1048 en: Rename section
1049 de: Abschnitt umbenennen
1050 move_up:
1051 en: Move up
1052 de: Nach oben
1053 move_down:
1054 en: Move down
1055 de: Nach unten
1056 delete_section:
1057 en: Delete section
1058 de: Abschnitt löschen
1059 delete_section_title:
1060 en: 'Delete section "%{name}"?'
1061 de: 'Abschnitt „%{name}" löschen?'
1062 delete_section_detail:
1063 en: Chats in it move back to Chats.
1064 de: Chats darin werden zurück zu Chats verschoben.
1065 new_channel:
1066 en: New channel
1067 de: Neuer Kanal
1068 new_message:
1069 en: New message
1070 de: Neue Nachricht
1071 new_items:
1072 en: New items
1073 de: Neue Elemente
1074 notifications:
1075 en: Notifications
1076 de: Benachrichtigungen
1077 notify_banner_activity:
1078 en: Banner and activity
1079 de: Banner und Aktivität
1080 notify_activity_only:
1081 en: Activity only
1082 de: Nur Aktivität
1083 notify_off:
1084 en: Off
1085 de: Aus
1086 include_thread_replies:
1087 en: Include thread replies
1088 de: Thread-Antworten einschließen
1089 filter:
1090 placeholder:
1091 en: Filter by person or chat name
1092 de: Nach Person oder Chatname filtern
1093 channel_placeholder:
1094 en: Filter by channel name
1095 de: Nach Kanalname filtern
1096 no_matches:
1097 en: We didn't find any matches.
1098 de: Keine Treffer gefunden.
1099 clear:
1100 en: Clear filters
1101 de: Filter zurücksetzen
1102 clear_text:
1103 en: Clear filter text
1104 de: Filtertext löschen
1105 show_box:
1106 en: Show filter text box
1107 de: Filterfeld anzeigen
1108 close_box:
1109 en: Close filter text box
1110 de: Filterfeld schließen
1111 show_shortcut:
1112 en: "%{label} (Ctrl+Shift+F)"
1113 de: "%{label} (Strg+Umschalt+F)"
1114 unread:
1115 en: Unread
1116 de: Ungelesen
1117 pill:
1118 unread:
1119 en: Unread
1120 de: Ungelesen
1121 mentions:
1122 en: "@Mentions"
1123 de: "@Erwähnungen"
1124 chats:
1125 en: Chats
1126 de: Chats
1127 meetings:
1128 en: Meeting chats
1129 de: Besprechungschats
1130 muted:
1131 en: Muted
1132 de: Stummgeschaltet
1133 quick_view:
1134 mentions:
1135 en: Mentions
1136 de: Erwähnungen
1137 drafts:
1138 en: Drafts
1139 de: Entwürfe
1140 saved:
1141 en: Saved
1142 de: Gespeichert
1143 mentions_empty:
1144 en: No mentions yet. When someone @mentions you, it shows up here.
1145 de: Noch keine Erwähnungen. Wenn Sie jemand @erwähnt, erscheint es hier.
1146 drafts_empty:
1147 en: No drafts. Messages you start and do not send show up here.
1148 de: Keine Entwürfe. Begonnene, aber nicht gesendete Nachrichten erscheinen hier.
1149 saved_empty:
1150 en: No saved messages. Use Save message in the ... menu of a message.
1151 de: Keine gespeicherten Nachrichten. Nutzen Sie «Nachricht speichern» im …-Menü einer Nachricht.
1152 shortcuts:
1153 title:
1154 en: Keyboard shortcuts
1155 de: Tastenkürzel
1156 group:
1157 general:
1158 en: General
1159 de: Allgemein
1160 navigation:
1161 en: Navigation
1162 de: Navigation
1163 composer:
1164 en: Messages and composer
1165 de: Nachrichten und Editor
1166 calls:
1167 en: Calls
1168 de: Anrufe
@@ -0,0 +1,1168 @@
1_version: 2
2common:
3 cancel:
4 en: Cancel
5 de: Abbrechen
6 save:
7 en: Save
8 de: Speichern
9 close:
10 en: Close
11 de: Schließen
12 delete:
13 en: Delete
14 de: Löschen
15 ok:
16 en: OK
17 de: OK
18 add:
19 en: Add
20 de: Hinzufügen
21 remove:
22 en: Remove
23 de: Entfernen
24 join:
25 en: Join
26 de: Beitreten
27 leave:
28 en: Leave
29 de: Verlassen
30 retry:
31 en: Retry
32 de: Erneut versuchen
33 invite:
34 en: Invite
35 de: Einladen
36 admit:
37 en: Admit
38 de: Zulassen
39 deny:
40 en: Deny
41 de: Ablehnen
42 stop:
43 en: Stop
44 de: Stoppen
45 resume:
46 en: Resume
47 de: Fortsetzen
48 done:
49 en: Done
50 de: Fertig
51 send:
52 en: Send
53 de: Senden
54 sending:
55 en: Sending...
56 de: Wird gesendet...
57 you:
58 en: You
59 de: Sie
60 create:
61 en: Create
62 de: Erstellen
63 attach:
64 en: Attach
65 de: Anhängen
66 chat:
67 en: Chat
68 de: Chat
69 call:
70 en: Call
71 de: Anruf
72 settings:
73 en: Settings
74 de: Einstellungen
75 open:
76 en: Open
77 de: Öffnen
78 quit:
79 en: Quit
80 de: Beenden
81notice:
82 generic_detail:
83 en: "Something went wrong: %{detail}"
84 de: "Etwas ist schiefgelaufen: %{detail}"
85settings:
86 search:
87 no_results:
88 en: No settings found
89 de: Keine Einstellungen gefunden
90 nav:
91 general:
92 en: General
93 de: Allgemein
94 notifications:
95 en: Notifications and activity
96 de: Benachrichtigungen und Aktivität
97 appearance:
98 en: Appearance and accessibility
99 de: Darstellung und Barrierefreiheit
100 chats:
101 en: Chats and channels
102 de: Chats und Kanäle
103 calls:
104 en: Calls
105 de: Anrufe
106 calendar:
107 en: Calendar
108 de: Kalender
109 devices:
110 en: Devices
111 de: Geräte
112 agents:
113 en: Agents
114 de: Agents
115 mcp:
116 en: MCP
117 de: MCP
118 about:
119 en: About
120 de: Info
121 caption:
122 system:
123 en: SYSTEM
124 de: SYSTEM
125 compose_box:
126 en: COMPOSE BOX
127 de: EINGABEFELD
128 translation:
129 en: TRANSLATION
130 de: ÜBERSETZUNG
131 language:
132 en: LANGUAGE
133 de: SPRACHE
134 theme:
135 en: THEME
136 de: DESIGN
137 app_icon:
138 en: APP ICON
139 de: APP-SYMBOL
140 appearance_and_sound:
141 en: APPEARANCE AND SOUND
142 de: DARSTELLUNG UND TON
143 sound:
144 en: SOUND
145 de: TON
146 general:
147 auto_start:
148 en: Auto-start Teams
149 de: Teams automatisch starten
150 open_in_background:
151 en: Open application in background
152 de: Anwendung im Hintergrund starten
153 close_to_tray:
154 en: On close, keep the application running
155 de: Beim Schließen Anwendung weiterlaufen lassen
156 close_to_tray_detail:
157 en: The title bar X hides the window to the tray
158 de: Das X in der Titelleiste blendet das Fenster ins Infobereich-Symbol aus
159 up_arrow:
160 en: Up arrow key behaviour in compose box
161 de: Verhalten der Aufwärtspfeil-Taste im Eingabefeld
162 up_arrow_detail:
163 en: Choose what happens when you press Up arrow at the beginning of the compose box.
164 de: Legen Sie fest, was passiert, wenn Sie am Anfang des Eingabefelds die Aufwärtspfeil-Taste drücken.
165 translation_not_loaded:
166 en: Translation settings not loaded yet
167 de: Übersetzungseinstellungen noch nicht geladen
168 translation_title:
169 en: Translation
170 de: Übersetzung
171 translate_into:
172 en: Translate messages into this language
173 de: Nachrichten in diese Sprache übersetzen
174 behavior_title:
175 en: How to handle messages in other languages
176 de: Umgang mit Nachrichten in anderen Sprachen
177 behavior_ask:
178 en: Ask me before translating
179 de: Vor dem Übersetzen nachfragen
180 behavior_auto:
181 en: Auto-translate all messages
182 de: Alle Nachrichten automatisch übersetzen
183 behavior_never:
184 en: Never translate
185 de: Nie übersetzen
186 never_translate:
187 en: Never translate messages in these languages
188 de: Nachrichten in diesen Sprachen nie übersetzen
189 notifications:
190 flash_taskbar:
191 en: Flash taskbar when notifications are received
192 de: Taskleiste bei Benachrichtigungen blinken lassen
193 flash_taskbar_detail:
194 en: On new messages, until you open the window
195 de: Bei neuen Nachrichten, bis Sie das Fenster öffnen
196 play_sounds:
197 en: Play sounds with notifications
198 de: Töne bei Benachrichtigungen abspielen
199 urgent_sounds:
200 en: Play sounds with urgent and priority contact notifications
201 de: Töne bei dringenden und Prioritätskontakt-Benachrichtigungen
202 call_sounds:
203 en: Play sounds with incoming calls, requests to join, and meeting start notifications
204 de: Töne bei eingehenden Anrufen, Beitrittsanfragen und Besprechungsstarts
205 busy_sounds:
206 en: Play sounds when I'm busy or in a meeting
207 de: Töne abspielen, wenn ich beschäftigt bin oder in einer Besprechung
208 hide_in_calls:
209 en: Hide notifications during calls and meetings
210 de: Benachrichtigungen während Anrufen und Besprechungen ausblenden
211 hide_in_calls_detail:
212 en: No message toasts while a call is active
213 de: Keine Nachrichten-Toasts während ein Anruf aktiv ist
214 position:
215 en: Position on the screen
216 de: Position auf dem Bildschirm
217 position_detail:
218 en: Corner of the main screen
219 de: Ecke des Hauptbildschirms
220 test:
221 en: Test notification
222 de: Testbenachrichtigung
223 test_detail:
224 en: Shows a toast with the settings above
225 de: Zeigt einen Toast mit den obigen Einstellungen
226 send_test:
227 en: Send test notification
228 de: Testbenachrichtigung senden
229 notification_sound:
230 en: Notification sound
231 de: Benachrichtigungston
232 urgent_sound:
233 en: Urgent sound
234 de: Dringlichkeitston
235 chat_messages:
236 en: Chat message notifications
237 de: Chatnachrichten-Benachrichtigungen
238 meeting_chats:
239 en: Meeting chat notifications
240 de: Besprechungschat-Benachrichtigungen
241 likes_reactions:
242 en: Likes and reactions
243 de: Likes und Reaktionen
244 teams_channels:
245 en: Teams and channels
246 de: Teams und Kanäle
247 show_preview:
248 en: Show message preview
249 de: Nachrichtenvorschau anzeigen
250 appearance:
251 color_scheme:
252 en: Color scheme
253 de: Farbschema
254 color_scheme_detail:
255 en: The colors to use for Rusty Teams
256 de: Die Farben für Rusty Teams
257 theme:
258 en: Theme
259 de: Design
260 theme_detail:
261 en: The theme to use for Teams
262 de: Das Design für Teams
263 theme_follow_os:
264 en: Follow operating system theme
265 de: Systemdesign folgen
266 theme_light:
267 en: Light
268 de: Hell
269 theme_dark:
270 en: Dark
271 de: Dunkel
272 theme_high_contrast:
273 en: High contrast
274 de: Hoher Kontrast
275 app_icon:
276 en: App icon
277 de: App-Symbol
278 app_icon_detail_windows:
279 en: Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe
280 de: In Titelleiste, Taskleiste und Infobereich. Angeheftete Verknüpfungen behalten das Symbol der .exe
281 app_icon_detail:
282 en: Shown in the title bar, taskbar and tray
283 de: In Titelleiste, Taskleiste und Infobereich
284 language:
285 title:
286 en: Language
287 de: Sprache
288 detail:
289 en: Language for Rusty Teams and controls
290 de: Sprache für Rusty Teams und Steuerelemente
291 follow_system:
292 en: Follow system
293 de: Systemeinstellung folgen
294 english:
295 en: English
296 de: Englisch
297 german:
298 en: Deutsch
299 de: Deutsch
300 chats:
301 density:
302 en: Message density
303 de: Nachrichtendichte
304 read_receipts:
305 en: Read receipts
306 de: Lesebestätigungen
307 message_actions:
308 en: Show message actions on right click
309 de: Nachrichtenaktionen per Rechtsklick anzeigen
310 muted_section:
311 en: Show muted items in their own section
312 de: Stummgeschaltete Einträge in eigenem Abschnitt anzeigen
313 enter_to:
314 en: When writing a message, press Enter to
315 de: Beim Schreiben einer Nachricht führt Eingabetaste zu
316 markdown:
317 en: Format messages using mark-down
318 de: Nachrichten mit Mark-down formatieren
319 markdown_detail:
320 en: Use mark-down language to define the structure and appearance of messages. Your formatting will take effect once you send your message. When this is on, the formatting options menu won't be visible.
321 de: Verwenden Sie Mark-down, um Struktur und Darstellung von Nachrichten festzulegen. Die Formatierung gilt nach dem Senden. Ist diese Option aktiv, ist das Formatierungsmenü ausgeblendet.
322 calls:
323 ringtones:
324 en: Ringtones
325 de: Klingeltöne
326rail:
327 activity:
328 en: Activity
329 de: Aktivität
330 chat:
331 en: Chat
332 de: Chat
333 teams:
334 en: Teams
335 de: Teams
336 calendar:
337 en: Calendar
338 de: Kalender
339 calls:
340 en: Calls
341 de: Anrufe
342 agents:
343 en: Agents
344 de: Agents
345 shortcut_activity:
346 en: Open Activity
347 de: Aktivität öffnen
348 shortcut_chats:
349 en: Show Chats
350 de: Chats anzeigen
351 shortcut_channels:
352 en: Show Channels
353 de: Kanäle anzeigen
354 shortcut_calendar:
355 en: Open Calendar
356 de: Kalender öffnen
357 shortcut_calls:
358 en: Show Calls
359 de: Anrufe anzeigen
360 shortcut_agents:
361 en: Open Agents
362 de: Agents öffnen
363tray:
364 open:
365 en: Open
366 de: Öffnen
367 quit:
368 en: Quit
369 de: Beenden
370 do_not_disturb:
371 en: Do not disturb
372 de: Nicht stören
373 notifications:
374 en: Notifications
375 de: Benachrichtigungen
376 mute_sound:
377 en: Mute sound
378 de: Ton stumm schalten
379calls:
380 notice:
381 not_connected:
382 en: Not connected to Teams yet
383 de: Noch nicht mit Teams verbunden
384 read_only:
385 en: Calls are off in read-only mode
386 de: Anrufe sind im Nur-Lesen-Modus deaktiviert
387 not_callable:
388 en: This chat cannot be called
389 de: Dieser Chat kann nicht angerufen werden
390 meeting_unavailable:
391 en: This meeting cannot be joined
392 de: Dieser Besprechung kann nicht beigetreten werden
393 answer_failed:
394 en: Could not answer the call
395 de: Anruf konnte nicht angenommen werden
396 consult_ended:
397 en: The consultation ended
398 de: Die Rücksprache ist beendet
399 report_saved:
400 en: Test report saved
401 de: Testbericht gespeichert
402 response_failed:
403 en: Could not send your response
404 de: Ihre Antwort konnte nicht gesendet werden
405 delete_failed:
406 en: Could not delete the meeting
407 de: Besprechung konnte nicht gelöscht werden
408 delete_read_only:
409 en: Meetings cannot be deleted in read-only mode.
410 de: Besprechungen können im Nur-Lesen-Modus nicht gelöscht werden.
411 no_meeting_chat:
412 en: This meeting chat is not available
413 de: Dieser Besprechungschat ist nicht verfügbar
414 invite_failed:
415 en: Could not add that person
416 de: Diese Person konnte nicht hinzugefügt werden
417 no_peer:
418 en: This call cannot be extended
419 de: Dieser Anruf kann nicht erweitert werden
420 missed:
421 en: Call missed
422 de: Anruf verpasst
423 not_found:
424 en: Could not find that meeting
425 de: Diese Besprechung wurde nicht gefunden
426 meet_now_failed:
427 en: Could not start the meeting
428 de: Besprechung konnte nicht gestartet werden
429 consent_first:
430 en: Accept the recording notice first
431 de: Bitte zuerst den Aufzeichnungshinweis bestätigen
432 on_hold:
433 en: Resume the call first
434 de: Setzen Sie den Anruf zuerst fort
435 change_running:
436 en: Another change is still running, try again in a moment
437 de: Eine andere Änderung läuft noch, versuchen Sie es gleich erneut
438 video_failed:
439 en: Video could not start, the call stays audio only
440 de: Video konnte nicht starten, der Anruf bleibt nur Audio
441 share_queued:
442 en: Sharing starts in a moment
443 de: Freigabe startet gleich
444 share_refused:
445 en: The other side did not accept the screen share
446 de: Die Gegenseite hat die Bildschirmfreigabe nicht akzeptiert
447 portal_unavailable:
448 en: Screen sharing needs a desktop portal on this system
449 de: Bildschirmfreigabe benötigt auf diesem System ein Desktop-Portal
450 files_later:
451 en: Files can be added once the chat exists.
452 de: Dateien können hinzugefügt werden, sobald der Chat existiert.
453 calendar_load_failed:
454 en: We couldn't load your calendar.
455 de: Ihr Kalender konnte nicht geladen werden.
456 no_calls:
457 en: No calls yet
458 de: Noch keine Anrufe
459 video_starts_once_connected:
460 en: Video starts once the call is connected
461 de: Video startet, sobald der Anruf verbunden ist
462 call_transferred:
463 en: Call transferred
464 de: Anruf weitergeleitet
465 transfer_failed:
466 en: The transfer did not go through
467 de: Die Weiterleitung ist fehlgeschlagen
468 recording_join_failed:
469 en: The recording service could not join
470 de: Der Aufzeichnungsdienst konnte nicht beitreten
471 captions_join_failed:
472 en: The captions service could not join
473 de: Der Untertitel-Dienst konnte nicht beitreten
474 caption_language_failed:
475 en: Could not change the spoken language
476 de: Gesprochene Sprache konnte nicht geändert werden
477 camera_start:
478 en: "Camera could not start: %{detail}"
479 de: "Kamera konnte nicht starten: %{detail}"
480 camera_restart:
481 en: "Camera could not restart: %{detail}"
482 de: "Kamera konnte nicht neu starten: %{detail}"
483 sharing_start:
484 en: "Sharing could not start: %{detail}"
485 de: "Freigabe konnte nicht starten: %{detail}"
486 raise_hand_failed:
487 en: Could not raise your hand
488 de: Hand heben ist fehlgeschlagen
489 lower_hand_failed:
490 en: Could not lower your hand
491 de: Hand senken ist fehlgeschlagen
492 lower_that_hand_failed:
493 en: Could not lower that hand
494 de: Diese Hand konnte nicht gesenkt werden
495 lower_all_hands_failed:
496 en: Could not lower all hands
497 de: Alle Hände konnten nicht gesenkt werden
498 confirm_recording_failed:
499 en: Could not confirm the recording notice
500 de: Aufzeichnungshinweis konnte nicht bestätigt werden
501 hold_failed:
502 en: Could not put the call on hold
503 de: Anruf konnte nicht gehalten werden
504 resume_failed:
505 en: Could not resume the call
506 de: Anruf konnte nicht fortgesetzt werden
507 transfer_not_allowed:
508 en: This call cannot be transferred
509 de: Dieser Anruf kann nicht weitergeleitet werden
510 transfer_call_failed:
511 en: Could not transfer the call
512 de: Anruf konnte nicht weitergeleitet werden
513 transferring:
514 en: "Transferring to %{detail}..."
515 de: "Weiterleitung an %{detail}..."
516 whiteboards_meetings_only:
517 en: Whiteboards belong to meetings
518 de: Whiteboards gehören zu Besprechungen
519 whiteboard_open_failed:
520 en: The whiteboard could not be opened
521 de: Das Whiteboard konnte nicht geöffnet werden
522 reaction_failed:
523 en: Could not send the reaction
524 de: Reaktion konnte nicht gesendet werden
525 recording_not_started:
526 en: The recording did not start
527 de: Die Aufzeichnung hat nicht gestartet
528 recording_start_failed:
529 en: The recording could not start
530 de: Die Aufzeichnung konnte nicht starten
531 captions_start_failed:
532 en: Captions could not start
533 de: Untertitel konnten nicht starten
534 hold_change_failed:
535 en: The hold did not go through
536 de: Halten ist fehlgeschlagen
537 recording_stop_failed:
538 en: The recording could not be stopped
539 de: Die Aufzeichnung konnte nicht gestoppt werden
540 background_image_failed:
541 en: That background image could not be used
542 de: Dieses Hintergrundbild konnte nicht verwendet werden
543 camera_stopped:
544 en: "Camera stopped: %{detail}"
545 de: "Kamera gestoppt: %{detail}"
546 screen_share_stopped:
547 en: "Screen share stopped: %{detail}"
548 de: "Bildschirmfreigabe gestoppt: %{detail}"
549 admit_failed:
550 en: Could not admit that person
551 de: Diese Person konnte nicht zugelassen werden
552 admit_all_failed:
553 en: Could not admit everyone
554 de: Nicht alle konnten zugelassen werden
555 deny_failed:
556 en: Could not deny that person
557 de: Diese Person konnte nicht abgewiesen werden
558 remove_participant_failed:
559 en: Could not remove that person
560 de: Diese Person konnte nicht entfernt werden
561 mute_participant_failed:
562 en: Could not mute that person
563 de: Diese Person konnte nicht stummgeschaltet werden
564 mute_all_failed:
565 en: Could not mute everyone
566 de: Nicht alle konnten stummgeschaltet werden
567 meeting_lock_failed:
568 en: Could not change the meeting lock
569 de: Besprechungssperre konnte nicht geändert werden
570 change_role_failed:
571 en: Could not change that role
572 de: Diese Rolle konnte nicht geändert werden
573 mic_setting_failed:
574 en: Could not change that microphone setting
575 de: Diese Mikrofoneinstellung konnte nicht geändert werden
576 camera_setting_failed:
577 en: Could not change that camera setting
578 de: Diese Kameraeinstellung konnte nicht geändert werden
579 attendee_settings_failed:
580 en: Could not change the attendee settings
581 de: Teilnehmereinstellungen konnten nicht geändert werden
582 invite_person_failed:
583 en: Could not invite that person
584 de: Diese Person konnte nicht eingeladen werden
585 spotlight_failed:
586 en: Could not spotlight that person
587 de: Diese Person konnte nicht hervorgehoben werden
588 stop_spotlight_failed:
589 en: Could not stop the spotlight
590 de: Hervorhebung konnte nicht beendet werden
591 page:
592 title:
593 en: Calls
594 de: Anrufe
595 history:
596 en: History
597 de: Verlauf
598 speed_dial:
599 en: Speed dial
600 de: Kurzwahl
601 speed_dial_empty:
602 en: Add people to speed dial for quick access.
603 de: Personen zur Kurzwahl hinzufügen für schnellen Zugriff.
604 speed_dial_add:
605 en: Add to speed dial
606 de: Zur Kurzwahl hinzufügen
607 pick_one:
608 en: Pick one person to call
609 de: Eine Person zum Anrufen wählen
610 chrome:
611 video_call:
612 en: Video call
613 de: Videoanruf
614 audio_call:
615 en: Audio call
616 de: Audioanruf
617 call_options:
618 en: Call options
619 de: Anrufoptionen
620 meet_now:
621 en: Meet now
622 de: Jetzt besprechen
623 stop_sharing:
624 en: Stop sharing
625 de: Freigabe beenden
626 raise_hand:
627 en: Raise hand
628 de: Hand heben
629 lower_hand:
630 en: Lower hand
631 de: Hand senken
632 lower_all_hands:
633 en: Lower all hands
634 de: Alle Hände senken
635 end_meeting_for_all:
636 en: End meeting for everyone
637 de: Besprechung für alle beenden
638 open_chat:
639 en: Open the chat
640 de: Chat öffnen
641 close_chat:
642 en: Close the chat
643 de: Chat schließen
644 share_entire_screen:
645 en: Share entire screen
646 de: Gesamten Bildschirm freigeben
647 share_screen_n:
648 en: "Share screen %{n}"
649 de: "Bildschirm %{n} freigeben"
650 share_window:
651 en: Share a window
652 de: Fenster freigeben
653 share_window_ellipsis:
654 en: Share a window...
655 de: Fenster freigeben...
656 computer_sound_on:
657 en: Computer sound on
658 de: Computerton ein
659 computer_sound_off:
660 en: Computer sound off
661 de: Computerton aus
662 sharing_label:
663 en: "You are sharing: %{label}"
664 de: "Sie geben frei: %{label}"
665 no_microphone:
666 en: No microphone found
667 de: Kein Mikrofon gefunden
668 audio_off_meeting:
669 en: Audio is off for this meeting
670 de: Audio ist für diese Besprechung aus
671 no_camera:
672 en: No camera found
673 de: Keine Kamera gefunden
674 sharing_when_connected:
675 en: Sharing starts once the call is connected
676 de: Freigabe startet, sobald der Anruf verbunden ist
677 no_windows:
678 en: No windows found
679 de: Keine Fenster gefunden
680 lobby_waiting:
681 en: Waiting in the lobby...
682 de: Warten in der Lobby...
683 include_computer_sound:
684 en: Include computer sound
685 de: Computerton einbeziehen
686 optimize_motion:
687 en: Optimize for motion
688 de: Für Bewegung optimieren
689 show_me_over_content:
690 en: Show me over my content
691 de: Mich über meinen Inhalt anzeigen
692 camera_on_first:
693 en: Turn your camera on first
694 de: Kamera zuerst einschalten
695 noise_suppression:
696 en: Noise suppression
697 de: Rauschunterdrückung
698 music_mode:
699 en: Music mode
700 de: Musikmodus
701 push_to_talk:
702 en: Unmuted - release Ctrl+Space to mute
703 de: Entstummt – Strg+Leertaste loslassen zum Stummschalten
704 hand_raised:
705 en: Hand raised
706 de: Hand gehoben
707 hand_position:
708 en: "Hand %{position}"
709 de: "Hand %{position}"
710 reconnecting:
711 en: Reconnecting...
712 de: Verbindung wird wiederhergestellt...
713 microphone:
714 en: Microphone
715 de: Mikrofon
716 speaker:
717 en: Speaker
718 de: Lautsprecher
719 return_main:
720 en: Return to main meeting
721 de: Zur Hauptbesprechung zurück
722 breakout_room:
723 en: Breakout room
724 de: Breakout-Raum
725 on_hold:
726 en: On hold
727 de: Gehalten
728 you_on_hold:
729 en: You're on hold
730 de: Sie sind in der Warteschleife
731 open_in_browser:
732 en: Open in browser
733 de: Im Browser öffnen
734 recording_notice:
735 en: This meeting is being recorded
736 de: Diese Besprechung wird aufgezeichnet
737 recording_accept_hint:
738 en: Your microphone and camera stay off until you accept.
739 de: Mikrofon und Kamera bleiben aus, bis Sie zustimmen.
740 transfer:
741 en: Transfer
742 de: Weiterleiten
743 resume_person:
744 en: "Resume %{name}"
745 de: "%{name} fortsetzen"
746 video_quality:
747 en: Video quality
748 de: Videoqualität
749 auto:
750 en: Auto
751 de: Auto
752 effects:
753 en: Effects
754 de: Effekte
755 mirror_video:
756 en: Mirror my video
757 de: Video spiegeln
758 auto_framing:
759 en: Auto framing
760 de: Automatischer Bildausschnitt
761 adjust_brightness:
762 en: Adjust brightness
763 de: Helligkeit anpassen
764 soft_focus:
765 en: Soft focus
766 de: Weichzeichner
767 background:
768 en: Background
769 de: Hintergrund
770 background_none:
771 en: None
772 de: Keiner
773 background_blur:
774 en: Blur
775 de: Unscharf
776 add_image:
777 en: Add image...
778 de: Bild hinzufügen...
779 prejoin:
780 camera_off:
781 en: Your camera is off
782 de: Ihre Kamera ist aus
783 default_device:
784 en: Default device
785 de: Standardgerät
786 starting_camera:
787 en: Starting camera...
788 de: Kamera wird gestartet...
789 camera_failed:
790 en: "Camera could not start: %{detail}"
791 de: "Kamera konnte nicht starten: %{detail}"
792 background:
793 en: Background
794 de: Hintergrund
795 camera:
796 en: Camera
797 de: Kamera
798 microphone:
799 en: Microphone
800 de: Mikrofon
801 speaker:
802 en: Speaker
803 de: Lautsprecher
804 join_now:
805 en: Join now
806 de: Jetzt beitreten
807 choose_av:
808 en: Choose your video and audio settings, then join
809 de: Video- und Audioeinstellungen wählen, dann beitreten
810 join_dialog:
811 title:
812 en: Join with a meeting ID
813 de: Mit Besprechungs-ID beitreten
814 meeting_id:
815 en: Meeting ID
816 de: Besprechungs-ID
817 passcode:
818 en: Passcode
819 de: Kenncode
820 passcode_placeholder:
821 en: Passcode (if the invitation has one)
822 de: Kenncode (falls in der Einladung angegeben)
823 meeting:
824 new_title:
825 en: New meeting
826 de: Neue Besprechung
827 title_label:
828 en: Title
829 de: Titel
830 title_placeholder:
831 en: Add a title
832 de: Titel hinzufügen
833 people:
834 en: People
835 de: Personen
836 date:
837 en: Date
838 de: Datum
839 start:
840 en: Start
841 de: Beginn
842 end:
843 en: End
844 de: Ende
845 repeat:
846 en: Repeat
847 de: Wiederholen
848 details:
849 en: Details
850 de: Details
851 details_placeholder:
852 en: Add details
853 de: Details hinzufügen
854 teams_link_added:
855 en: Teams meeting link is added
856 de: Teams-Besprechungslink wird hinzugefügt
857agents:
858 start:
859 new_session:
860 en: New session
861 de: Neue Sitzung
862 recent_sessions:
863 en: Recent sessions
864 de: Letzte Sitzungen
865 other_sessions:
866 en: Other sessions
867 de: Weitere Sitzungen
868 recent:
869 en: Recent
870 de: Zuletzt
871 browse:
872 en: Browse...
873 de: Durchsuchen...
874 session:
875 en: Session
876 de: Sitzung
877 working_dir:
878 en: Working dir
879 de: Arbeitsverzeichnis
880 message_to_session:
881 en: Message to the session
882 de: Nachricht an die Sitzung
883 extra_instructions:
884 en: Extra instructions (optional)
885 de: Zusätzliche Anweisungen (optional)
886 show_prompt:
887 en: Show prompt
888 de: Prompt anzeigen
889 send:
890 en: Send
891 de: Senden
892 allow_and_start:
893 en: Allow and start
894 de: Erlauben und starten
895 start:
896 en: Start
897 de: Starten
898 message_placeholder:
899 en: Type the message to send
900 de: Nachricht zum Senden eingeben
901 chat_invisible:
902 en: Agents can't see this chat yet.
903 de: Agents sehen diesen Chat noch nicht.
904 settings:
905 note:
906 en: Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.
907 de: Agents erhalten die Nachricht, den Absender und bis zu 20 frühere Nachrichten. Ohne Sie wird nichts an Teams gesendet.
908 on_this_computer:
909 en: ON THIS COMPUTER
910 de: AUF DIESEM COMPUTER
911 scan_again:
912 en: Scan again
913 de: Erneut suchen
914 no_cli_found:
915 en: No Claude, Copilot, Codex, Cursor or Antigravity CLI is waiting to be added.
916 de: Keine Claude-, Copilot-, Codex-, Cursor- oder Antigravity-CLI wartet auf Hinzufügen.
917 agents_header:
918 en: AGENTS
919 de: AGENTS
920 actions_header:
921 en: ACTIONS - IN THIS ORDER IN THE MENU
922 de: AKTIONEN – IN DIESER REIHENFOLGE IM MENÜ
923 write_with:
924 en: Write with
925 de: Schreiben mit
926 rewrite_hint:
927 en: Rewrite in the composer and the chat assistant island. Microsoft Copilot needs the licence.
928 de: Umschreiben im Editor und im Chat-Assistenten-Insel. Microsoft Copilot benötigt die Lizenz.
929 answer_with:
930 en: "Answer with %{name}"
931 de: "Antworten mit %{name}"
932 new_action:
933 en: New action
934 de: Neue Aktion
935 custom_agent:
936 en: Custom agent
937 de: Eigener Agent
938 unknown_agent:
939 en: Unknown agent
940 de: Unbekannter Agent
941auth:
942 sign_in:
943 en: Sign in
944 de: Anmelden
945shell:
946 settings_and_more:
947 en: Settings and more
948 de: Einstellungen und mehr
949status_menu:
950 view_account:
951 en: View account
952 de: Konto anzeigen
953 set_status_message:
954 en: Set status message
955 de: Statusmeldung festlegen
956 resume_notifications:
957 en: Resume notifications
958 de: Benachrichtigungen fortsetzen
959 chat_list:
960 en: Chat list
961 de: Chatliste
962 translation:
963 en: Translation
964 de: Übersetzung
965 notification_settings:
966 en: Notification settings
967 de: Benachrichtigungseinstellungen
968 test_call:
969 en: Make a test call
970 de: Testanruf starten
971 simulate_incoming:
972 en: Simulate incoming call
973 de: Eingehenden Anruf simulieren
974 duration:
975 en: Duration
976 de: Dauer
977 reset_status:
978 en: Reset status
979 de: Status zurücksetzen
980 work_location_today:
981 en: Set work location for today
982 de: Arbeitsort für heute festlegen
983 office:
984 en: Office
985 de: Büro
986 remote:
987 en: Remote
988 de: Remote
989 clear_work_location:
990 en: Clear work location
991 de: Arbeitsort löschen
992sidebar:
993 pinned:
994 en: Pinned
995 de: Angepinnt
996 quick_views:
997 en: Quick views
998 de: Schnellansichten
999 teams:
1000 en: Teams
1001 de: Teams
1002 mark_all_read:
1003 en: Mark all as read
1004 de: Alle als gelesen markieren
1005 collapse_all:
1006 en: Collapse all sections
1007 de: Alle Abschnitte einklappen
1008 hidden_teams:
1009 en: Hidden teams
1010 de: Ausgeblendete Teams
1011 see_all_channels:
1012 en: See all channels
1013 de: Alle Kanäle anzeigen
1014 see_fewer_channels:
1015 en: See fewer channels
1016 de: Weniger Kanäle anzeigen
1017 loading_older:
1018 en: Loading older chats
1019 de: Ältere Chats werden geladen
1020 new_chat:
1021 en: New chat
1022 de: Neuer Chat
1023 new_chat_shortcut:
1024 en: New chat (Ctrl+N)
1025 de: Neuer Chat (Strg+N)
1026 more_options:
1027 en: More options
1028 de: Weitere Optionen
1029 draft:
1030 en: Draft
1031 de: Entwurf
1032 draft_prefix:
1033 en: "Draft:"
1034 de: "Entwurf:"
1035 not_sent:
1036 en: Not sent
1037 de: Nicht gesendet
1038 see_more:
1039 en: "See more (%{count})"
1040 de: "Mehr anzeigen (%{count})"
1041 see_less:
1042 en: See less
1043 de: Weniger anzeigen
1044 new_section:
1045 en: New section
1046 de: Neuer Abschnitt
1047 rename_section:
1048 en: Rename section
1049 de: Abschnitt umbenennen
1050 move_up:
1051 en: Move up
1052 de: Nach oben
1053 move_down:
1054 en: Move down
1055 de: Nach unten
1056 delete_section:
1057 en: Delete section
1058 de: Abschnitt löschen
1059 delete_section_title:
1060 en: 'Delete section "%{name}"?'
1061 de: 'Abschnitt „%{name}" löschen?'
1062 delete_section_detail:
1063 en: Chats in it move back to Chats.
1064 de: Chats darin werden zurück zu Chats verschoben.
1065 new_channel:
1066 en: New channel
1067 de: Neuer Kanal
1068 new_message:
1069 en: New message
1070 de: Neue Nachricht
1071 new_items:
1072 en: New items
1073 de: Neue Elemente
1074 notifications:
1075 en: Notifications
1076 de: Benachrichtigungen
1077 notify_banner_activity:
1078 en: Banner and activity
1079 de: Banner und Aktivität
1080 notify_activity_only:
1081 en: Activity only
1082 de: Nur Aktivität
1083 notify_off:
1084 en: Off
1085 de: Aus
1086 include_thread_replies:
1087 en: Include thread replies
1088 de: Thread-Antworten einschließen
1089 filter:
1090 placeholder:
1091 en: Filter by person or chat name
1092 de: Nach Person oder Chatname filtern
1093 channel_placeholder:
1094 en: Filter by channel name
1095 de: Nach Kanalname filtern
1096 no_matches:
1097 en: We didn't find any matches.
1098 de: Keine Treffer gefunden.
1099 clear:
1100 en: Clear filters
1101 de: Filter zurücksetzen
1102 clear_text:
1103 en: Clear filter text
1104 de: Filtertext löschen
1105 show_box:
1106 en: Show filter text box
1107 de: Filterfeld anzeigen
1108 close_box:
1109 en: Close filter text box
1110 de: Filterfeld schließen
1111 show_shortcut:
1112 en: "%{label} (Ctrl+Shift+F)"
1113 de: "%{label} (Strg+Umschalt+F)"
1114 unread:
1115 en: Unread
1116 de: Ungelesen
1117 pill:
1118 unread:
1119 en: Unread
1120 de: Ungelesen
1121 mentions:
1122 en: "@Mentions"
1123 de: "@Erwähnungen"
1124 chats:
1125 en: Chats
1126 de: Chats
1127 meetings:
1128 en: Meeting chats
1129 de: Besprechungschats
1130 muted:
1131 en: Muted
1132 de: Stummgeschaltet
1133 quick_view:
1134 mentions:
1135 en: Mentions
1136 de: Erwähnungen
1137 drafts:
1138 en: Drafts
1139 de: Entwürfe
1140 saved:
1141 en: Saved
1142 de: Gespeichert
1143 mentions_empty:
1144 en: No mentions yet. When someone @mentions you, it shows up here.
1145 de: Noch keine Erwähnungen. Wenn Sie jemand @erwähnt, erscheint es hier.
1146 drafts_empty:
1147 en: No drafts. Messages you start and do not send show up here.
1148 de: Keine Entwürfe. Begonnene, aber nicht gesendete Nachrichten erscheinen hier.
1149 saved_empty:
1150 en: No saved messages. Use Save message in the ... menu of a message.
1151 de: Keine gespeicherten Nachrichten. Nutzen Sie «Nachricht speichern» im …-Menü einer Nachricht.
1152shortcuts:
1153 title:
1154 en: Keyboard shortcuts
1155 de: Tastenkürzel
1156 group:
1157 general:
1158 en: General
1159 de: Allgemein
1160 navigation:
1161 en: Navigation
1162 de: Navigation
1163 composer:
1164 en: Messages and composer
1165 de: Nachrichten und Editor
1166 calls:
1167 en: Calls
1168 de: Anrufe
crates/app-base/src/lib.rs +3 −0
@@ -36,9 +36,12 @@ pub mod stickers;
36 36 pub mod task_dialog;
37 37 pub mod theme;
38 38 pub mod translation;
39 pub mod ui_locale;
39 40 pub mod updater;
40 41 pub mod user_activity;
41 42 pub mod version;
42 43 pub mod zoom;
43 44
44 45 pub const APP_NAME: &str = "Rusty Teams";
46
47 rust_i18n::i18n!("locales", fallback = "en");
@@ -36,9 +36,12 @@ pub mod stickers;
36pub mod task_dialog;
36pub mod task_dialog;
37pub mod theme;
37pub mod theme;
38pub mod translation;
38pub mod translation;
39pub mod ui_locale;
39pub mod updater;
40pub mod updater;
40pub mod user_activity;
41pub mod user_activity;
41pub mod version;
42pub mod version;
42pub mod zoom;
43pub mod zoom;
43
44
44pub const APP_NAME: &str = "Rusty Teams";
45pub const APP_NAME: &str = "Rusty Teams";
46
47rust_i18n::i18n!("locales", fallback = "en");
crates/app-base/src/notify/platform/stub.rs +2 −0
@@ -108,6 +108,8 @@ impl Tray {
108 108 }
109 109
110 110 pub fn sync(&self, _sound_on: bool, _do_not_disturb: bool, _mention: bool) {}
111
112 pub fn relocalize(&self) {}
111 113 }
112 114
113 115 pub fn animations_enabled() -> bool {
@@ -108,6 +108,8 @@ impl Tray {
108 }
108 }
109
109
110 pub fn sync(&self, _sound_on: bool, _do_not_disturb: bool, _mention: bool) {}
110 pub fn sync(&self, _sound_on: bool, _do_not_disturb: bool, _mention: bool) {}
111
112 pub fn relocalize(&self) {}
111}
113}
112
114
113pub fn animations_enabled() -> bool {
115pub fn animations_enabled() -> bool {
crates/app-base/src/notify/platform/windows_impl.rs +37 −5
@@ -656,26 +656,44 @@ const ID_QUIT: &str = "quit";
656 656
657 657 pub struct Tray {
658 658 icon: TrayIcon,
659 open: MenuItem,
659 660 sound: CheckMenuItem,
660 661 do_not_disturb: CheckMenuItem,
662 settings: MenuItem,
663 quit: MenuItem,
661 664 plain: Icon,
662 665 with_dot: Icon,
663 666 }
664 667
668 fn tray_menu_label(key: &str) -> String {
669 crate::ui_locale::tr(key)
670 }
671
665 672 impl Tray {
666 673 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
667 674 let (plain, with_dot) = tray_icons(icon_png)?;
668 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
669 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
675 let open = MenuItem::with_id(ID_OPEN, tray_menu_label("tray.open"), true, None);
676 let sound = CheckMenuItem::with_id(
677 ID_SOUND,
678 tray_menu_label("tray.mute_sound"),
679 true,
680 !sound_on,
681 None,
682 );
670 683 let dnd = CheckMenuItem::with_id(
671 684 ID_DO_NOT_DISTURB,
672 "Do not disturb",
685 tray_menu_label("tray.do_not_disturb"),
673 686 true,
674 687 do_not_disturb,
675 688 None,
676 689 );
677 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
678 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
690 let settings = MenuItem::with_id(
691 ID_SETTINGS,
692 tray_menu_label("tray.notifications"),
693 true,
694 None,
695 );
696 let quit = MenuItem::with_id(ID_QUIT, tray_menu_label("tray.quit"), true, None);
679 697 let menu = Menu::new();
680 698 menu.append_items(&[
681 699 &open,
@@ -696,13 +714,26 @@ impl Tray {
696 714 .ok()?;
697 715 Some(Tray {
698 716 icon,
717 open,
699 718 sound,
700 719 do_not_disturb: dnd,
720 settings,
721 quit,
701 722 plain,
702 723 with_dot,
703 724 })
704 725 }
705 726
727 pub fn relocalize(&self) {
728 let _ = self.open.set_text(tray_menu_label("tray.open"));
729 let _ = self.sound.set_text(tray_menu_label("tray.mute_sound"));
730 let _ = self
731 .do_not_disturb
732 .set_text(tray_menu_label("tray.do_not_disturb"));
733 let _ = self.settings.set_text(tray_menu_label("tray.notifications"));
734 let _ = self.quit.set_text(tray_menu_label("tray.quit"));
735 }
736
706 737 pub fn poll(&self) -> Vec<TrayCommand> {
707 738 let mut commands = Vec::new();
708 739 while let Ok(event) = MenuEvent::receiver().try_recv() {
@@ -740,6 +771,7 @@ impl Tray {
740 771 }
741 772
742 773 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
774 self.relocalize();
743 775 self.sound.set_checked(!sound_on);
744 776 self.do_not_disturb.set_checked(do_not_disturb);
745 777 let icon = if mention { &self.with_dot } else { &self.plain };
@@ -656,26 +656,44 @@ const ID_QUIT: &str = "quit";
656
656
657pub struct Tray {
657pub struct Tray {
658 icon: TrayIcon,
658 icon: TrayIcon,
659 open: MenuItem,
659 sound: CheckMenuItem,
660 sound: CheckMenuItem,
660 do_not_disturb: CheckMenuItem,
661 do_not_disturb: CheckMenuItem,
662 settings: MenuItem,
663 quit: MenuItem,
661 plain: Icon,
664 plain: Icon,
662 with_dot: Icon,
665 with_dot: Icon,
663}
666}
664
667
668fn tray_menu_label(key: &str) -> String {
669 crate::ui_locale::tr(key)
670}
671
665impl Tray {
672impl Tray {
666 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
673 pub fn new(sound_on: bool, do_not_disturb: bool, icon_png: &[u8]) -> Option<Self> {
667 let (plain, with_dot) = tray_icons(icon_png)?;
674 let (plain, with_dot) = tray_icons(icon_png)?;
668 let open = MenuItem::with_id(ID_OPEN, "Open", true, None);
675 let open = MenuItem::with_id(ID_OPEN, tray_menu_label("tray.open"), true, None);
669 let sound = CheckMenuItem::with_id(ID_SOUND, "Mute sound", true, !sound_on, None);
676 let sound = CheckMenuItem::with_id(
677 ID_SOUND,
678 tray_menu_label("tray.mute_sound"),
679 true,
680 !sound_on,
681 None,
682 );
670 let dnd = CheckMenuItem::with_id(
683 let dnd = CheckMenuItem::with_id(
671 ID_DO_NOT_DISTURB,
684 ID_DO_NOT_DISTURB,
672 "Do not disturb",
685 tray_menu_label("tray.do_not_disturb"),
673 true,
686 true,
674 do_not_disturb,
687 do_not_disturb,
675 None,
688 None,
676 );
689 );
677 let settings = MenuItem::with_id(ID_SETTINGS, "Notifications", true, None);
690 let settings = MenuItem::with_id(
678 let quit = MenuItem::with_id(ID_QUIT, "Quit", true, None);
691 ID_SETTINGS,
692 tray_menu_label("tray.notifications"),
693 true,
694 None,
695 );
696 let quit = MenuItem::with_id(ID_QUIT, tray_menu_label("tray.quit"), true, None);
679 let menu = Menu::new();
697 let menu = Menu::new();
680 menu.append_items(&[
698 menu.append_items(&[
681 &open,
699 &open,
@@ -696,13 +714,26 @@ impl Tray {
696 .ok()?;
714 .ok()?;
697 Some(Tray {
715 Some(Tray {
698 icon,
716 icon,
717 open,
699 sound,
718 sound,
700 do_not_disturb: dnd,
719 do_not_disturb: dnd,
720 settings,
721 quit,
701 plain,
722 plain,
702 with_dot,
723 with_dot,
703 })
724 })
704 }
725 }
705
726
727 pub fn relocalize(&self) {
728 let _ = self.open.set_text(tray_menu_label("tray.open"));
729 let _ = self.sound.set_text(tray_menu_label("tray.mute_sound"));
730 let _ = self
731 .do_not_disturb
732 .set_text(tray_menu_label("tray.do_not_disturb"));
733 let _ = self.settings.set_text(tray_menu_label("tray.notifications"));
734 let _ = self.quit.set_text(tray_menu_label("tray.quit"));
735 }
736
706 pub fn poll(&self) -> Vec<TrayCommand> {
737 pub fn poll(&self) -> Vec<TrayCommand> {
707 let mut commands = Vec::new();
738 let mut commands = Vec::new();
708 while let Ok(event) = MenuEvent::receiver().try_recv() {
739 while let Ok(event) = MenuEvent::receiver().try_recv() {
@@ -740,6 +771,7 @@ impl Tray {
740 }
771 }
741
772
742 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
773 pub fn sync(&self, sound_on: bool, do_not_disturb: bool, mention: bool) {
774 self.relocalize();
743 self.sound.set_checked(!sound_on);
775 self.sound.set_checked(!sound_on);
744 self.do_not_disturb.set_checked(do_not_disturb);
776 self.do_not_disturb.set_checked(do_not_disturb);
745 let icon = if mention { &self.with_dot } else { &self.plain };
777 let icon = if mention { &self.with_dot } else { &self.plain };
crates/app-base/src/ui_locale.rs added +243 −0
@@ -0,0 +1,243 @@
1 use std::collections::HashMap;
2
3 use store::Store;
4
5 const META_KEY: &str = "ui.locale";
6 const PREFERENCE_KEY: &str = "preference";
7
8 #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9 pub enum LocalePreference {
10 #[default]
11 Auto,
12 English,
13 German,
14 }
15
16 impl LocalePreference {
17 pub const ALL: [LocalePreference; 3] = [
18 LocalePreference::Auto,
19 LocalePreference::English,
20 LocalePreference::German,
21 ];
22
23 pub fn key(self) -> &'static str {
24 match self {
25 LocalePreference::Auto => "auto",
26 LocalePreference::English => "en",
27 LocalePreference::German => "de",
28 }
29 }
30
31 pub fn from_key(key: &str) -> Option<LocalePreference> {
32 Self::ALL
33 .into_iter()
34 .find(|preference| preference.key() == key)
35 }
36 }
37
38 pub fn os_language_tag() -> String {
39 sys_locale::get_locale().unwrap_or_else(|| "en".to_owned())
40 }
41
42 pub fn effective_locale(pref: LocalePreference) -> &'static str {
43 effective_locale_for(pref, &os_language_tag())
44 }
45
46 pub(crate) fn effective_locale_for(pref: LocalePreference, os_tag: &str) -> &'static str {
47 match pref {
48 LocalePreference::German => "de",
49 LocalePreference::English => "en",
50 LocalePreference::Auto => {
51 if os_tag.to_lowercase().starts_with("de") {
52 "de"
53 } else {
54 "en"
55 }
56 }
57 }
58 }
59
60 pub fn apply_locale(locale: &str) {
61 rust_i18n::set_locale(locale);
62 gpui_kit::component::set_locale(locale);
63 }
64
65 pub fn load(store: &Store) -> LocalePreference {
66 store
67 .meta(META_KEY)
68 .ok()
69 .flatten()
70 .map(|text| parse(&text))
71 .unwrap_or_default()
72 }
73
74 pub fn save(store: &Store, pref: LocalePreference) {
75 let _ = store.set_meta(META_KEY, &serialize(pref));
76 }
77
78 fn serialize(pref: LocalePreference) -> String {
79 format!("{PREFERENCE_KEY}={}", pref.key())
80 }
81
82 fn parse(text: &str) -> LocalePreference {
83 for line in text.lines() {
84 if let Some((PREFERENCE_KEY, value)) = line.split_once('=') {
85 if let Some(pref) = LocalePreference::from_key(value.trim()) {
86 return pref;
87 }
88 }
89 }
90 LocalePreference::default()
91 }
92
93 pub fn tr(key: &str) -> String {
94 rust_i18n::t!(key).to_string()
95 }
96
97 pub fn tr_args(key: &str, args: &HashMap<String, String>) -> String {
98 if args.is_empty() {
99 return tr(key);
100 }
101 let patterns: Vec<&str> = args.keys().map(String::as_str).collect();
102 let values: Vec<String> = patterns.iter().map(|name| args[*name].clone()).collect();
103 rust_i18n::replace_patterns(&tr(key), &patterns, &values)
104 }
105
106 /// Separator between an i18n key and a detail payload in `CallUpdate::Notice`.
107 pub const NOTICE_DETAIL_SEP: char = '\u{1f}';
108
109 /// Resolve a call/UI notice payload: bare key, or `key` + detail after [`NOTICE_DETAIL_SEP`].
110 pub fn localize_notice(payload: &str) -> String {
111 if let Some((key, detail)) = payload.split_once(NOTICE_DETAIL_SEP) {
112 let mut args = HashMap::new();
113 args.insert("detail".to_owned(), detail.to_owned());
114 return tr_args(key, &args);
115 }
116 if payload.contains('.') {
117 return tr(payload);
118 }
119 payload.to_owned()
120 }
121
122 pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124 }
125
126 #[cfg(test)]
127 mod tests {
128 use std::sync::{Mutex, MutexGuard};
129
130 use super::*;
131 use tempfile::tempdir;
132
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
134 static LOCK: Mutex<()> = Mutex::new(());
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
136 }
137
138 #[test]
139 fn ui_locale_effective_prefers_explicit_english_and_german() {
140 let _guard = locale_test_lock();
141 assert_eq!(effective_locale_for(LocalePreference::English, "de-DE"), "en");
142 assert_eq!(effective_locale_for(LocalePreference::German, "en-US"), "de");
143 }
144
145 #[test]
146 fn ui_locale_effective_auto_follows_os_tag() {
147 let _guard = locale_test_lock();
148 assert_eq!(effective_locale_for(LocalePreference::Auto, "de-DE"), "de");
149 assert_eq!(effective_locale_for(LocalePreference::Auto, "de"), "de");
150 assert_eq!(effective_locale_for(LocalePreference::Auto, "en-US"), "en");
151 assert_eq!(effective_locale_for(LocalePreference::Auto, "fr-FR"), "en");
152 }
153
154 #[test]
155 fn ui_locale_load_save_roundtrip_in_store() {
156 let _guard = locale_test_lock();
157 let store = Store::open_in_memory().expect("in-memory store");
158 assert_eq!(load(&store), LocalePreference::Auto);
159 save(&store, LocalePreference::German);
160 assert_eq!(load(&store), LocalePreference::German);
161 save(&store, LocalePreference::English);
162 assert_eq!(load(&store), LocalePreference::English);
163 }
164
165 #[test]
166 fn ui_locale_persists_via_tempfile_store() {
167 let _guard = locale_test_lock();
168 let directory = tempdir().expect("tempdir");
169 let path = directory.path().join("locale.sqlite3");
170 let store = Store::open(&path).expect("store on disk");
171 save(&store, LocalePreference::German);
172 drop(store);
173 let store = Store::open(&path).expect("reopen store");
174 assert_eq!(load(&store), LocalePreference::German);
175 }
176
177 #[test]
178 fn ui_locale_unknown_preference_falls_back_to_auto() {
179 let _guard = locale_test_lock();
180 let store = Store::open_in_memory().expect("in-memory store");
181 let _ = store.set_meta(META_KEY, "preference=fr");
182 assert_eq!(load(&store), LocalePreference::Auto);
183 }
184
185 #[test]
186 fn ui_locale_tr_resolves_catalog_in_en_and_de() {
187 let _guard = locale_test_lock();
188 apply_locale("en");
189 assert_eq!(tr("common.cancel"), "Cancel");
190 apply_locale("de");
191 assert_eq!(tr("common.cancel"), "Abbrechen");
192 }
193
194 #[test]
195 fn ui_locale_tr_args_substitutes_detail() {
196 let _guard = locale_test_lock();
197 apply_locale("en");
198 let mut args = HashMap::new();
199 args.insert("detail".to_owned(), "timeout".to_owned());
200 assert_eq!(
201 tr_args("notice.generic_detail", &args),
202 "Something went wrong: timeout"
203 );
204 }
205
206 #[test]
207 fn ui_locale_notice_localizes_call_on_hold_in_de() {
208 let _guard = locale_test_lock();
209 apply_locale("de");
210 let localized = localize_notice("calls.notice.on_hold");
211 assert_eq!(localized, "Setzen Sie den Anruf zuerst fort");
212 }
213
214 #[test]
215 fn ui_locale_sidebar_and_status_menu_in_de() {
216 let _guard = locale_test_lock();
217 apply_locale("de");
218 assert_eq!(tr("sidebar.quick_views"), "Schnellansichten");
219 assert_eq!(tr("status_menu.view_account"), "Konto anzeigen");
220 assert_eq!(tr("shell.settings_and_more"), "Einstellungen und mehr");
221 }
222
223 #[test]
224 fn ui_locale_tray_keys_resolve() {
225 let _guard = locale_test_lock();
226 apply_locale("en");
227 assert_eq!(tr("tray.open"), "Open");
228 assert_eq!(tr("tray.quit"), "Quit");
229 assert_eq!(tr("tray.mute_sound"), "Mute sound");
230 apply_locale("de");
231 assert_eq!(tr("tray.do_not_disturb"), "Nicht stören");
232 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
233 }
234
235 #[test]
236 fn ui_locale_fallback_missing_key_returns_english_or_key() {
237 let _guard = locale_test_lock();
238 apply_locale("de");
239 assert_eq!(tr("common.cancel"), "Abbrechen");
240 let missing = tr("catalog.does_not_exist_yet");
241 assert!(!missing.is_empty());
242 }
243 }
@@ -0,0 +1,243 @@
1use std::collections::HashMap;
2
3use store::Store;
4
5const META_KEY: &str = "ui.locale";
6const PREFERENCE_KEY: &str = "preference";
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
9pub enum LocalePreference {
10 #[default]
11 Auto,
12 English,
13 German,
14}
15
16impl LocalePreference {
17 pub const ALL: [LocalePreference; 3] = [
18 LocalePreference::Auto,
19 LocalePreference::English,
20 LocalePreference::German,
21 ];
22
23 pub fn key(self) -> &'static str {
24 match self {
25 LocalePreference::Auto => "auto",
26 LocalePreference::English => "en",
27 LocalePreference::German => "de",
28 }
29 }
30
31 pub fn from_key(key: &str) -> Option<LocalePreference> {
32 Self::ALL
33 .into_iter()
34 .find(|preference| preference.key() == key)
35 }
36}
37
38pub fn os_language_tag() -> String {
39 sys_locale::get_locale().unwrap_or_else(|| "en".to_owned())
40}
41
42pub fn effective_locale(pref: LocalePreference) -> &'static str {
43 effective_locale_for(pref, &os_language_tag())
44}
45
46pub(crate) fn effective_locale_for(pref: LocalePreference, os_tag: &str) -> &'static str {
47 match pref {
48 LocalePreference::German => "de",
49 LocalePreference::English => "en",
50 LocalePreference::Auto => {
51 if os_tag.to_lowercase().starts_with("de") {
52 "de"
53 } else {
54 "en"
55 }
56 }
57 }
58}
59
60pub fn apply_locale(locale: &str) {
61 rust_i18n::set_locale(locale);
62 gpui_kit::component::set_locale(locale);
63}
64
65pub fn load(store: &Store) -> LocalePreference {
66 store
67 .meta(META_KEY)
68 .ok()
69 .flatten()
70 .map(|text| parse(&text))
71 .unwrap_or_default()
72}
73
74pub fn save(store: &Store, pref: LocalePreference) {
75 let _ = store.set_meta(META_KEY, &serialize(pref));
76}
77
78fn serialize(pref: LocalePreference) -> String {
79 format!("{PREFERENCE_KEY}={}", pref.key())
80}
81
82fn parse(text: &str) -> LocalePreference {
83 for line in text.lines() {
84 if let Some((PREFERENCE_KEY, value)) = line.split_once('=') {
85 if let Some(pref) = LocalePreference::from_key(value.trim()) {
86 return pref;
87 }
88 }
89 }
90 LocalePreference::default()
91}
92
93pub fn tr(key: &str) -> String {
94 rust_i18n::t!(key).to_string()
95}
96
97pub fn tr_args(key: &str, args: &HashMap<String, String>) -> String {
98 if args.is_empty() {
99 return tr(key);
100 }
101 let patterns: Vec<&str> = args.keys().map(String::as_str).collect();
102 let values: Vec<String> = patterns.iter().map(|name| args[*name].clone()).collect();
103 rust_i18n::replace_patterns(&tr(key), &patterns, &values)
104}
105
106/// Separator between an i18n key and a detail payload in `CallUpdate::Notice`.
107pub const NOTICE_DETAIL_SEP: char = '\u{1f}';
108
109/// Resolve a call/UI notice payload: bare key, or `key` + detail after [`NOTICE_DETAIL_SEP`].
110pub fn localize_notice(payload: &str) -> String {
111 if let Some((key, detail)) = payload.split_once(NOTICE_DETAIL_SEP) {
112 let mut args = HashMap::new();
113 args.insert("detail".to_owned(), detail.to_owned());
114 return tr_args(key, &args);
115 }
116 if payload.contains('.') {
117 return tr(payload);
118 }
119 payload.to_owned()
120}
121
122pub fn notice_payload(key: &str, detail: impl std::fmt::Display) -> String {
123 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
124}
125
126#[cfg(test)]
127mod tests {
128 use std::sync::{Mutex, MutexGuard};
129
130 use super::*;
131 use tempfile::tempdir;
132
133 fn locale_test_lock() -> MutexGuard<'static, ()> {
134 static LOCK: Mutex<()> = Mutex::new(());
135 LOCK.lock().unwrap_or_else(|error| error.into_inner())
136 }
137
138 #[test]
139 fn ui_locale_effective_prefers_explicit_english_and_german() {
140 let _guard = locale_test_lock();
141 assert_eq!(effective_locale_for(LocalePreference::English, "de-DE"), "en");
142 assert_eq!(effective_locale_for(LocalePreference::German, "en-US"), "de");
143 }
144
145 #[test]
146 fn ui_locale_effective_auto_follows_os_tag() {
147 let _guard = locale_test_lock();
148 assert_eq!(effective_locale_for(LocalePreference::Auto, "de-DE"), "de");
149 assert_eq!(effective_locale_for(LocalePreference::Auto, "de"), "de");
150 assert_eq!(effective_locale_for(LocalePreference::Auto, "en-US"), "en");
151 assert_eq!(effective_locale_for(LocalePreference::Auto, "fr-FR"), "en");
152 }
153
154 #[test]
155 fn ui_locale_load_save_roundtrip_in_store() {
156 let _guard = locale_test_lock();
157 let store = Store::open_in_memory().expect("in-memory store");
158 assert_eq!(load(&store), LocalePreference::Auto);
159 save(&store, LocalePreference::German);
160 assert_eq!(load(&store), LocalePreference::German);
161 save(&store, LocalePreference::English);
162 assert_eq!(load(&store), LocalePreference::English);
163 }
164
165 #[test]
166 fn ui_locale_persists_via_tempfile_store() {
167 let _guard = locale_test_lock();
168 let directory = tempdir().expect("tempdir");
169 let path = directory.path().join("locale.sqlite3");
170 let store = Store::open(&path).expect("store on disk");
171 save(&store, LocalePreference::German);
172 drop(store);
173 let store = Store::open(&path).expect("reopen store");
174 assert_eq!(load(&store), LocalePreference::German);
175 }
176
177 #[test]
178 fn ui_locale_unknown_preference_falls_back_to_auto() {
179 let _guard = locale_test_lock();
180 let store = Store::open_in_memory().expect("in-memory store");
181 let _ = store.set_meta(META_KEY, "preference=fr");
182 assert_eq!(load(&store), LocalePreference::Auto);
183 }
184
185 #[test]
186 fn ui_locale_tr_resolves_catalog_in_en_and_de() {
187 let _guard = locale_test_lock();
188 apply_locale("en");
189 assert_eq!(tr("common.cancel"), "Cancel");
190 apply_locale("de");
191 assert_eq!(tr("common.cancel"), "Abbrechen");
192 }
193
194 #[test]
195 fn ui_locale_tr_args_substitutes_detail() {
196 let _guard = locale_test_lock();
197 apply_locale("en");
198 let mut args = HashMap::new();
199 args.insert("detail".to_owned(), "timeout".to_owned());
200 assert_eq!(
201 tr_args("notice.generic_detail", &args),
202 "Something went wrong: timeout"
203 );
204 }
205
206 #[test]
207 fn ui_locale_notice_localizes_call_on_hold_in_de() {
208 let _guard = locale_test_lock();
209 apply_locale("de");
210 let localized = localize_notice("calls.notice.on_hold");
211 assert_eq!(localized, "Setzen Sie den Anruf zuerst fort");
212 }
213
214 #[test]
215 fn ui_locale_sidebar_and_status_menu_in_de() {
216 let _guard = locale_test_lock();
217 apply_locale("de");
218 assert_eq!(tr("sidebar.quick_views"), "Schnellansichten");
219 assert_eq!(tr("status_menu.view_account"), "Konto anzeigen");
220 assert_eq!(tr("shell.settings_and_more"), "Einstellungen und mehr");
221 }
222
223 #[test]
224 fn ui_locale_tray_keys_resolve() {
225 let _guard = locale_test_lock();
226 apply_locale("en");
227 assert_eq!(tr("tray.open"), "Open");
228 assert_eq!(tr("tray.quit"), "Quit");
229 assert_eq!(tr("tray.mute_sound"), "Mute sound");
230 apply_locale("de");
231 assert_eq!(tr("tray.do_not_disturb"), "Nicht stören");
232 assert_eq!(tr("tray.notifications"), "Benachrichtigungen");
233 }
234
235 #[test]
236 fn ui_locale_fallback_missing_key_returns_english_or_key() {
237 let _guard = locale_test_lock();
238 apply_locale("de");
239 assert_eq!(tr("common.cancel"), "Abbrechen");
240 let missing = tr("catalog.does_not_exist_yet");
241 assert!(!missing.is_empty());
242 }
243}
crates/app-state/src/app_state.rs +8 −8
@@ -37,19 +37,19 @@ pub enum QuickView {
37 37 }
38 38
39 39 impl QuickView {
40 pub fn title(self) -> &'static str {
40 pub fn title(self) -> String {
41 41 match self {
42 QuickView::Mentions => "Mentions",
43 QuickView::Drafts => "Drafts",
44 QuickView::Saved => "Saved",
42 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions"),
43 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts"),
44 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved"),
45 45 }
46 46 }
47 47
48 pub fn empty_text(self) -> &'static str {
48 pub fn empty_text(self) -> String {
49 49 match self {
50 QuickView::Mentions => "No mentions yet. When someone @mentions you, it shows up here.",
51 QuickView::Drafts => "No drafts. Messages you start and do not send show up here.",
52 QuickView::Saved => "No saved messages. Use Save message in the ... menu of a message.",
50 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions_empty"),
51 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts_empty"),
52 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved_empty"),
53 53 }
54 54 }
55 55 }
@@ -37,19 +37,19 @@ pub enum QuickView {
37}
37}
38
38
39impl QuickView {
39impl QuickView {
40 pub fn title(self) -> &'static str {
40 pub fn title(self) -> String {
41 match self {
41 match self {
42 QuickView::Mentions => "Mentions",
42 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions"),
43 QuickView::Drafts => "Drafts",
43 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts"),
44 QuickView::Saved => "Saved",
44 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved"),
45 }
45 }
46 }
46 }
47
47
48 pub fn empty_text(self) -> &'static str {
48 pub fn empty_text(self) -> String {
49 match self {
49 match self {
50 QuickView::Mentions => "No mentions yet. When someone @mentions you, it shows up here.",
50 QuickView::Mentions => app_base::ui_locale::tr("sidebar.quick_view.mentions_empty"),
51 QuickView::Drafts => "No drafts. Messages you start and do not send show up here.",
51 QuickView::Drafts => app_base::ui_locale::tr("sidebar.quick_view.drafts_empty"),
52 QuickView::Saved => "No saved messages. Use Save message in the ... menu of a message.",
52 QuickView::Saved => app_base::ui_locale::tr("sidebar.quick_view.saved_empty"),
53 }
53 }
54 }
54 }
55}
55}
crates/app-state/src/call/actions.rs +2 −1
@@ -5,6 +5,7 @@ use calling::{
5 5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7 7 };
8 use app_base::ui_locale::localize_notice;
8 9 use gpui_kit::*;
9 10
10 11 use super::background::{
@@ -489,7 +490,7 @@ impl AppState {
489 490 return;
490 491 }
491 492 CallUpdate::Notice(text) => {
492 self.raise_notice(text, None, cx);
493 self.raise_notice(localize_notice(&text), None, cx);
493 494 return;
494 495 }
495 496 CallUpdate::WhiteboardUrl(url) => {
@@ -5,6 +5,7 @@ use calling::{
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
5 AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, CameraEffects,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
6 DeviceChoice, EndReason, EngineEvent, MicSettings, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
7};
7};
8use app_base::ui_locale::localize_notice;
8use gpui_kit::*;
9use gpui_kit::*;
9
10
10use super::background::{
11use super::background::{
@@ -489,7 +490,7 @@ impl AppState {
489 return;
490 return;
490 }
491 }
491 CallUpdate::Notice(text) => {
492 CallUpdate::Notice(text) => {
492 self.raise_notice(text, None, cx);
493 self.raise_notice(localize_notice(&text), None, cx);
493 return;
494 return;
494 }
495 }
495 CallUpdate::WhiteboardUrl(url) => {
496 CallUpdate::WhiteboardUrl(url) => {
crates/app-state/src/call/consult.rs +1 −1
@@ -110,7 +110,7 @@ impl AppState {
110 110 };
111 111 match update {
112 112 CallUpdate::Notice(text) => {
113 self.raise_notice(text, None, cx);
113 self.raise_notice(app_base::ui_locale::localize_notice(&text), None, cx);
114 114 return;
115 115 }
116 116 CallUpdate::TransferResult { succeeded } => {
@@ -110,7 +110,7 @@ impl AppState {
110 };
110 };
111 match update {
111 match update {
112 CallUpdate::Notice(text) => {
112 CallUpdate::Notice(text) => {
113 self.raise_notice(text, None, cx);
113 self.raise_notice(app_base::ui_locale::localize_notice(&text), None, cx);
114 return;
114 return;
115 }
115 }
116 CallUpdate::TransferResult { succeeded } => {
116 CallUpdate::TransferResult { succeeded } => {
crates/app-state/src/channel_filter.rs +7 −2
@@ -1,7 +1,12 @@
1 1 use store::SidebarTeam;
2 2
3 pub const CHANNEL_FILTER_PLACEHOLDER: &str = "Filter by channel name";
4 pub const UNREAD_PILL: &str = "Unread";
3 pub fn channel_filter_placeholder() -> String {
4 app_base::ui_locale::tr("sidebar.filter.channel_placeholder")
5 }
6
7 pub fn channel_unread_pill() -> String {
8 app_base::ui_locale::tr("sidebar.filter.unread")
9 }
5 10
6 11 #[derive(Debug, Clone, Default, PartialEq, Eq)]
7 12 pub struct ChannelFilter {
@@ -1,7 +1,12 @@
1use store::SidebarTeam;
1use store::SidebarTeam;
2
2
3pub const CHANNEL_FILTER_PLACEHOLDER: &str = "Filter by channel name";
3pub fn channel_filter_placeholder() -> String {
4pub const UNREAD_PILL: &str = "Unread";
4 app_base::ui_locale::tr("sidebar.filter.channel_placeholder")
5}
6
7pub fn channel_unread_pill() -> String {
8 app_base::ui_locale::tr("sidebar.filter.unread")
9}
5
10
6#[derive(Debug, Clone, Default, PartialEq, Eq)]
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
7pub struct ChannelFilter {
12pub struct ChannelFilter {
crates/app-state/src/chat_filter.rs +30 −12
@@ -6,12 +6,30 @@ use crate::activity::{Entry, Kind};
6 6 use crate::app_state::chat_title;
7 7 use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
8 8
9 pub const FILTER_PLACEHOLDER: &str = "Filter by person or chat name";
10 pub const NO_MATCHES: &str = "We didn't find any matches.";
11 pub const CLEAR_FILTERS: &str = "Clear filters";
12 pub const CLEAR_FILTER_TEXT: &str = "Clear filter text";
13 pub const SHOW_FILTER_TEXT: &str = "Show filter text box";
14 pub const CLOSE_FILTER_TEXT: &str = "Close filter text box";
9 pub fn filter_placeholder() -> String {
10 app_base::ui_locale::tr("sidebar.filter.placeholder")
11 }
12
13 pub fn filter_no_matches() -> String {
14 app_base::ui_locale::tr("sidebar.filter.no_matches")
15 }
16
17 pub fn filter_clear_all() -> String {
18 app_base::ui_locale::tr("sidebar.filter.clear")
19 }
20
21 pub fn filter_clear_text() -> String {
22 app_base::ui_locale::tr("sidebar.filter.clear_text")
23 }
24
25 pub fn filter_show_box() -> String {
26 app_base::ui_locale::tr("sidebar.filter.show_box")
27 }
28
29 pub fn filter_close_box() -> String {
30 app_base::ui_locale::tr("sidebar.filter.close_box")
31 }
32
15 33 pub const MORE_FILTERS: &str = "More filters";
16 34 pub const FEWER_FILTERS: &str = "Fewer filters";
17 35 const MEETING_KIND: &str = "meeting";
@@ -33,13 +51,13 @@ impl ChatFilterPill {
33 51 ];
34 52 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Mentions, ChatFilterPill::Muted];
35 53
36 pub fn label(self) -> &'static str {
54 pub fn label(self) -> String {
37 55 match self {
38 ChatFilterPill::Unread => "Unread",
39 ChatFilterPill::Mentions => "@Mentions",
40 ChatFilterPill::Chats => "Chats",
41 ChatFilterPill::Meetings => "Meeting chats",
42 ChatFilterPill::Muted => "Muted",
56 ChatFilterPill::Unread => app_base::ui_locale::tr("sidebar.pill.unread"),
57 ChatFilterPill::Mentions => app_base::ui_locale::tr("sidebar.pill.mentions"),
58 ChatFilterPill::Chats => app_base::ui_locale::tr("sidebar.pill.chats"),
59 ChatFilterPill::Meetings => app_base::ui_locale::tr("sidebar.pill.meetings"),
60 ChatFilterPill::Muted => app_base::ui_locale::tr("sidebar.pill.muted"),
43 61 }
44 62 }
45 63
@@ -6,12 +6,30 @@ use crate::activity::{Entry, Kind};
6use crate::app_state::chat_title;
6use crate::app_state::chat_title;
7use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
7use crate::sidebar_model::{MUTED_ID, OTHERS_ID, Section, SectionInput, build_sections};
8
8
9pub const FILTER_PLACEHOLDER: &str = "Filter by person or chat name";
9pub fn filter_placeholder() -> String {
10pub const NO_MATCHES: &str = "We didn't find any matches.";
10 app_base::ui_locale::tr("sidebar.filter.placeholder")
11pub const CLEAR_FILTERS: &str = "Clear filters";
11}
12pub const CLEAR_FILTER_TEXT: &str = "Clear filter text";
12
13pub const SHOW_FILTER_TEXT: &str = "Show filter text box";
13pub fn filter_no_matches() -> String {
14pub const CLOSE_FILTER_TEXT: &str = "Close filter text box";
14 app_base::ui_locale::tr("sidebar.filter.no_matches")
15}
16
17pub fn filter_clear_all() -> String {
18 app_base::ui_locale::tr("sidebar.filter.clear")
19}
20
21pub fn filter_clear_text() -> String {
22 app_base::ui_locale::tr("sidebar.filter.clear_text")
23}
24
25pub fn filter_show_box() -> String {
26 app_base::ui_locale::tr("sidebar.filter.show_box")
27}
28
29pub fn filter_close_box() -> String {
30 app_base::ui_locale::tr("sidebar.filter.close_box")
31}
32
15pub const MORE_FILTERS: &str = "More filters";
33pub const MORE_FILTERS: &str = "More filters";
16pub const FEWER_FILTERS: &str = "Fewer filters";
34pub const FEWER_FILTERS: &str = "Fewer filters";
17const MEETING_KIND: &str = "meeting";
35const MEETING_KIND: &str = "meeting";
@@ -33,13 +51,13 @@ impl ChatFilterPill {
33 ];
51 ];
34 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Mentions, ChatFilterPill::Muted];
52 pub const OVERFLOW: [ChatFilterPill; 2] = [ChatFilterPill::Mentions, ChatFilterPill::Muted];
35
53
36 pub fn label(self) -> &'static str {
54 pub fn label(self) -> String {
37 match self {
55 match self {
38 ChatFilterPill::Unread => "Unread",
56 ChatFilterPill::Unread => app_base::ui_locale::tr("sidebar.pill.unread"),
39 ChatFilterPill::Mentions => "@Mentions",
57 ChatFilterPill::Mentions => app_base::ui_locale::tr("sidebar.pill.mentions"),
40 ChatFilterPill::Chats => "Chats",
58 ChatFilterPill::Chats => app_base::ui_locale::tr("sidebar.pill.chats"),
41 ChatFilterPill::Meetings => "Meeting chats",
59 ChatFilterPill::Meetings => app_base::ui_locale::tr("sidebar.pill.meetings"),
42 ChatFilterPill::Muted => "Muted",
60 ChatFilterPill::Muted => app_base::ui_locale::tr("sidebar.pill.muted"),
43 }
61 }
44 }
62 }
45
63
crates/app-ui-kit/src/settings_controls.rs +1 −1
@@ -154,7 +154,7 @@ pub fn link_dropdown(
154 154 })
155 155 }
156 156
157 pub fn section_header(title: &'static str, trailing: Option<AnyElement>) -> Div {
157 pub fn section_header(title: String, trailing: Option<AnyElement>) -> Div {
158 158 h_flex()
159 159 .w_full()
160 160 .items_center()
@@ -154,7 +154,7 @@ pub fn link_dropdown(
154 })
154 })
155}
155}
156
156
157pub fn section_header(title: &'static str, trailing: Option<AnyElement>) -> Div {
157pub fn section_header(title: String, trailing: Option<AnyElement>) -> Div {
158 h_flex()
158 h_flex()
159 .w_full()
159 .w_full()
160 .items_center()
160 .items_center()
crates/app/src/active_locale.rs added +34 −0
@@ -0,0 +1,34 @@
1 use app_base::ui_locale::{self, LocalePreference};
2 use gpui_kit::*;
3 use store::Store;
4
5 #[derive(Default)]
6 pub struct ActiveLocale {
7 preference: LocalePreference,
8 }
9
10 impl Global for ActiveLocale {}
11
12 pub fn install(store: &Store, cx: &mut App) {
13 let preference = ui_locale::load(store);
14 ui_locale::apply_locale(ui_locale::effective_locale(preference));
15 cx.set_global(ActiveLocale { preference });
16 }
17
18 pub fn current_preference(cx: &App) -> LocalePreference {
19 cx.try_global::<ActiveLocale>()
20 .map(|active| active.preference)
21 .unwrap_or_default()
22 }
23
24 #[allow(dead_code)]
25 pub fn effective(cx: &App) -> &'static str {
26 ui_locale::effective_locale(current_preference(cx))
27 }
28
29 pub fn set_preference(pref: LocalePreference, store: &Store, cx: &mut App) {
30 ui_locale::save(store, pref);
31 ui_locale::apply_locale(ui_locale::effective_locale(pref));
32 cx.set_global(ActiveLocale { preference: pref });
33 cx.refresh_windows();
34 }
@@ -0,0 +1,34 @@
1use app_base::ui_locale::{self, LocalePreference};
2use gpui_kit::*;
3use store::Store;
4
5#[derive(Default)]
6pub struct ActiveLocale {
7 preference: LocalePreference,
8}
9
10impl Global for ActiveLocale {}
11
12pub fn install(store: &Store, cx: &mut App) {
13 let preference = ui_locale::load(store);
14 ui_locale::apply_locale(ui_locale::effective_locale(preference));
15 cx.set_global(ActiveLocale { preference });
16}
17
18pub fn current_preference(cx: &App) -> LocalePreference {
19 cx.try_global::<ActiveLocale>()
20 .map(|active| active.preference)
21 .unwrap_or_default()
22}
23
24#[allow(dead_code)]
25pub fn effective(cx: &App) -> &'static str {
26 ui_locale::effective_locale(current_preference(cx))
27}
28
29pub fn set_preference(pref: LocalePreference, store: &Store, cx: &mut App) {
30 ui_locale::save(store, pref);
31 ui_locale::apply_locale(ui_locale::effective_locale(pref));
32 cx.set_global(ActiveLocale { preference: pref });
33 cx.refresh_windows();
34}
crates/app/src/agents/settings_section.rs +334 −26
@@ -1,4 +1,4 @@
1 use agents::{AgentAction, AgentProfile, Environment, OutputFormat};
1 use agents::{AgentAction, AgentBackend, AgentProfile, Environment, OutputFormat};
2 2 use gpui_kit::assets::IconName;
3 3 use gpui_kit::component::{
4 4 button::{Button, ButtonVariants as _},
@@ -11,13 +11,15 @@ use gpui_kit::*;
11 11
12 12 use super::environment_label;
13 13 use super::runs::AgentRuns;
14 use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
14 use super::settings_controls::{
15 Choice, MenuEntry, PAGE_PADDING, dropdown, link_dropdown, section_header,
16 };
15 17 use super::settings_forms::resume_toggle;
18 use crate::i18n::{tr, tr_args};
16 19 use crate::runtime;
17 20 use crate::theme;
18 21 use crate::views::widgets::icon;
19 22
20 const NOTE: &str = "Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.";
21 23 const DEFAULT_DISTRO: &str = "Ubuntu";
22 24 const PROMPT_MIN_ROWS: usize = 4;
23 25 const PROMPT_MAX_ROWS: usize = 8;
@@ -44,6 +46,9 @@ pub(super) struct AgentForm {
44 46 pub command: Entity<InputState>,
45 47 pub open_session: Entity<InputState>,
46 48 pub mcp_flag: Entity<InputState>,
49 pub base_url: Entity<InputState>,
50 pub model: Entity<InputState>,
51 pub api_key: Entity<InputState>,
47 52 }
48 53
49 54 pub(super) struct ActionForm {
@@ -60,6 +65,10 @@ pub struct AgentsSettings {
60 65 pub(super) agent_form: Option<AgentForm>,
61 66 pub(super) action_form: Option<ActionForm>,
62 67 pub(super) probe: Probe,
68 pub(super) models: Vec<String>,
69 models_request: u64,
70 pub(super) found: Vec<agents::CliHit>,
71 scanned: bool,
63 72 form_subscriptions: Vec<Subscription>,
64 73 _runs_subscription: Subscription,
65 74 }
@@ -98,6 +107,10 @@ impl AgentsSettings {
98 107 agent_form: None,
99 108 action_form: None,
100 109 probe: Probe::Idle,
110 models: Vec::new(),
111 models_request: 0,
112 found: Vec::new(),
113 scanned: false,
101 114 form_subscriptions: Vec::new(),
102 115 _runs_subscription: subscription,
103 116 }
@@ -109,6 +122,8 @@ impl AgentsSettings {
109 122 self.action_form = None;
110 123 self.form_subscriptions.clear();
111 124 self.probe = Probe::Idle;
125 self.models.clear();
126 self.models_request += 1;
112 127 cx.notify();
113 128 }
114 129
@@ -151,6 +166,13 @@ impl AgentsSettings {
151 166 } => distro.clone(),
152 167 _ => String::new(),
153 168 };
169 let (base_url, model) = match &profile.backend {
170 AgentBackend::OpenAi {
171 base_url, model, ..
172 } => (base_url.clone(), model.clone()),
173 AgentBackend::Anthropic { model, .. } => (String::new(), model.clone()),
174 AgentBackend::Command => (String::new(), String::new()),
175 };
154 176 self.agent_form = Some(AgentForm {
155 177 id: profile.id.clone(),
156 178 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
@@ -163,11 +185,35 @@ impl AgentsSettings {
163 185 Self::commit_agent,
164 186 ),
165 187 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
188 base_url: self.line_input(&base_url, window, cx, Self::commit_agent),
189 model: self.line_input(&model, window, cx, Self::commit_agent),
190 api_key: self.line_input("", window, cx, Self::commit_agent),
166 191 });
192 let inputs = self
193 .agent_form
194 .as_ref()
195 .map(|form| (form.base_url.clone(), form.api_key.clone()));
196 if let Some((base_url, api_key)) = inputs {
197 self.watch_model_refresh(&base_url, cx);
198 self.watch_model_refresh(&api_key, cx);
199 }
167 200 self.page = Page::Agent;
201 if profile.is_chat() {
202 self.refresh_models(cx);
203 }
168 204 cx.notify();
169 205 }
170 206
207 fn watch_model_refresh(&mut self, input: &Entity<InputState>, cx: &mut Context<Self>) {
208 self.form_subscriptions
209 .push(cx.subscribe(input, |this, _, event: &InputEvent, cx| {
210 if matches!(event, InputEvent::Blur) {
211 this.commit_agent(cx);
212 this.refresh_models(cx);
213 }
214 }));
215 }
216
171 217 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
172 218 let Some(action) = self
173 219 .runs
@@ -213,6 +259,9 @@ impl AgentsSettings {
213 259 let command = form.command.read(cx).value().to_string();
214 260 let open_session = form.open_session.read(cx).value().to_string();
215 261 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
262 let base_url = form.base_url.read(cx).value().trim().to_owned();
263 let model = form.model.read(cx).value().trim().to_owned();
264 let typed_key = form.api_key.read(cx).value().trim().to_owned();
216 265 self.runs.update(cx, |runs, cx| {
217 266 runs.update_settings(
218 267 |settings| {
@@ -221,20 +270,96 @@ impl AgentsSettings {
221 270 return;
222 271 };
223 272 agent.name = name;
224 agent.command = command;
225 agent.open_session_command = open_session;
226 agent.mcp_config_flag = mcp_flag;
227 if let Environment::Wsl {
228 distro: Some(current),
229 } = &mut agent.environment
230 {
231 *current = distro;
273 if agent.is_chat() {
274 match &mut agent.backend {
275 AgentBackend::OpenAi {
276 base_url: url,
277 model: current,
278 api_key,
279 } => {
280 *url = base_url;
281 *current = model;
282 if !typed_key.is_empty() {
283 *api_key = typed_key;
284 }
285 }
286 AgentBackend::Anthropic {
287 model: current,
288 api_key,
289 } => {
290 *current = model;
291 if !typed_key.is_empty() {
292 *api_key = typed_key;
293 }
294 }
295 AgentBackend::Command => {}
296 }
297 } else {
298 agent.command = command;
299 agent.open_session_command = open_session;
300 agent.mcp_config_flag = mcp_flag;
301 if let Environment::Wsl {
302 distro: Some(current),
303 } = &mut agent.environment
304 {
305 *current = distro;
306 }
232 307 }
233 308 },
234 309 cx,
235 310 )
236 311 });
237 self.probe = Probe::Idle;
312 }
313
314 pub(super) fn set_model(&mut self, model: String, window: &mut Window, cx: &mut Context<Self>) {
315 let Some(form) = &self.agent_form else {
316 return;
317 };
318 form.model
319 .update(cx, |input, cx| input.set_value(model, window, cx));
320 self.commit_agent(cx);
321 }
322
323 pub(super) fn refresh_models(&mut self, cx: &mut Context<Self>) {
324 let Some(profile) = self.current_agent(cx) else {
325 return;
326 };
327 if !profile.is_chat() {
328 return;
329 }
330 self.models_request += 1;
331 let ticket = self.models_request;
332 self.probe = Probe::Running;
333 cx.notify();
334 let receiver = runtime::spawn(async move { agents::list_models(&profile).await });
335 cx.spawn(async move |this, cx| {
336 let result = receiver
337 .await
338 .unwrap_or_else(|_| Err("cancelled".to_owned()));
339 this.update(cx, |this, cx| {
340 if this.models_request != ticket {
341 return;
342 }
343 match result {
344 Ok(names) => {
345 let count = names.len();
346 this.models = names;
347 this.probe = Probe::Found(if count == 1 {
348 "1 model".to_owned()
349 } else {
350 format!("{count} models")
351 });
352 }
353 Err(error) => {
354 this.models.clear();
355 this.probe = Probe::Missing(error);
356 }
357 }
358 cx.notify();
359 })
360 .ok();
361 })
362 .detach();
238 363 }
239 364
240 365 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
@@ -319,6 +444,18 @@ impl AgentsSettings {
319 444 self.update_action(cx, move |action| action.agent_id = agent_id);
320 445 }
321 446
447 pub(super) fn set_write_with(&mut self, agent_id: String, cx: &mut Context<Self>) {
448 self.runs.update(cx, |runs, cx| {
449 runs.update_settings(|settings| settings.write_with = agent_id, cx)
450 });
451 }
452
453 pub(super) fn rescan(&mut self, cx: &mut Context<Self>) {
454 self.found = agents::scan_clis();
455 self.scanned = true;
456 cx.notify();
457 }
458
322 459 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
323 460 self.runs.update(cx, |runs, cx| {
324 461 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
@@ -393,6 +530,10 @@ impl AgentsSettings {
393 530 let Some(profile) = self.current_agent(cx) else {
394 531 return;
395 532 };
533 if profile.is_chat() {
534 self.refresh_models(cx);
535 return;
536 }
396 537 if profile.command.trim().is_empty() {
397 538 self.probe = Probe::Missing("The command is empty".to_owned());
398 539 cx.notify();
@@ -443,8 +584,30 @@ impl AgentsSettings {
443 584 existing.iter().any(|id| id == candidate)
444 585 });
445 586 let id = profile.id.clone();
587 let chat = profile.is_chat();
588 let mut action = AgentAction::answer_this(&id);
589 action.extra_args.clear();
590 let mut args = std::collections::HashMap::new();
591 args.insert("name".to_owned(), profile.name.clone());
592 action.label = tr_args("agents.settings.answer_with", &args);
593 action.id = unique_id(&format!("answer-{id}"), |candidate| {
594 self.runs
595 .read(cx)
596 .settings()
597 .actions
598 .iter()
599 .any(|action| action.id == candidate)
600 });
446 601 self.runs.update(cx, |runs, cx| {
447 runs.update_settings(|settings| settings.agents.push(profile), cx)
602 runs.update_settings(
603 |settings| {
604 settings.agents.push(profile);
605 if chat {
606 settings.actions.push(action);
607 }
608 },
609 cx,
610 )
448 611 });
449 612 self.open_agent(&id, window, cx);
450 613 }
@@ -457,7 +620,7 @@ impl AgentsSettings {
457 620 .map(|agent| agent.id.clone())
458 621 .unwrap_or_default();
459 622 let mut action = AgentAction::answer_this(&agent_id);
460 action.label = "New action".to_owned();
623 action.label = tr("agents.settings.new_action");
461 624 action.id = unique_id("action", |candidate| {
462 625 settings.actions.iter().any(|action| action.id == candidate)
463 626 });
@@ -482,26 +645,83 @@ impl AgentsSettings {
482 645
483 646 type Preset = (&'static str, fn() -> AgentProfile);
484 647
485 fn agent_presets() -> [Preset; 4] {
648 fn agent_presets() -> [Preset; 9] {
486 649 fn custom() -> AgentProfile {
487 650 AgentProfile {
488 651 id: "custom".to_owned(),
489 name: "Custom agent".to_owned(),
652 name: tr("agents.settings.custom_agent"),
490 653 environment: Environment::Host,
491 command: String::new(),
492 654 output: OutputFormat::Text,
493 open_session_command: String::new(),
494 mcp_config_flag: String::new(),
655 ..AgentProfile::default()
495 656 }
496 657 }
497 658 [
498 ("Claude Code (WSL)", AgentProfile::claude_wsl),
659 (
660 "Claude Code (WSL)",
661 AgentProfile::claude_wsl as fn() -> AgentProfile,
662 ),
499 663 ("Claude Code (Windows)", AgentProfile::claude_host),
500 664 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
665 ("Ollama", AgentProfile::ollama),
666 ("OpenAI", AgentProfile::openai),
667 ("OpenRouter", AgentProfile::openrouter),
668 ("Anthropic", AgentProfile::anthropic),
669 ("OpenAI-compatible", AgentProfile::openai_compatible),
501 670 ("Custom", custom),
502 671 ]
503 672 }
504 673
674 fn write_with_label(settings: &agents::AgentSettings) -> String {
675 if settings.write_with.is_empty() {
676 return "Microsoft Copilot".to_owned();
677 }
678 settings
679 .agents
680 .iter()
681 .find(|agent| agent.id == settings.write_with && agent.is_chat())
682 .map(|agent| agent.name.clone())
683 .unwrap_or_else(|| "Microsoft Copilot".to_owned())
684 }
685
686 fn write_with_entries(
687 settings: &agents::AgentSettings,
688 this: &Entity<AgentsSettings>,
689 ) -> Vec<MenuEntry> {
690 let mut entries = vec![write_with_entry(
691 this,
692 "Microsoft Copilot",
693 "",
694 settings.write_with.is_empty(),
695 )];
696 for agent in settings.agents.iter().filter(|agent| agent.is_chat()) {
697 entries.push(write_with_entry(
698 this,
699 &agent.name,
700 &agent.id,
701 settings.write_with == agent.id,
702 ));
703 }
704 entries
705 }
706
707 fn write_with_entry(
708 this: &Entity<AgentsSettings>,
709 label: &str,
710 agent_id: &str,
711 selected: bool,
712 ) -> MenuEntry {
713 let (this, agent_id) = (this.clone(), agent_id.to_owned());
714 let choose: Choice = std::rc::Rc::new(move |_, cx| {
715 let agent_id = agent_id.clone();
716 this.update(cx, |this, cx| this.set_write_with(agent_id, cx))
717 });
718 MenuEntry {
719 label: label.to_owned(),
720 selected,
721 choose,
722 }
723 }
724
505 725 fn list_row(
506 726 id: (&'static str, usize),
507 727 leading: Option<AnyElement>,
@@ -568,7 +788,17 @@ fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Sta
568 788
569 789 impl AgentsSettings {
570 790 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
791 if !self.scanned {
792 self.found = agents::scan_clis();
793 self.scanned = true;
794 }
571 795 let settings = self.runs.read(cx).settings().clone();
796 let found: Vec<agents::CliHit> = self
797 .found
798 .iter()
799 .filter(|hit| !agents::already_installed(&settings.agents, &hit.profile))
800 .cloned()
801 .collect();
572 802 let this = cx.entity();
573 803 let preset_entries: Vec<MenuEntry> = agent_presets()
574 804 .into_iter()
@@ -611,8 +841,12 @@ impl AgentsSettings {
611 841 .into_any_element(),
612 842 ),
613 843 agent.name.clone(),
614 environment_label(&agent.environment),
615 Some(agent.command.clone()),
844 if agent.is_chat() {
845 agent.backend_label()
846 } else {
847 environment_label(&agent.environment)
848 },
849 agent.is_command().then(|| agent.command.clone()),
616 850 )
617 851 .on_click(move |_, window, cx| {
618 852 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
@@ -625,7 +859,8 @@ impl AgentsSettings {
625 859 .agents
626 860 .iter()
627 861 .find(|agent| agent.id == action.agent_id)
628 .map_or("Unknown agent", |agent| agent.name.as_str());
862 .map(|agent| agent.name.clone())
863 .unwrap_or_else(|| tr("agents.settings.unknown_agent"));
629 864 list_row(
630 865 ("action-row", index),
631 866 None,
@@ -660,18 +895,91 @@ impl AgentsSettings {
660 895 ),
661 896 )
662 897 });
898 let write_entries = write_with_entries(&settings, &this);
899 let write_label = write_with_label(&settings);
900 let rescan = this.clone();
901 let found_rows = found.iter().enumerate().map(|(index, hit)| {
902 let (this, profile) = (this.clone(), hit.profile.clone());
903 list_row(
904 ("found-cli", index),
905 None,
906 hit.profile.name.clone(),
907 hit.binary.display().to_string(),
908 Some(hit.profile.command.clone()),
909 )
910 .child(
911 Button::new(("add-found", index))
912 .link()
913 .label(tr("common.add"))
914 .on_click(move |_, window, cx| {
915 let profile = profile.clone();
916 this.update(cx, |this, cx| this.add_agent(profile, window, cx))
917 }),
918 )
919 });
920 let on_computer = tr("agents.settings.on_this_computer");
921 let agents_header = tr("agents.settings.agents_header");
922 let actions_header = tr("agents.settings.actions_header");
663 923 v_flex()
664 924 .w_full()
665 925 .child(section_header(
666 "AGENTS",
926 on_computer.clone(),
927 Some(
928 Button::new("rescan-clis")
929 .link()
930 .label(tr("agents.settings.scan_again"))
931 .on_click(move |_, _, cx| {
932 rescan.update(cx, |this, cx| this.rescan(cx))
933 })
934 .into_any_element(),
935 ),
936 ))
937 .child(
938 v_flex()
939 .w_full()
940 .px(px(8.))
941 .children(found_rows)
942 .when(found.is_empty(), |rows| {
943 rows.child(
944 div()
945 .px(px(12.))
946 .py(px(8.))
947 .text_size(px(12.))
948 .text_color(theme::text_muted())
949 .child(tr("agents.settings.no_cli_found")),
950 )
951 }),
952 )
953 .child(section_header(
954 agents_header.clone(),
667 955 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
668 956 ))
669 957 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
670 958 .child(section_header(
671 "ACTIONS - IN THIS ORDER IN THE MENU",
959 actions_header,
672 960 Some(add_action.into_any_element()),
673 961 ))
674 962 .child(v_flex().w_full().px(px(8.)).children(action_rows))
963 .child(
964 v_flex()
965 .w_full()
966 .px(px(PAGE_PADDING))
967 .pt(px(16.))
968 .gap(px(6.))
969 .child(
970 div()
971 .text_size(px(14.))
972 .font_weight(FontWeight::SEMIBOLD)
973 .child(tr("agents.settings.write_with")),
974 )
975 .child(
976 div()
977 .text_size(px(12.))
978 .text_color(theme::text_muted())
979 .child(tr("agents.settings.rewrite_hint")),
980 )
981 .child(dropdown("write-with", write_label, write_entries)),
982 )
675 983 .child(resume_toggle(settings.resume_interrupted_runs, this))
676 984 .child(
677 985 div()
@@ -682,7 +990,7 @@ impl AgentsSettings {
682 990 .text_size(px(12.))
683 991 .line_height(relative(1.5))
684 992 .text_color(theme::text_faint())
685 .child(NOTE),
993 .child(tr("agents.settings.note")),
686 994 )
687 995 }
688 996 }
@@ -1,4 +1,4 @@
1use agents::{AgentAction, AgentProfile, Environment, OutputFormat};
1use agents::{AgentAction, AgentBackend, AgentProfile, Environment, OutputFormat};
2use gpui_kit::assets::IconName;
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
4 button::{Button, ButtonVariants as _},
@@ -11,13 +11,15 @@ use gpui_kit::*;
11
11
12use super::environment_label;
12use super::environment_label;
13use super::runs::AgentRuns;
13use super::runs::AgentRuns;
14use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
14use super::settings_controls::{
15 Choice, MenuEntry, PAGE_PADDING, dropdown, link_dropdown, section_header,
16};
15use super::settings_forms::resume_toggle;
17use super::settings_forms::resume_toggle;
18use crate::i18n::{tr, tr_args};
16use crate::runtime;
19use crate::runtime;
17use crate::theme;
20use crate::theme;
18use crate::views::widgets::icon;
21use crate::views::widgets::icon;
19
22
20const NOTE: &str = "Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.";
21const DEFAULT_DISTRO: &str = "Ubuntu";
23const DEFAULT_DISTRO: &str = "Ubuntu";
22const PROMPT_MIN_ROWS: usize = 4;
24const PROMPT_MIN_ROWS: usize = 4;
23const PROMPT_MAX_ROWS: usize = 8;
25const PROMPT_MAX_ROWS: usize = 8;
@@ -44,6 +46,9 @@ pub(super) struct AgentForm {
44 pub command: Entity<InputState>,
46 pub command: Entity<InputState>,
45 pub open_session: Entity<InputState>,
47 pub open_session: Entity<InputState>,
46 pub mcp_flag: Entity<InputState>,
48 pub mcp_flag: Entity<InputState>,
49 pub base_url: Entity<InputState>,
50 pub model: Entity<InputState>,
51 pub api_key: Entity<InputState>,
47}
52}
48
53
49pub(super) struct ActionForm {
54pub(super) struct ActionForm {
@@ -60,6 +65,10 @@ pub struct AgentsSettings {
60 pub(super) agent_form: Option<AgentForm>,
65 pub(super) agent_form: Option<AgentForm>,
61 pub(super) action_form: Option<ActionForm>,
66 pub(super) action_form: Option<ActionForm>,
62 pub(super) probe: Probe,
67 pub(super) probe: Probe,
68 pub(super) models: Vec<String>,
69 models_request: u64,
70 pub(super) found: Vec<agents::CliHit>,
71 scanned: bool,
63 form_subscriptions: Vec<Subscription>,
72 form_subscriptions: Vec<Subscription>,
64 _runs_subscription: Subscription,
73 _runs_subscription: Subscription,
65}
74}
@@ -98,6 +107,10 @@ impl AgentsSettings {
98 agent_form: None,
107 agent_form: None,
99 action_form: None,
108 action_form: None,
100 probe: Probe::Idle,
109 probe: Probe::Idle,
110 models: Vec::new(),
111 models_request: 0,
112 found: Vec::new(),
113 scanned: false,
101 form_subscriptions: Vec::new(),
114 form_subscriptions: Vec::new(),
102 _runs_subscription: subscription,
115 _runs_subscription: subscription,
103 }
116 }
@@ -109,6 +122,8 @@ impl AgentsSettings {
109 self.action_form = None;
122 self.action_form = None;
110 self.form_subscriptions.clear();
123 self.form_subscriptions.clear();
111 self.probe = Probe::Idle;
124 self.probe = Probe::Idle;
125 self.models.clear();
126 self.models_request += 1;
112 cx.notify();
127 cx.notify();
113 }
128 }
114
129
@@ -151,6 +166,13 @@ impl AgentsSettings {
151 } => distro.clone(),
166 } => distro.clone(),
152 _ => String::new(),
167 _ => String::new(),
153 };
168 };
169 let (base_url, model) = match &profile.backend {
170 AgentBackend::OpenAi {
171 base_url, model, ..
172 } => (base_url.clone(), model.clone()),
173 AgentBackend::Anthropic { model, .. } => (String::new(), model.clone()),
174 AgentBackend::Command => (String::new(), String::new()),
175 };
154 self.agent_form = Some(AgentForm {
176 self.agent_form = Some(AgentForm {
155 id: profile.id.clone(),
177 id: profile.id.clone(),
156 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
178 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
@@ -163,11 +185,35 @@ impl AgentsSettings {
163 Self::commit_agent,
185 Self::commit_agent,
164 ),
186 ),
165 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
187 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
188 base_url: self.line_input(&base_url, window, cx, Self::commit_agent),
189 model: self.line_input(&model, window, cx, Self::commit_agent),
190 api_key: self.line_input("", window, cx, Self::commit_agent),
166 });
191 });
192 let inputs = self
193 .agent_form
194 .as_ref()
195 .map(|form| (form.base_url.clone(), form.api_key.clone()));
196 if let Some((base_url, api_key)) = inputs {
197 self.watch_model_refresh(&base_url, cx);
198 self.watch_model_refresh(&api_key, cx);
199 }
167 self.page = Page::Agent;
200 self.page = Page::Agent;
201 if profile.is_chat() {
202 self.refresh_models(cx);
203 }
168 cx.notify();
204 cx.notify();
169 }
205 }
170
206
207 fn watch_model_refresh(&mut self, input: &Entity<InputState>, cx: &mut Context<Self>) {
208 self.form_subscriptions
209 .push(cx.subscribe(input, |this, _, event: &InputEvent, cx| {
210 if matches!(event, InputEvent::Blur) {
211 this.commit_agent(cx);
212 this.refresh_models(cx);
213 }
214 }));
215 }
216
171 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
217 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
172 let Some(action) = self
218 let Some(action) = self
173 .runs
219 .runs
@@ -213,6 +259,9 @@ impl AgentsSettings {
213 let command = form.command.read(cx).value().to_string();
259 let command = form.command.read(cx).value().to_string();
214 let open_session = form.open_session.read(cx).value().to_string();
260 let open_session = form.open_session.read(cx).value().to_string();
215 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
261 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
262 let base_url = form.base_url.read(cx).value().trim().to_owned();
263 let model = form.model.read(cx).value().trim().to_owned();
264 let typed_key = form.api_key.read(cx).value().trim().to_owned();
216 self.runs.update(cx, |runs, cx| {
265 self.runs.update(cx, |runs, cx| {
217 runs.update_settings(
266 runs.update_settings(
218 |settings| {
267 |settings| {
@@ -221,20 +270,96 @@ impl AgentsSettings {
221 return;
270 return;
222 };
271 };
223 agent.name = name;
272 agent.name = name;
224 agent.command = command;
273 if agent.is_chat() {
225 agent.open_session_command = open_session;
274 match &mut agent.backend {
226 agent.mcp_config_flag = mcp_flag;
275 AgentBackend::OpenAi {
227 if let Environment::Wsl {
276 base_url: url,
228 distro: Some(current),
277 model: current,
229 } = &mut agent.environment
278 api_key,
230 {
279 } => {
231 *current = distro;
280 *url = base_url;
281 *current = model;
282 if !typed_key.is_empty() {
283 *api_key = typed_key;
284 }
285 }
286 AgentBackend::Anthropic {
287 model: current,
288 api_key,
289 } => {
290 *current = model;
291 if !typed_key.is_empty() {
292 *api_key = typed_key;
293 }
294 }
295 AgentBackend::Command => {}
296 }
297 } else {
298 agent.command = command;
299 agent.open_session_command = open_session;
300 agent.mcp_config_flag = mcp_flag;
301 if let Environment::Wsl {
302 distro: Some(current),
303 } = &mut agent.environment
304 {
305 *current = distro;
306 }
232 }
307 }
233 },
308 },
234 cx,
309 cx,
235 )
310 )
236 });
311 });
237 self.probe = Probe::Idle;
312 }
313
314 pub(super) fn set_model(&mut self, model: String, window: &mut Window, cx: &mut Context<Self>) {
315 let Some(form) = &self.agent_form else {
316 return;
317 };
318 form.model
319 .update(cx, |input, cx| input.set_value(model, window, cx));
320 self.commit_agent(cx);
321 }
322
323 pub(super) fn refresh_models(&mut self, cx: &mut Context<Self>) {
324 let Some(profile) = self.current_agent(cx) else {
325 return;
326 };
327 if !profile.is_chat() {
328 return;
329 }
330 self.models_request += 1;
331 let ticket = self.models_request;
332 self.probe = Probe::Running;
333 cx.notify();
334 let receiver = runtime::spawn(async move { agents::list_models(&profile).await });
335 cx.spawn(async move |this, cx| {
336 let result = receiver
337 .await
338 .unwrap_or_else(|_| Err("cancelled".to_owned()));
339 this.update(cx, |this, cx| {
340 if this.models_request != ticket {
341 return;
342 }
343 match result {
344 Ok(names) => {
345 let count = names.len();
346 this.models = names;
347 this.probe = Probe::Found(if count == 1 {
348 "1 model".to_owned()
349 } else {
350 format!("{count} models")
351 });
352 }
353 Err(error) => {
354 this.models.clear();
355 this.probe = Probe::Missing(error);
356 }
357 }
358 cx.notify();
359 })
360 .ok();
361 })
362 .detach();
238 }
363 }
239
364
240 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
365 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
@@ -319,6 +444,18 @@ impl AgentsSettings {
319 self.update_action(cx, move |action| action.agent_id = agent_id);
444 self.update_action(cx, move |action| action.agent_id = agent_id);
320 }
445 }
321
446
447 pub(super) fn set_write_with(&mut self, agent_id: String, cx: &mut Context<Self>) {
448 self.runs.update(cx, |runs, cx| {
449 runs.update_settings(|settings| settings.write_with = agent_id, cx)
450 });
451 }
452
453 pub(super) fn rescan(&mut self, cx: &mut Context<Self>) {
454 self.found = agents::scan_clis();
455 self.scanned = true;
456 cx.notify();
457 }
458
322 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
459 pub(super) fn set_resume_interrupted_runs(&mut self, resume: bool, cx: &mut Context<Self>) {
323 self.runs.update(cx, |runs, cx| {
460 self.runs.update(cx, |runs, cx| {
324 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
461 runs.update_settings(|settings| settings.resume_interrupted_runs = resume, cx)
@@ -393,6 +530,10 @@ impl AgentsSettings {
393 let Some(profile) = self.current_agent(cx) else {
530 let Some(profile) = self.current_agent(cx) else {
394 return;
531 return;
395 };
532 };
533 if profile.is_chat() {
534 self.refresh_models(cx);
535 return;
536 }
396 if profile.command.trim().is_empty() {
537 if profile.command.trim().is_empty() {
397 self.probe = Probe::Missing("The command is empty".to_owned());
538 self.probe = Probe::Missing("The command is empty".to_owned());
398 cx.notify();
539 cx.notify();
@@ -443,8 +584,30 @@ impl AgentsSettings {
443 existing.iter().any(|id| id == candidate)
584 existing.iter().any(|id| id == candidate)
444 });
585 });
445 let id = profile.id.clone();
586 let id = profile.id.clone();
587 let chat = profile.is_chat();
588 let mut action = AgentAction::answer_this(&id);
589 action.extra_args.clear();
590 let mut args = std::collections::HashMap::new();
591 args.insert("name".to_owned(), profile.name.clone());
592 action.label = tr_args("agents.settings.answer_with", &args);
593 action.id = unique_id(&format!("answer-{id}"), |candidate| {
594 self.runs
595 .read(cx)
596 .settings()
597 .actions
598 .iter()
599 .any(|action| action.id == candidate)
600 });
446 self.runs.update(cx, |runs, cx| {
601 self.runs.update(cx, |runs, cx| {
447 runs.update_settings(|settings| settings.agents.push(profile), cx)
602 runs.update_settings(
603 |settings| {
604 settings.agents.push(profile);
605 if chat {
606 settings.actions.push(action);
607 }
608 },
609 cx,
610 )
448 });
611 });
449 self.open_agent(&id, window, cx);
612 self.open_agent(&id, window, cx);
450 }
613 }
@@ -457,7 +620,7 @@ impl AgentsSettings {
457 .map(|agent| agent.id.clone())
620 .map(|agent| agent.id.clone())
458 .unwrap_or_default();
621 .unwrap_or_default();
459 let mut action = AgentAction::answer_this(&agent_id);
622 let mut action = AgentAction::answer_this(&agent_id);
460 action.label = "New action".to_owned();
623 action.label = tr("agents.settings.new_action");
461 action.id = unique_id("action", |candidate| {
624 action.id = unique_id("action", |candidate| {
462 settings.actions.iter().any(|action| action.id == candidate)
625 settings.actions.iter().any(|action| action.id == candidate)
463 });
626 });
@@ -482,26 +645,83 @@ impl AgentsSettings {
482
645
483type Preset = (&'static str, fn() -> AgentProfile);
646type Preset = (&'static str, fn() -> AgentProfile);
484
647
485fn agent_presets() -> [Preset; 4] {
648fn agent_presets() -> [Preset; 9] {
486 fn custom() -> AgentProfile {
649 fn custom() -> AgentProfile {
487 AgentProfile {
650 AgentProfile {
488 id: "custom".to_owned(),
651 id: "custom".to_owned(),
489 name: "Custom agent".to_owned(),
652 name: tr("agents.settings.custom_agent"),
490 environment: Environment::Host,
653 environment: Environment::Host,
491 command: String::new(),
492 output: OutputFormat::Text,
654 output: OutputFormat::Text,
493 open_session_command: String::new(),
655 ..AgentProfile::default()
494 mcp_config_flag: String::new(),
495 }
656 }
496 }
657 }
497 [
658 [
498 ("Claude Code (WSL)", AgentProfile::claude_wsl),
659 (
660 "Claude Code (WSL)",
661 AgentProfile::claude_wsl as fn() -> AgentProfile,
662 ),
499 ("Claude Code (Windows)", AgentProfile::claude_host),
663 ("Claude Code (Windows)", AgentProfile::claude_host),
500 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
664 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
665 ("Ollama", AgentProfile::ollama),
666 ("OpenAI", AgentProfile::openai),
667 ("OpenRouter", AgentProfile::openrouter),
668 ("Anthropic", AgentProfile::anthropic),
669 ("OpenAI-compatible", AgentProfile::openai_compatible),
501 ("Custom", custom),
670 ("Custom", custom),
502 ]
671 ]
503}
672}
504
673
674fn write_with_label(settings: &agents::AgentSettings) -> String {
675 if settings.write_with.is_empty() {
676 return "Microsoft Copilot".to_owned();
677 }
678 settings
679 .agents
680 .iter()
681 .find(|agent| agent.id == settings.write_with && agent.is_chat())
682 .map(|agent| agent.name.clone())
683 .unwrap_or_else(|| "Microsoft Copilot".to_owned())
684}
685
686fn write_with_entries(
687 settings: &agents::AgentSettings,
688 this: &Entity<AgentsSettings>,
689) -> Vec<MenuEntry> {
690 let mut entries = vec![write_with_entry(
691 this,
692 "Microsoft Copilot",
693 "",
694 settings.write_with.is_empty(),
695 )];
696 for agent in settings.agents.iter().filter(|agent| agent.is_chat()) {
697 entries.push(write_with_entry(
698 this,
699 &agent.name,
700 &agent.id,
701 settings.write_with == agent.id,
702 ));
703 }
704 entries
705}
706
707fn write_with_entry(
708 this: &Entity<AgentsSettings>,
709 label: &str,
710 agent_id: &str,
711 selected: bool,
712) -> MenuEntry {
713 let (this, agent_id) = (this.clone(), agent_id.to_owned());
714 let choose: Choice = std::rc::Rc::new(move |_, cx| {
715 let agent_id = agent_id.clone();
716 this.update(cx, |this, cx| this.set_write_with(agent_id, cx))
717 });
718 MenuEntry {
719 label: label.to_owned(),
720 selected,
721 choose,
722 }
723}
724
505fn list_row(
725fn list_row(
506 id: (&'static str, usize),
726 id: (&'static str, usize),
507 leading: Option<AnyElement>,
727 leading: Option<AnyElement>,
@@ -568,7 +788,17 @@ fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Sta
568
788
569impl AgentsSettings {
789impl AgentsSettings {
570 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
790 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
791 if !self.scanned {
792 self.found = agents::scan_clis();
793 self.scanned = true;
794 }
571 let settings = self.runs.read(cx).settings().clone();
795 let settings = self.runs.read(cx).settings().clone();
796 let found: Vec<agents::CliHit> = self
797 .found
798 .iter()
799 .filter(|hit| !agents::already_installed(&settings.agents, &hit.profile))
800 .cloned()
801 .collect();
572 let this = cx.entity();
802 let this = cx.entity();
573 let preset_entries: Vec<MenuEntry> = agent_presets()
803 let preset_entries: Vec<MenuEntry> = agent_presets()
574 .into_iter()
804 .into_iter()
@@ -611,8 +841,12 @@ impl AgentsSettings {
611 .into_any_element(),
841 .into_any_element(),
612 ),
842 ),
613 agent.name.clone(),
843 agent.name.clone(),
614 environment_label(&agent.environment),
844 if agent.is_chat() {
615 Some(agent.command.clone()),
845 agent.backend_label()
846 } else {
847 environment_label(&agent.environment)
848 },
849 agent.is_command().then(|| agent.command.clone()),
616 )
850 )
617 .on_click(move |_, window, cx| {
851 .on_click(move |_, window, cx| {
618 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
852 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
@@ -625,7 +859,8 @@ impl AgentsSettings {
625 .agents
859 .agents
626 .iter()
860 .iter()
627 .find(|agent| agent.id == action.agent_id)
861 .find(|agent| agent.id == action.agent_id)
628 .map_or("Unknown agent", |agent| agent.name.as_str());
862 .map(|agent| agent.name.clone())
863 .unwrap_or_else(|| tr("agents.settings.unknown_agent"));
629 list_row(
864 list_row(
630 ("action-row", index),
865 ("action-row", index),
631 None,
866 None,
@@ -660,18 +895,91 @@ impl AgentsSettings {
660 ),
895 ),
661 )
896 )
662 });
897 });
898 let write_entries = write_with_entries(&settings, &this);
899 let write_label = write_with_label(&settings);
900 let rescan = this.clone();
901 let found_rows = found.iter().enumerate().map(|(index, hit)| {
902 let (this, profile) = (this.clone(), hit.profile.clone());
903 list_row(
904 ("found-cli", index),
905 None,
906 hit.profile.name.clone(),
907 hit.binary.display().to_string(),
908 Some(hit.profile.command.clone()),
909 )
910 .child(
911 Button::new(("add-found", index))
912 .link()
913 .label(tr("common.add"))
914 .on_click(move |_, window, cx| {
915 let profile = profile.clone();
916 this.update(cx, |this, cx| this.add_agent(profile, window, cx))
917 }),
918 )
919 });
920 let on_computer = tr("agents.settings.on_this_computer");
921 let agents_header = tr("agents.settings.agents_header");
922 let actions_header = tr("agents.settings.actions_header");
663 v_flex()
923 v_flex()
664 .w_full()
924 .w_full()
665 .child(section_header(
925 .child(section_header(
666 "AGENTS",
926 on_computer.clone(),
927 Some(
928 Button::new("rescan-clis")
929 .link()
930 .label(tr("agents.settings.scan_again"))
931 .on_click(move |_, _, cx| {
932 rescan.update(cx, |this, cx| this.rescan(cx))
933 })
934 .into_any_element(),
935 ),
936 ))
937 .child(
938 v_flex()
939 .w_full()
940 .px(px(8.))
941 .children(found_rows)
942 .when(found.is_empty(), |rows| {
943 rows.child(
944 div()
945 .px(px(12.))
946 .py(px(8.))
947 .text_size(px(12.))
948 .text_color(theme::text_muted())
949 .child(tr("agents.settings.no_cli_found")),
950 )
951 }),
952 )
953 .child(section_header(
954 agents_header.clone(),
667 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
955 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
668 ))
956 ))
669 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
957 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
670 .child(section_header(
958 .child(section_header(
671 "ACTIONS - IN THIS ORDER IN THE MENU",
959 actions_header,
672 Some(add_action.into_any_element()),
960 Some(add_action.into_any_element()),
673 ))
961 ))
674 .child(v_flex().w_full().px(px(8.)).children(action_rows))
962 .child(v_flex().w_full().px(px(8.)).children(action_rows))
963 .child(
964 v_flex()
965 .w_full()
966 .px(px(PAGE_PADDING))
967 .pt(px(16.))
968 .gap(px(6.))
969 .child(
970 div()
971 .text_size(px(14.))
972 .font_weight(FontWeight::SEMIBOLD)
973 .child(tr("agents.settings.write_with")),
974 )
975 .child(
976 div()
977 .text_size(px(12.))
978 .text_color(theme::text_muted())
979 .child(tr("agents.settings.rewrite_hint")),
980 )
981 .child(dropdown("write-with", write_label, write_entries)),
982 )
675 .child(resume_toggle(settings.resume_interrupted_runs, this))
983 .child(resume_toggle(settings.resume_interrupted_runs, this))
676 .child(
984 .child(
677 div()
985 div()
@@ -682,7 +990,7 @@ impl AgentsSettings {
682 .text_size(px(12.))
990 .text_size(px(12.))
683 .line_height(relative(1.5))
991 .line_height(relative(1.5))
684 .text_color(theme::text_faint())
992 .text_color(theme::text_faint())
685 .child(NOTE),
993 .child(tr("agents.settings.note")),
686 )
994 )
687 }
995 }
688}
996}
crates/app/src/agents/start_dialog.rs +26 −20
@@ -20,6 +20,7 @@ use super::{
20 20 mcp_bridge, message_context, raise_notice, runs_handle, start_run, start_run_when_mcp_ready,
21 21 };
22 22 use crate::app_state::AppState;
23 use crate::i18n::tr;
23 24 use crate::theme::{self, ElevatedSurface as _};
24 25 use crate::views::widgets::{icon, symbol};
25 26
@@ -37,7 +38,6 @@ const FIELD_MAX_ROWS: usize = 6;
37 38 const PROMPT_SIZE: f32 = 12.;
38 39 const DISABLED_OPACITY: f32 = 0.5;
39 40 const DEFAULT_PLACEHOLDER: &str = "e.g. only the backend, open a PR when done";
40 const SESSION_PLACEHOLDER: &str = "Type the message to send";
41 41
42 42 pub enum StartDialogEvent {
43 43 Close,
@@ -58,6 +58,7 @@ pub struct StartDialog {
58 58 working_dir: String,
59 59 recent_working_dirs: Vec<String>,
60 60 offers_sessions: bool,
61 asks_for_directory: bool,
61 62 scans_external: bool,
62 63 run_sessions: Vec<SessionOption>,
63 64 external_sessions: Vec<SessionOption>,
@@ -108,6 +109,7 @@ impl StartDialog {
108 109 })
109 110 .unwrap_or_default();
110 111 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
112 let asks_for_directory = profile.as_ref().is_none_or(|profile| profile.is_command());
111 113 let run_sessions = match runs {
112 114 Some(runs) if offers_sessions => {
113 115 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
@@ -131,6 +133,7 @@ impl StartDialog {
131 133 working_dir: action.working_dir.clone(),
132 134 recent_working_dirs,
133 135 offers_sessions,
136 asks_for_directory,
134 137 scans_external: profile
135 138 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
136 139 && offers_sessions,
@@ -180,9 +183,9 @@ impl StartDialog {
180 183 cx: &mut Context<Self>,
181 184 ) {
182 185 let placeholder = if session.is_some() {
183 SESSION_PLACEHOLDER
186 tr("agents.start.message_placeholder")
184 187 } else {
185 DEFAULT_PLACEHOLDER
188 DEFAULT_PLACEHOLDER.to_owned()
186 189 };
187 190 self.input.update(cx, |input, cx| {
188 191 input.set_placeholder(placeholder, window, cx)
@@ -361,7 +364,8 @@ impl StartDialog {
361 364 .text_size(px(12.))
362 365 .line_height(relative(1.4))
363 366 .text_color(theme::text_soft())
364 .line_clamp(QUOTE_LINES).text_ellipsis()
367 .line_clamp(QUOTE_LINES)
368 .text_ellipsis()
365 369 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
366 370 }
367 371
@@ -387,7 +391,7 @@ impl StartDialog {
387 391 };
388 392 let new_dialog = dialog.clone();
389 393 let mut parts = vec![MenuPart::Row(MenuRow {
390 label: "New session".to_owned(),
394 label: tr("agents.start.new_session"),
391 395 meta: None,
392 396 running: false,
393 397 selected: self.selected_session.is_none(),
@@ -397,12 +401,12 @@ impl StartDialog {
397 401 })];
398 402 if !self.run_sessions.is_empty() {
399 403 parts.push(MenuPart::Separator);
400 parts.push(MenuPart::Header("Recent sessions".to_owned()));
404 parts.push(MenuPart::Header(tr("agents.start.recent_sessions")));
401 405 parts.extend(self.run_sessions.iter().map(row));
402 406 }
403 407 if !self.external_sessions.is_empty() {
404 408 parts.push(MenuPart::Separator);
405 parts.push(MenuPart::Header("Other sessions".to_owned()));
409 parts.push(MenuPart::Header(tr("agents.start.other_sessions")));
406 410 parts.extend(self.external_sessions.iter().map(row));
407 411 }
408 412 parts
@@ -425,7 +429,7 @@ impl StartDialog {
425 429 };
426 430 let browse_dialog = dialog.clone();
427 431 let mut parts = vec![
428 MenuPart::Header("Recent".to_owned()),
432 MenuPart::Header(tr("agents.start.recent")),
429 433 row(&self.default_working_dir, Some("action default")),
430 434 ];
431 435 parts.extend(
@@ -436,7 +440,7 @@ impl StartDialog {
436 440 );
437 441 parts.push(MenuPart::Separator);
438 442 parts.push(MenuPart::Row(MenuRow {
439 label: "Browse...".to_owned(),
443 label: tr("agents.start.browse"),
440 444 meta: None,
441 445 running: false,
442 446 selected: false,
@@ -456,10 +460,10 @@ impl StartDialog {
456 460 Some(session.meta.clone()),
457 461 session.running,
458 462 ),
459 None => ("New session".to_owned(), None, false),
463 None => (tr("agents.start.new_session"), None, false),
460 464 };
461 465 picker_row(
462 "Session",
466 tr("agents.start.session"),
463 467 select(
464 468 "agent-dialog-session",
465 469 value,
@@ -486,7 +490,9 @@ impl StartDialog {
486 490 .w_full()
487 491 .gap(px(8.))
488 492 .children(session_row)
489 .child(picker_row("Working dir", working_dir_control))
493 .when(self.asks_for_directory, |rows| {
494 rows.child(picker_row(tr("agents.start.working_dir"), working_dir_control))
495 })
490 496 }
491 497
492 498 fn field(&self, window: &Window, cx: &App) -> Div {
@@ -500,9 +506,9 @@ impl StartDialog {
500 506 .font_weight(FontWeight::SEMIBOLD)
501 507 .text_color(theme::text_faint())
502 508 .child(if self.selected_session.is_some() {
503 "Message to the session"
509 tr("agents.start.message_to_session")
504 510 } else {
505 "Extra instructions (optional)"
511 tr("agents.start.extra_instructions")
506 512 }),
507 513 )
508 514 .child(
@@ -540,7 +546,7 @@ impl StartDialog {
540 546 12.,
541 547 theme::text_muted(),
542 548 ))
543 .child("Show prompt")
549 .child(tr("agents.start.show_prompt"))
544 550 .on_click(cx.listener(|this, _, _, cx| {
545 551 this.show_prompt = !this.show_prompt;
546 552 cx.notify();
@@ -580,11 +586,11 @@ impl StartDialog {
580 586 let blocked =
581 587 self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();
582 588 let start_label = if self.selected_session.is_some() {
583 "Send"
589 tr("agents.start.send")
584 590 } else if self.needs_allow {
585 "Allow and start"
591 tr("agents.start.allow_and_start")
586 592 } else {
587 "Start"
593 tr("agents.start.start")
588 594 };
589 595 h_flex()
590 596 .w_full()
@@ -603,7 +609,7 @@ impl StartDialog {
603 609 .bg(theme::surface_raised())
604 610 .hover(|button| button.bg(theme::popup_hover()))
605 611 .text_size(px(13.))
606 .child("Cancel")
612 .child(tr("common.cancel"))
607 613 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
608 614 )
609 615 .child(
@@ -672,7 +678,7 @@ impl Render for StartDialog {
672 678 div()
673 679 .text_size(px(12.))
674 680 .text_color(theme::text_soft())
675 .child("Agents can't see this chat yet."),
681 .child(tr("agents.start.chat_invisible")),
676 682 )
677 683 })
678 684 .child(self.pickers(cx))
@@ -20,6 +20,7 @@ use super::{
20 mcp_bridge, message_context, raise_notice, runs_handle, start_run, start_run_when_mcp_ready,
20 mcp_bridge, message_context, raise_notice, runs_handle, start_run, start_run_when_mcp_ready,
21};
21};
22use crate::app_state::AppState;
22use crate::app_state::AppState;
23use crate::i18n::tr;
23use crate::theme::{self, ElevatedSurface as _};
24use crate::theme::{self, ElevatedSurface as _};
24use crate::views::widgets::{icon, symbol};
25use crate::views::widgets::{icon, symbol};
25
26
@@ -37,7 +38,6 @@ const FIELD_MAX_ROWS: usize = 6;
37const PROMPT_SIZE: f32 = 12.;
38const PROMPT_SIZE: f32 = 12.;
38const DISABLED_OPACITY: f32 = 0.5;
39const DISABLED_OPACITY: f32 = 0.5;
39const DEFAULT_PLACEHOLDER: &str = "e.g. only the backend, open a PR when done";
40const DEFAULT_PLACEHOLDER: &str = "e.g. only the backend, open a PR when done";
40const SESSION_PLACEHOLDER: &str = "Type the message to send";
41
41
42pub enum StartDialogEvent {
42pub enum StartDialogEvent {
43 Close,
43 Close,
@@ -58,6 +58,7 @@ pub struct StartDialog {
58 working_dir: String,
58 working_dir: String,
59 recent_working_dirs: Vec<String>,
59 recent_working_dirs: Vec<String>,
60 offers_sessions: bool,
60 offers_sessions: bool,
61 asks_for_directory: bool,
61 scans_external: bool,
62 scans_external: bool,
62 run_sessions: Vec<SessionOption>,
63 run_sessions: Vec<SessionOption>,
63 external_sessions: Vec<SessionOption>,
64 external_sessions: Vec<SessionOption>,
@@ -108,6 +109,7 @@ impl StartDialog {
108 })
109 })
109 .unwrap_or_default();
110 .unwrap_or_default();
110 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
111 let offers_sessions = profile.as_ref().is_some_and(agents::supports_resume);
112 let asks_for_directory = profile.as_ref().is_none_or(|profile| profile.is_command());
111 let run_sessions = match runs {
113 let run_sessions = match runs {
112 Some(runs) if offers_sessions => {
114 Some(runs) if offers_sessions => {
113 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
115 run_options(&runs.for_agent(&action.agent_id), app.read(cx), Utc::now())
@@ -131,6 +133,7 @@ impl StartDialog {
131 working_dir: action.working_dir.clone(),
133 working_dir: action.working_dir.clone(),
132 recent_working_dirs,
134 recent_working_dirs,
133 offers_sessions,
135 offers_sessions,
136 asks_for_directory,
134 scans_external: profile
137 scans_external: profile
135 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
138 .is_some_and(|profile| profile.output == agents::OutputFormat::ClaudeStreamJson)
136 && offers_sessions,
139 && offers_sessions,
@@ -180,9 +183,9 @@ impl StartDialog {
180 cx: &mut Context<Self>,
183 cx: &mut Context<Self>,
181 ) {
184 ) {
182 let placeholder = if session.is_some() {
185 let placeholder = if session.is_some() {
183 SESSION_PLACEHOLDER
186 tr("agents.start.message_placeholder")
184 } else {
187 } else {
185 DEFAULT_PLACEHOLDER
188 DEFAULT_PLACEHOLDER.to_owned()
186 };
189 };
187 self.input.update(cx, |input, cx| {
190 self.input.update(cx, |input, cx| {
188 input.set_placeholder(placeholder, window, cx)
191 input.set_placeholder(placeholder, window, cx)
@@ -361,7 +364,8 @@ impl StartDialog {
361 .text_size(px(12.))
364 .text_size(px(12.))
362 .line_height(relative(1.4))
365 .line_height(relative(1.4))
363 .text_color(theme::text_soft())
366 .text_color(theme::text_soft())
364 .line_clamp(QUOTE_LINES).text_ellipsis()
367 .line_clamp(QUOTE_LINES)
368 .text_ellipsis()
365 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
369 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
366 }
370 }
367
371
@@ -387,7 +391,7 @@ impl StartDialog {
387 };
391 };
388 let new_dialog = dialog.clone();
392 let new_dialog = dialog.clone();
389 let mut parts = vec![MenuPart::Row(MenuRow {
393 let mut parts = vec![MenuPart::Row(MenuRow {
390 label: "New session".to_owned(),
394 label: tr("agents.start.new_session"),
391 meta: None,
395 meta: None,
392 running: false,
396 running: false,
393 selected: self.selected_session.is_none(),
397 selected: self.selected_session.is_none(),
@@ -397,12 +401,12 @@ impl StartDialog {
397 })];
401 })];
398 if !self.run_sessions.is_empty() {
402 if !self.run_sessions.is_empty() {
399 parts.push(MenuPart::Separator);
403 parts.push(MenuPart::Separator);
400 parts.push(MenuPart::Header("Recent sessions".to_owned()));
404 parts.push(MenuPart::Header(tr("agents.start.recent_sessions")));
401 parts.extend(self.run_sessions.iter().map(row));
405 parts.extend(self.run_sessions.iter().map(row));
402 }
406 }
403 if !self.external_sessions.is_empty() {
407 if !self.external_sessions.is_empty() {
404 parts.push(MenuPart::Separator);
408 parts.push(MenuPart::Separator);
405 parts.push(MenuPart::Header("Other sessions".to_owned()));
409 parts.push(MenuPart::Header(tr("agents.start.other_sessions")));
406 parts.extend(self.external_sessions.iter().map(row));
410 parts.extend(self.external_sessions.iter().map(row));
407 }
411 }
408 parts
412 parts
@@ -425,7 +429,7 @@ impl StartDialog {
425 };
429 };
426 let browse_dialog = dialog.clone();
430 let browse_dialog = dialog.clone();
427 let mut parts = vec![
431 let mut parts = vec![
428 MenuPart::Header("Recent".to_owned()),
432 MenuPart::Header(tr("agents.start.recent")),
429 row(&self.default_working_dir, Some("action default")),
433 row(&self.default_working_dir, Some("action default")),
430 ];
434 ];
431 parts.extend(
435 parts.extend(
@@ -436,7 +440,7 @@ impl StartDialog {
436 );
440 );
437 parts.push(MenuPart::Separator);
441 parts.push(MenuPart::Separator);
438 parts.push(MenuPart::Row(MenuRow {
442 parts.push(MenuPart::Row(MenuRow {
439 label: "Browse...".to_owned(),
443 label: tr("agents.start.browse"),
440 meta: None,
444 meta: None,
441 running: false,
445 running: false,
442 selected: false,
446 selected: false,
@@ -456,10 +460,10 @@ impl StartDialog {
456 Some(session.meta.clone()),
460 Some(session.meta.clone()),
457 session.running,
461 session.running,
458 ),
462 ),
459 None => ("New session".to_owned(), None, false),
463 None => (tr("agents.start.new_session"), None, false),
460 };
464 };
461 picker_row(
465 picker_row(
462 "Session",
466 tr("agents.start.session"),
463 select(
467 select(
464 "agent-dialog-session",
468 "agent-dialog-session",
465 value,
469 value,
@@ -486,7 +490,9 @@ impl StartDialog {
486 .w_full()
490 .w_full()
487 .gap(px(8.))
491 .gap(px(8.))
488 .children(session_row)
492 .children(session_row)
489 .child(picker_row("Working dir", working_dir_control))
493 .when(self.asks_for_directory, |rows| {
494 rows.child(picker_row(tr("agents.start.working_dir"), working_dir_control))
495 })
490 }
496 }
491
497
492 fn field(&self, window: &Window, cx: &App) -> Div {
498 fn field(&self, window: &Window, cx: &App) -> Div {
@@ -500,9 +506,9 @@ impl StartDialog {
500 .font_weight(FontWeight::SEMIBOLD)
506 .font_weight(FontWeight::SEMIBOLD)
501 .text_color(theme::text_faint())
507 .text_color(theme::text_faint())
502 .child(if self.selected_session.is_some() {
508 .child(if self.selected_session.is_some() {
503 "Message to the session"
509 tr("agents.start.message_to_session")
504 } else {
510 } else {
505 "Extra instructions (optional)"
511 tr("agents.start.extra_instructions")
506 }),
512 }),
507 )
513 )
508 .child(
514 .child(
@@ -540,7 +546,7 @@ impl StartDialog {
540 12.,
546 12.,
541 theme::text_muted(),
547 theme::text_muted(),
542 ))
548 ))
543 .child("Show prompt")
549 .child(tr("agents.start.show_prompt"))
544 .on_click(cx.listener(|this, _, _, cx| {
550 .on_click(cx.listener(|this, _, _, cx| {
545 this.show_prompt = !this.show_prompt;
551 this.show_prompt = !this.show_prompt;
546 cx.notify();
552 cx.notify();
@@ -580,11 +586,11 @@ impl StartDialog {
580 let blocked =
586 let blocked =
581 self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();
587 self.selected_session.is_some() && self.input.read(cx).value().trim().is_empty();
582 let start_label = if self.selected_session.is_some() {
588 let start_label = if self.selected_session.is_some() {
583 "Send"
589 tr("agents.start.send")
584 } else if self.needs_allow {
590 } else if self.needs_allow {
585 "Allow and start"
591 tr("agents.start.allow_and_start")
586 } else {
592 } else {
587 "Start"
593 tr("agents.start.start")
588 };
594 };
589 h_flex()
595 h_flex()
590 .w_full()
596 .w_full()
@@ -603,7 +609,7 @@ impl StartDialog {
603 .bg(theme::surface_raised())
609 .bg(theme::surface_raised())
604 .hover(|button| button.bg(theme::popup_hover()))
610 .hover(|button| button.bg(theme::popup_hover()))
605 .text_size(px(13.))
611 .text_size(px(13.))
606 .child("Cancel")
612 .child(tr("common.cancel"))
607 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
613 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
608 )
614 )
609 .child(
615 .child(
@@ -672,7 +678,7 @@ impl Render for StartDialog {
672 div()
678 div()
673 .text_size(px(12.))
679 .text_size(px(12.))
674 .text_color(theme::text_soft())
680 .text_color(theme::text_soft())
675 .child("Agents can't see this chat yet."),
681 .child(tr("agents.start.chat_invisible")),
676 )
682 )
677 })
683 })
678 .child(self.pickers(cx))
684 .child(self.pickers(cx))
crates/app/src/agents/start_dialog_pickers.rs +1 −1
@@ -34,7 +34,7 @@ pub enum MenuPart {
34 34 Row(MenuRow),
35 35 }
36 36
37 pub fn picker_row(label: &'static str, control: impl IntoElement) -> Div {
37 pub fn picker_row(label: String, control: impl IntoElement) -> Div {
38 38 h_flex()
39 39 .w_full()
40 40 .items_center()
@@ -34,7 +34,7 @@ pub enum MenuPart {
34 Row(MenuRow),
34 Row(MenuRow),
35}
35}
36
36
37pub fn picker_row(label: &'static str, control: impl IntoElement) -> Div {
37pub fn picker_row(label: String, control: impl IntoElement) -> Div {
38 h_flex()
38 h_flex()
39 .w_full()
39 .w_full()
40 .items_center()
40 .items_center()
crates/app/src/i18n.rs added +67 −0
@@ -0,0 +1,67 @@
1 pub use app_base::ui_locale::{tr, tr_args};
2
3 #[cfg(test)]
4 mod tests {
5 use std::sync::{Mutex, MutexGuard};
6
7 use app_base::ui_locale::{apply_locale, tr};
8
9 fn locale_test_lock() -> MutexGuard<'static, ()> {
10 static LOCK: Mutex<()> = Mutex::new(());
11 LOCK.lock().unwrap_or_else(|error| error.into_inner())
12 }
13
14 #[test]
15 fn ui_locale_settings_common_actions() {
16 let _guard = locale_test_lock();
17 apply_locale("de");
18 assert_eq!(tr("common.cancel"), "Abbrechen");
19 apply_locale("en");
20 assert_eq!(tr("settings.nav.general"), "General");
21 }
22
23 #[test]
24 fn ui_locale_chrome_rail_and_nav_keys() {
25 let _guard = locale_test_lock();
26 apply_locale("en");
27 assert_eq!(tr("rail.activity"), "Activity");
28 assert_eq!(tr("rail.chat"), "Chat");
29 assert_eq!(tr("settings.nav.notifications"), "Notifications and activity");
30 apply_locale("de");
31 assert_eq!(tr("rail.calendar"), "Kalender");
32 assert_eq!(tr("common.save"), "Speichern");
33 }
34
35 #[test]
36 fn ui_locale_calls_page_keys_resolve_in_de() {
37 let _guard = locale_test_lock();
38 apply_locale("de");
39 assert_eq!(tr("calls.page.title"), "Anrufe");
40 assert_eq!(tr("auth.sign_in"), "Anmelden");
41 }
42
43 #[test]
44 fn ui_locale_chat_sidebar_and_filters_in_de() {
45 let _guard = locale_test_lock();
46 apply_locale("de");
47 assert_eq!(tr("sidebar.pinned"), "Angepinnt");
48 assert_eq!(tr("sidebar.filter.no_matches"), "Keine Treffer gefunden.");
49 assert_eq!(tr("sidebar.pill.meetings"), "Besprechungschats");
50 }
51
52 #[test]
53 fn ui_locale_call_chrome_in_de() {
54 let _guard = locale_test_lock();
55 apply_locale("de");
56 assert_eq!(tr("calls.chrome.stop_sharing"), "Freigabe beenden");
57 assert_eq!(tr("calls.prejoin.join_now"), "Jetzt beitreten");
58 }
59
60 #[test]
61 fn ui_locale_calendar_meeting_dialog_in_de() {
62 let _guard = locale_test_lock();
63 apply_locale("de");
64 assert_eq!(tr("calls.meeting.new_title"), "Neue Besprechung");
65 assert_eq!(tr("calls.meeting.teams_link_added"), "Teams-Besprechungslink wird hinzugefügt");
66 }
67 }
@@ -0,0 +1,67 @@
1pub use app_base::ui_locale::{tr, tr_args};
2
3#[cfg(test)]
4mod tests {
5 use std::sync::{Mutex, MutexGuard};
6
7 use app_base::ui_locale::{apply_locale, tr};
8
9 fn locale_test_lock() -> MutexGuard<'static, ()> {
10 static LOCK: Mutex<()> = Mutex::new(());
11 LOCK.lock().unwrap_or_else(|error| error.into_inner())
12 }
13
14 #[test]
15 fn ui_locale_settings_common_actions() {
16 let _guard = locale_test_lock();
17 apply_locale("de");
18 assert_eq!(tr("common.cancel"), "Abbrechen");
19 apply_locale("en");
20 assert_eq!(tr("settings.nav.general"), "General");
21 }
22
23 #[test]
24 fn ui_locale_chrome_rail_and_nav_keys() {
25 let _guard = locale_test_lock();
26 apply_locale("en");
27 assert_eq!(tr("rail.activity"), "Activity");
28 assert_eq!(tr("rail.chat"), "Chat");
29 assert_eq!(tr("settings.nav.notifications"), "Notifications and activity");
30 apply_locale("de");
31 assert_eq!(tr("rail.calendar"), "Kalender");
32 assert_eq!(tr("common.save"), "Speichern");
33 }
34
35 #[test]
36 fn ui_locale_calls_page_keys_resolve_in_de() {
37 let _guard = locale_test_lock();
38 apply_locale("de");
39 assert_eq!(tr("calls.page.title"), "Anrufe");
40 assert_eq!(tr("auth.sign_in"), "Anmelden");
41 }
42
43 #[test]
44 fn ui_locale_chat_sidebar_and_filters_in_de() {
45 let _guard = locale_test_lock();
46 apply_locale("de");
47 assert_eq!(tr("sidebar.pinned"), "Angepinnt");
48 assert_eq!(tr("sidebar.filter.no_matches"), "Keine Treffer gefunden.");
49 assert_eq!(tr("sidebar.pill.meetings"), "Besprechungschats");
50 }
51
52 #[test]
53 fn ui_locale_call_chrome_in_de() {
54 let _guard = locale_test_lock();
55 apply_locale("de");
56 assert_eq!(tr("calls.chrome.stop_sharing"), "Freigabe beenden");
57 assert_eq!(tr("calls.prejoin.join_now"), "Jetzt beitreten");
58 }
59
60 #[test]
61 fn ui_locale_calendar_meeting_dialog_in_de() {
62 let _guard = locale_test_lock();
63 apply_locale("de");
64 assert_eq!(tr("calls.meeting.new_title"), "Neue Besprechung");
65 assert_eq!(tr("calls.meeting.teams_link_added"), "Teams-Besprechungslink wird hinzugefügt");
66 }
67}
crates/app/src/layout_guard.rs +1 −1
@@ -1611,7 +1611,7 @@ mod frames {
1611 1611 f32::from(
1612 1612 window
1613 1613 .text_system()
1614 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1614 .shape_line(text.clone().into(), px(NAV_LABEL_SIZE), &[run], None)
1615 1615 .width,
1616 1616 )
1617 1617 });
@@ -1611,7 +1611,7 @@ mod frames {
1611 f32::from(
1611 f32::from(
1612 window
1612 window
1613 .text_system()
1613 .text_system()
1614 .shape_line(text.into(), px(NAV_LABEL_SIZE), &[run], None)
1614 .shape_line(text.clone().into(), px(NAV_LABEL_SIZE), &[run], None)
1615 .width,
1615 .width,
1616 )
1616 )
1617 });
1617 });
crates/app/src/main.rs +102 −70
@@ -4,12 +4,15 @@
4 4 )]
5 5
6 6 mod active_appearance;
7 mod agent_direct;
7 mod active_locale;
8 mod i18n;
8 9 pub mod agents;
9 10 pub mod call;
10 11 mod inline_video;
11 12 #[cfg(test)]
12 13 mod layout_guard;
14 #[cfg(target_os = "linux")]
15 mod linux_browser;
13 16 pub mod notify;
14 17 mod settings;
15 18 mod views;
@@ -122,6 +125,7 @@ fn data_path(name: &str) -> PathBuf {
122 125 fn transport(
123 126 endpoint: Option<&str>,
124 127 database: Option<&std::path::Path>,
128 #[cfg(windows)] sign_in_title: String,
125 129 ) -> Arc<dyn session::Transport> {
126 130 #[cfg(windows)]
127 131 if endpoint.is_none() {
@@ -132,7 +136,7 @@ fn transport(
132 136 inline_video::configure(user_data_folder.clone());
133 137 let transport = webview::start(webview::HostConfig {
134 138 user_data_folder,
135 window_title: format!("{APP_NAME} - Sign in"),
139 window_title: sign_in_title,
136 140 log: |line| app_base::diagnostics::record(line),
137 141 });
138 142 task_dialog::install_host(transport.clone());
@@ -140,6 +144,10 @@ fn transport(
140 144 }
141 145 #[cfg(not(windows))]
142 146 let _ = database;
147 #[cfg(target_os = "linux")]
148 if endpoint.is_none() {
149 return linux_browser::start(session::DEFAULT_ENDPOINT);
150 }
143 151 Arc::new(session::CdpTransport::new(
144 152 endpoint.unwrap_or(session::DEFAULT_ENDPOINT),
145 153 ))
@@ -170,6 +178,8 @@ fn main() {
170 178 data_path(crash_log::CRASH_LOG_FILE),
171 179 );
172 180 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
181 #[cfg(target_os = "linux")]
182 app_base::linux_fonts::hide_system_color_emoji();
173 183 let arguments = parse_arguments();
174 184 if !arguments.demo && arguments.database.is_none() {
175 185 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -211,8 +221,24 @@ fn main() {
211 221 open_store(&path)
212 222 };
213 223 let store = Arc::new(store);
224 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(app_base::ui_locale::load(
225 &store,
226 )));
227 #[cfg(windows)]
228 let sign_in_title = format!(
229 "{} - {}",
230 app_base::APP_NAME,
231 app_base::ui_locale::tr("auth.sign_in")
232 );
214 233 let user_input = user_activity::UserInput::new();
215 234 let receiver = (!arguments.demo).then(|| {
235 #[cfg(windows)]
236 let transport = transport(
237 arguments.endpoint.as_deref(),
238 arguments.database.as_deref(),
239 sign_in_title.clone(),
240 );
241 #[cfg(not(windows))]
216 242 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
217 243 let activity = user_activity::track(user_input.clone());
218 244 backend::start(store.clone(), transport, !arguments.read_only, activity)
@@ -225,80 +251,86 @@ fn main() {
225 251 application = application.with_http_client(Arc::new(http_client));
226 252 }
227 253
228 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
229 gpui_kit::init(cx);
230 cx.on_app_quit(|_| {
231 updater::exit_after_grace();
232 async {}
233 })
234 .detach();
235 theme::load_fonts(cx);
236 active_appearance::install(&store, cx);
237 theme::apply(cx);
238 bind_keys(cx);
239 let state = cx.new(|_| {
240 let mut state = AppState::new(store, mode);
241 state.start_on_channels = arguments.channels_tab;
242 state
243 });
244 views::shell::install_globals(&state, user_input, cx);
245 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
246 agents::install(state.clone(), cx);
247 agent_direct::install(state.clone(), cx);
248 if arguments.demo {
249 demo::start_session(&state, cx);
250 }
251 if let Some(mut receiver) = receiver {
252 let state = state.clone();
253 cx.spawn(async move |cx| {
254 while let Some(event) = receiver.recv().await {
255 let kind = event.kind();
256 let started = std::time::Instant::now();
257 state.update(cx, |state, cx| state.apply(event, cx));
258 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
259 }
254 application
255 .with_assets(app_base::assets::AppAssets)
256 .run(move |cx| {
257 gpui_kit::init(cx);
258 cx.on_app_quit(|_| {
259 updater::exit_after_grace();
260 async {}
260 261 })
261 262 .detach();
262 }
263 theme::load_fonts(cx);
264 active_appearance::install(&store, cx);
265 active_locale::install(&store, cx);
266 theme::apply(cx);
267 bind_keys(cx);
268 let state = cx.new(|_| {
269 let mut state = AppState::new(store, mode);
270 state.start_on_channels = arguments.channels_tab;
271 state
272 });
273 views::shell::install_globals(&state, user_input, cx);
274 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
275 agents::install(state.clone(), cx);
276 if arguments.demo {
277 demo::start_session(&state, cx);
278 }
279 if let Some(mut receiver) = receiver {
280 let state = state.clone();
281 cx.spawn(async move |cx| {
282 while let Some(event) = receiver.recv().await {
283 let kind = event.kind();
284 let started = std::time::Instant::now();
285 #[cfg(target_os = "linux")]
286 linux_browser::note_backend_event(&event);
287 state.update(cx, |state, cx| state.apply(event, cx));
288 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
289 }
290 })
291 .detach();
292 }
263 293
264 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
265 let mut options = TitleBar::window_options();
266 options.window_bounds = Some(WindowBounds::Windowed(bounds));
267 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
268 options.app_id = Some(LINUX_APP_ID.to_owned());
269 if let Some(titlebar) = options.titlebar.as_mut() {
270 titlebar.title = Some(APP_NAME.into());
271 }
272 let open_target = arguments.open_target;
273 let startup = Startup {
274 switcher_query: arguments.switcher_query,
275 composer_text: arguments.composer_text,
276 reply_to_last: arguments.reply_to_last,
277 launched_by_autostart: arguments.autostart,
278 };
279 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
280 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
281 })
282 .expect("failed to open window");
283 let main_window_id = main_window.window_id();
284 cx.on_window_closed(move |cx, closed| {
285 if closed == main_window_id {
286 cx.quit();
294 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
295 let mut options = TitleBar::window_options();
296 options.window_bounds = Some(WindowBounds::Windowed(bounds));
297 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
298 options.app_id = Some(LINUX_APP_ID.to_owned());
299 if let Some(titlebar) = options.titlebar.as_mut() {
300 titlebar.title = Some(APP_NAME.into());
287 301 }
288 })
289 .detach();
290 if !arguments.autostart {
291 cx.activate(true);
292 }
293 cx.spawn(async move |cx| {
294 loop {
295 app_base::native_dumps::heartbeat();
296 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
302 let open_target = arguments.open_target;
303 let startup = Startup {
304 switcher_query: arguments.switcher_query,
305 composer_text: arguments.composer_text,
306 reply_to_last: arguments.reply_to_last,
307 launched_by_autostart: arguments.autostart,
308 };
309 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
310 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
311 })
312 .expect("failed to open window");
313 let main_window_id = main_window.window_id();
314 cx.on_window_closed(move |cx, closed| {
315 if closed == main_window_id {
316 cx.quit();
317 }
318 })
319 .detach();
320 if !arguments.autostart {
321 cx.activate(true);
297 322 }
298 })
299 .detach();
300 });
323 cx.spawn(async move |cx| {
324 loop {
325 app_base::native_dumps::heartbeat();
326 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
327 }
328 })
329 .detach();
330 });
301 331 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
332 #[cfg(target_os = "linux")]
333 linux_browser::stop();
302 334 #[cfg(windows)]
303 335 updater::exit_now();
304 336 }
@@ -4,12 +4,15 @@
4)]
4)]
5
5
6mod active_appearance;
6mod active_appearance;
7mod agent_direct;
7mod active_locale;
8mod i18n;
8pub mod agents;
9pub mod agents;
9pub mod call;
10pub mod call;
10mod inline_video;
11mod inline_video;
11#[cfg(test)]
12#[cfg(test)]
12mod layout_guard;
13mod layout_guard;
14#[cfg(target_os = "linux")]
15mod linux_browser;
13pub mod notify;
16pub mod notify;
14mod settings;
17mod settings;
15mod views;
18mod views;
@@ -122,6 +125,7 @@ fn data_path(name: &str) -> PathBuf {
122fn transport(
125fn transport(
123 endpoint: Option<&str>,
126 endpoint: Option<&str>,
124 database: Option<&std::path::Path>,
127 database: Option<&std::path::Path>,
128 #[cfg(windows)] sign_in_title: String,
125) -> Arc<dyn session::Transport> {
129) -> Arc<dyn session::Transport> {
126 #[cfg(windows)]
130 #[cfg(windows)]
127 if endpoint.is_none() {
131 if endpoint.is_none() {
@@ -132,7 +136,7 @@ fn transport(
132 inline_video::configure(user_data_folder.clone());
136 inline_video::configure(user_data_folder.clone());
133 let transport = webview::start(webview::HostConfig {
137 let transport = webview::start(webview::HostConfig {
134 user_data_folder,
138 user_data_folder,
135 window_title: format!("{APP_NAME} - Sign in"),
139 window_title: sign_in_title,
136 log: |line| app_base::diagnostics::record(line),
140 log: |line| app_base::diagnostics::record(line),
137 });
141 });
138 task_dialog::install_host(transport.clone());
142 task_dialog::install_host(transport.clone());
@@ -140,6 +144,10 @@ fn transport(
140 }
144 }
141 #[cfg(not(windows))]
145 #[cfg(not(windows))]
142 let _ = database;
146 let _ = database;
147 #[cfg(target_os = "linux")]
148 if endpoint.is_none() {
149 return linux_browser::start(session::DEFAULT_ENDPOINT);
150 }
143 Arc::new(session::CdpTransport::new(
151 Arc::new(session::CdpTransport::new(
144 endpoint.unwrap_or(session::DEFAULT_ENDPOINT),
152 endpoint.unwrap_or(session::DEFAULT_ENDPOINT),
145 ))
153 ))
@@ -170,6 +178,8 @@ fn main() {
170 data_path(crash_log::CRASH_LOG_FILE),
178 data_path(crash_log::CRASH_LOG_FILE),
171 );
179 );
172 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
180 diagnostics::install(data_path(diagnostics::DIAGNOSTICS_FILE));
181 #[cfg(target_os = "linux")]
182 app_base::linux_fonts::hide_system_color_emoji();
173 let arguments = parse_arguments();
183 let arguments = parse_arguments();
174 if !arguments.demo && arguments.database.is_none() {
184 if !arguments.demo && arguments.database.is_none() {
175 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
185 let relaunch_value = std::env::var(updater::RELAUNCH_ENV).ok();
@@ -211,8 +221,24 @@ fn main() {
211 open_store(&path)
221 open_store(&path)
212 };
222 };
213 let store = Arc::new(store);
223 let store = Arc::new(store);
224 app_base::ui_locale::apply_locale(app_base::ui_locale::effective_locale(app_base::ui_locale::load(
225 &store,
226 )));
227 #[cfg(windows)]
228 let sign_in_title = format!(
229 "{} - {}",
230 app_base::APP_NAME,
231 app_base::ui_locale::tr("auth.sign_in")
232 );
214 let user_input = user_activity::UserInput::new();
233 let user_input = user_activity::UserInput::new();
215 let receiver = (!arguments.demo).then(|| {
234 let receiver = (!arguments.demo).then(|| {
235 #[cfg(windows)]
236 let transport = transport(
237 arguments.endpoint.as_deref(),
238 arguments.database.as_deref(),
239 sign_in_title.clone(),
240 );
241 #[cfg(not(windows))]
216 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
242 let transport = transport(arguments.endpoint.as_deref(), arguments.database.as_deref());
217 let activity = user_activity::track(user_input.clone());
243 let activity = user_activity::track(user_input.clone());
218 backend::start(store.clone(), transport, !arguments.read_only, activity)
244 backend::start(store.clone(), transport, !arguments.read_only, activity)
@@ -225,80 +251,86 @@ fn main() {
225 application = application.with_http_client(Arc::new(http_client));
251 application = application.with_http_client(Arc::new(http_client));
226 }
252 }
227
253
228 application.with_assets(app_base::assets::AppAssets).run(move |cx| {
254 application
229 gpui_kit::init(cx);
255 .with_assets(app_base::assets::AppAssets)
230 cx.on_app_quit(|_| {
256 .run(move |cx| {
231 updater::exit_after_grace();
257 gpui_kit::init(cx);
232 async {}
258 cx.on_app_quit(|_| {
233 })
259 updater::exit_after_grace();
234 .detach();
260 async {}
235 theme::load_fonts(cx);
236 active_appearance::install(&store, cx);
237 theme::apply(cx);
238 bind_keys(cx);
239 let state = cx.new(|_| {
240 let mut state = AppState::new(store, mode);
241 state.start_on_channels = arguments.channels_tab;
242 state
243 });
244 views::shell::install_globals(&state, user_input, cx);
245 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
246 agents::install(state.clone(), cx);
247 agent_direct::install(state.clone(), cx);
248 if arguments.demo {
249 demo::start_session(&state, cx);
250 }
251 if let Some(mut receiver) = receiver {
252 let state = state.clone();
253 cx.spawn(async move |cx| {
254 while let Some(event) = receiver.recv().await {
255 let kind = event.kind();
256 let started = std::time::Instant::now();
257 state.update(cx, |state, cx| state.apply(event, cx));
258 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
259 }
260 })
261 })
261 .detach();
262 .detach();
262 }
263 theme::load_fonts(cx);
264 active_appearance::install(&store, cx);
265 active_locale::install(&store, cx);
266 theme::apply(cx);
267 bind_keys(cx);
268 let state = cx.new(|_| {
269 let mut state = AppState::new(store, mode);
270 state.start_on_channels = arguments.channels_tab;
271 state
272 });
273 views::shell::install_globals(&state, user_input, cx);
274 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
275 agents::install(state.clone(), cx);
276 if arguments.demo {
277 demo::start_session(&state, cx);
278 }
279 if let Some(mut receiver) = receiver {
280 let state = state.clone();
281 cx.spawn(async move |cx| {
282 while let Some(event) = receiver.recv().await {
283 let kind = event.kind();
284 let started = std::time::Instant::now();
285 #[cfg(target_os = "linux")]
286 linux_browser::note_backend_event(&event);
287 state.update(cx, |state, cx| state.apply(event, cx));
288 app_base::diagnostics::record_if_slow(&kind, started.elapsed());
289 }
290 })
291 .detach();
292 }
263
293
264 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
294 let bounds = Bounds::centered(None, size(px(WINDOW_WIDTH), px(WINDOW_HEIGHT)), cx);
265 let mut options = TitleBar::window_options();
295 let mut options = TitleBar::window_options();
266 options.window_bounds = Some(WindowBounds::Windowed(bounds));
296 options.window_bounds = Some(WindowBounds::Windowed(bounds));
267 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
297 options.window_min_size = Some(size(px(WINDOW_MIN_WIDTH), px(WINDOW_MIN_HEIGHT)));
268 options.app_id = Some(LINUX_APP_ID.to_owned());
298 options.app_id = Some(LINUX_APP_ID.to_owned());
269 if let Some(titlebar) = options.titlebar.as_mut() {
299 if let Some(titlebar) = options.titlebar.as_mut() {
270 titlebar.title = Some(APP_NAME.into());
300 titlebar.title = Some(APP_NAME.into());
271 }
272 let open_target = arguments.open_target;
273 let startup = Startup {
274 switcher_query: arguments.switcher_query,
275 composer_text: arguments.composer_text,
276 reply_to_last: arguments.reply_to_last,
277 launched_by_autostart: arguments.autostart,
278 };
279 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
280 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
281 })
282 .expect("failed to open window");
283 let main_window_id = main_window.window_id();
284 cx.on_window_closed(move |cx, closed| {
285 if closed == main_window_id {
286 cx.quit();
287 }
301 }
288 })
302 let open_target = arguments.open_target;
289 .detach();
303 let startup = Startup {
290 if !arguments.autostart {
304 switcher_query: arguments.switcher_query,
291 cx.activate(true);
305 composer_text: arguments.composer_text,
292 }
306 reply_to_last: arguments.reply_to_last,
293 cx.spawn(async move |cx| {
307 launched_by_autostart: arguments.autostart,
294 loop {
308 };
295 app_base::native_dumps::heartbeat();
309 let (main_window, _) = gpui_kit::open_window(options, cx, move |window, cx| {
296 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
310 cx.new(|cx| AppShell::new(state, open_target, startup, window, cx))
311 })
312 .expect("failed to open window");
313 let main_window_id = main_window.window_id();
314 cx.on_window_closed(move |cx, closed| {
315 if closed == main_window_id {
316 cx.quit();
317 }
318 })
319 .detach();
320 if !arguments.autostart {
321 cx.activate(true);
297 }
322 }
298 })
323 cx.spawn(async move |cx| {
299 .detach();
324 loop {
300 });
325 app_base::native_dumps::heartbeat();
326 cx.background_executor().timer(HEARTBEAT_INTERVAL).await;
327 }
328 })
329 .detach();
330 });
301 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
331 presence_link::unregister_on_exit(ENDPOINT_UNREGISTER_TIMEOUT);
332 #[cfg(target_os = "linux")]
333 linux_browser::stop();
302 #[cfg(windows)]
334 #[cfg(windows)]
303 updater::exit_now();
335 updater::exit_now();
304}
336}
crates/app/src/notify/center.rs +12 −0
@@ -29,6 +29,7 @@ use super::text::describe;
29 29 use super::toast::{PillView, ToastView};
30 30 use super::urgent_repeat::UrgentRepeats;
31 31 use crate::active_appearance::{self, ActiveAppearance};
32 use crate::active_locale::ActiveLocale;
32 33 use crate::activity::ActivityCenter;
33 34 use crate::agent_api::{self, pending::PendingProposal};
34 35 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
@@ -110,6 +111,7 @@ pub struct NotificationCenter {
110 111 _subscription: Subscription,
111 112 _activity_observation: Subscription,
112 113 _appearance_observation: Subscription,
114 _locale_observation: Subscription,
113 115 _agent_subscription: Option<Subscription>,
114 116 started_at: DateTime<Utc>,
115 117 known_proposals: HashSet<String>,
@@ -139,6 +141,9 @@ impl NotificationCenter {
139 141 let appearance_observation = cx.observe_global::<ActiveAppearance>(|this, cx| {
140 142 this.apply_app_icon(active_appearance::current(cx).app_icon, cx)
141 143 });
144 let locale_observation = cx.observe_global::<ActiveLocale>(|this, _| {
145 this.relocalize_tray();
146 });
142 147 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
143 148 this.on_app_event(event, cx);
144 149 });
@@ -188,6 +193,7 @@ impl NotificationCenter {
188 193 _subscription: subscription,
189 194 _activity_observation: activity_observation,
190 195 _appearance_observation: appearance_observation,
196 _locale_observation: locale_observation,
191 197 _agent_subscription: agent_subscription,
192 198 };
193 199 cx.spawn(async move |this, cx| {
@@ -1179,6 +1185,12 @@ impl NotificationCenter {
1179 1185 });
1180 1186 }
1181 1187
1188 fn relocalize_tray(&self) {
1189 if let Some(tray) = &self.tray {
1190 tray.relocalize();
1191 }
1192 }
1193
1182 1194 fn sync_tray(&self) {
1183 1195 if let Some(tray) = &self.tray {
1184 1196 tray.sync(
@@ -29,6 +29,7 @@ use super::text::describe;
29use super::toast::{PillView, ToastView};
29use super::toast::{PillView, ToastView};
30use super::urgent_repeat::UrgentRepeats;
30use super::urgent_repeat::UrgentRepeats;
31use crate::active_appearance::{self, ActiveAppearance};
31use crate::active_appearance::{self, ActiveAppearance};
32use crate::active_locale::ActiveLocale;
32use crate::activity::ActivityCenter;
33use crate::activity::ActivityCenter;
33use crate::agent_api::{self, pending::PendingProposal};
34use crate::agent_api::{self, pending::PendingProposal};
34use crate::agents::{AgentRun, AgentRunsEvent, RunState};
35use crate::agents::{AgentRun, AgentRunsEvent, RunState};
@@ -110,6 +111,7 @@ pub struct NotificationCenter {
110 _subscription: Subscription,
111 _subscription: Subscription,
111 _activity_observation: Subscription,
112 _activity_observation: Subscription,
112 _appearance_observation: Subscription,
113 _appearance_observation: Subscription,
114 _locale_observation: Subscription,
113 _agent_subscription: Option<Subscription>,
115 _agent_subscription: Option<Subscription>,
114 started_at: DateTime<Utc>,
116 started_at: DateTime<Utc>,
115 known_proposals: HashSet<String>,
117 known_proposals: HashSet<String>,
@@ -139,6 +141,9 @@ impl NotificationCenter {
139 let appearance_observation = cx.observe_global::<ActiveAppearance>(|this, cx| {
141 let appearance_observation = cx.observe_global::<ActiveAppearance>(|this, cx| {
140 this.apply_app_icon(active_appearance::current(cx).app_icon, cx)
142 this.apply_app_icon(active_appearance::current(cx).app_icon, cx)
141 });
143 });
144 let locale_observation = cx.observe_global::<ActiveLocale>(|this, _| {
145 this.relocalize_tray();
146 });
142 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
147 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
143 this.on_app_event(event, cx);
148 this.on_app_event(event, cx);
144 });
149 });
@@ -188,6 +193,7 @@ impl NotificationCenter {
188 _subscription: subscription,
193 _subscription: subscription,
189 _activity_observation: activity_observation,
194 _activity_observation: activity_observation,
190 _appearance_observation: appearance_observation,
195 _appearance_observation: appearance_observation,
196 _locale_observation: locale_observation,
191 _agent_subscription: agent_subscription,
197 _agent_subscription: agent_subscription,
192 };
198 };
193 cx.spawn(async move |this, cx| {
199 cx.spawn(async move |this, cx| {
@@ -1179,6 +1185,12 @@ impl NotificationCenter {
1179 });
1185 });
1180 }
1186 }
1181
1187
1188 fn relocalize_tray(&self) {
1189 if let Some(tray) = &self.tray {
1190 tray.relocalize();
1191 }
1192 }
1193
1182 fn sync_tray(&self) {
1194 fn sync_tray(&self) {
1183 if let Some(tray) = &self.tray {
1195 if let Some(tray) = &self.tray {
1184 tray.sync(
1196 tray.sync(
crates/app/src/settings/account.rs +5 −1
@@ -97,7 +97,11 @@ pub fn label_of<T: PartialEq + Copy>(options: &[Labeled<T>], current: T) -> &'st
97 97
98 98 pub fn account_select<T: PartialEq + Copy + 'static>(
99 99 app: &Entity<AppState>,
100 (id, title, detail): (&'static str, &'static str, &'static str),
100 (id, title, detail): (
101 &'static str,
102 impl Into<SharedString>,
103 impl Into<SharedString>,
104 ),
101 105 options: &'static [Labeled<T>],
102 106 current: T,
103 107 change: fn(T) -> ChatSettingChange,
@@ -97,7 +97,11 @@ pub fn label_of<T: PartialEq + Copy>(options: &[Labeled<T>], current: T) -> &'st
97
97
98pub fn account_select<T: PartialEq + Copy + 'static>(
98pub fn account_select<T: PartialEq + Copy + 'static>(
99 app: &Entity<AppState>,
99 app: &Entity<AppState>,
100 (id, title, detail): (&'static str, &'static str, &'static str),
100 (id, title, detail): (
101 &'static str,
102 impl Into<SharedString>,
103 impl Into<SharedString>,
104 ),
101 options: &'static [Labeled<T>],
105 options: &'static [Labeled<T>],
102 current: T,
106 current: T,
103 change: fn(T) -> ChatSettingChange,
107 change: fn(T) -> ChatSettingChange,
crates/app/src/settings/appearance.rs +58 −17
@@ -4,8 +4,11 @@ use gpui_kit::*;
4 4
5 5 use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
6 6 use crate::active_appearance;
7 use crate::active_locale;
7 8 use crate::app_state::AppState;
8 9 use crate::appearance::{AppIcon, ThemeChoice};
10 use crate::i18n::tr;
11 use app_base::ui_locale::LocalePreference;
9 12 use crate::theme::{self, Palette};
10 13 use crate::views::title_bar::app_icon_image;
11 14
@@ -18,18 +21,40 @@ const PREVIEW_RADIUS: f32 = TILE_RADIUS - TILE_PADDING;
18 21 const PREVIEW_ICON_SIZE: f32 = 48.;
19 22 const RADIO_SIZE: f32 = 16.;
20 23 const RADIO_DOT_SIZE: f32 = 8.;
21 const COLOR_SCHEME_DETAIL: &str = "The colors to use for Rusty Teams";
22 const THEME_TITLE: &str = "Theme";
23 const THEME_DETAIL: &str = "The theme to use for Teams";
24 24 const THEME_SELECT_WIDTH: f32 = 240.;
25 #[cfg(windows)]
26 const APP_ICON_DETAIL: &str =
27 "Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe";
28 #[cfg(not(windows))]
29 const APP_ICON_DETAIL: &str = "Shown in the title bar, taskbar and tray";
25 const LANGUAGE_SELECT_WIDTH: f32 = 240.;
26
27 fn language_label(pref: LocalePreference) -> String {
28 match pref {
29 LocalePreference::Auto => tr("settings.appearance.language.follow_system"),
30 LocalePreference::English => tr("settings.appearance.language.english"),
31 LocalePreference::German => tr("settings.appearance.language.german"),
32 }
33 }
34 fn app_icon_detail() -> String {
35 #[cfg(windows)]
36 {
37 tr("settings.appearance.app_icon_detail_windows")
38 }
39 #[cfg(not(windows))]
40 {
41 tr("settings.appearance.app_icon_detail")
42 }
43 }
30 44
31 45 pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
32 46 let current = active_appearance::current(cx);
47 let locale_pref = active_locale::current_preference(cx);
48 let language_choices = LocalePreference::ALL
49 .into_iter()
50 .map(|pref| {
51 let app = app.clone();
52 Choice::new(language_label(pref), pref == locale_pref, move |cx| {
53 let store = app.read(cx).store.clone();
54 active_locale::set_preference(pref, &store, cx);
55 })
56 })
57 .collect();
33 58 let scheme_tiles = theme::SCHEMES.into_iter().map(|scheme| {
34 59 let app = app.clone();
35 60 tile(
@@ -68,10 +93,22 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
68 93 .collect();
69 94 v_flex()
70 95 .w_full()
71 .child(caption("THEME"))
96 .child(caption(&tr("settings.caption.language")))
97 .child(control_row(
98 &tr("settings.appearance.language.title"),
99 &tr("settings.appearance.language.detail"),
100 select_with_width(
101 "settings-language",
102 language_label(locale_pref),
103 LANGUAGE_SELECT_WIDTH,
104 false,
105 language_choices,
106 ),
107 ))
108 .child(caption(tr("settings.caption.theme")))
72 109 .child(control_row(
73 THEME_TITLE,
74 THEME_DETAIL,
110 tr("settings.appearance.theme"),
111 tr("settings.appearance.theme_detail"),
75 112 select_with_width(
76 113 "settings-theme",
77 114 current.theme.label(),
@@ -81,17 +118,21 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
81 118 ),
82 119 ))
83 120 .child(choice_group(
84 "Color scheme",
85 COLOR_SCHEME_DETAIL,
121 tr("settings.appearance.color_scheme"),
122 tr("settings.appearance.color_scheme_detail"),
86 123 scheme_tiles,
87 124 ))
88 .child(caption("APP ICON"))
89 .child(choice_group("App icon", APP_ICON_DETAIL, icon_tiles))
125 .child(caption(tr("settings.caption.app_icon")))
126 .child(choice_group(
127 tr("settings.appearance.app_icon"),
128 app_icon_detail(),
129 icon_tiles,
130 ))
90 131 }
91 132
92 133 fn choice_group(
93 title: &'static str,
94 detail: &'static str,
134 title: impl Into<SharedString>,
135 detail: impl Into<SharedString>,
95 136 tiles: impl Iterator<Item = Stateful<Div>>,
96 137 ) -> Div {
97 138 v_flex()
@@ -4,8 +4,11 @@ use gpui_kit::*;
4
4
5use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
5use super::rows::{Choice, ROW_INSET, caption, control_row, select_with_width, titled};
6use crate::active_appearance;
6use crate::active_appearance;
7use crate::active_locale;
7use crate::app_state::AppState;
8use crate::app_state::AppState;
8use crate::appearance::{AppIcon, ThemeChoice};
9use crate::appearance::{AppIcon, ThemeChoice};
10use crate::i18n::tr;
11use app_base::ui_locale::LocalePreference;
9use crate::theme::{self, Palette};
12use crate::theme::{self, Palette};
10use crate::views::title_bar::app_icon_image;
13use crate::views::title_bar::app_icon_image;
11
14
@@ -18,18 +21,40 @@ const PREVIEW_RADIUS: f32 = TILE_RADIUS - TILE_PADDING;
18const PREVIEW_ICON_SIZE: f32 = 48.;
21const PREVIEW_ICON_SIZE: f32 = 48.;
19const RADIO_SIZE: f32 = 16.;
22const RADIO_SIZE: f32 = 16.;
20const RADIO_DOT_SIZE: f32 = 8.;
23const RADIO_DOT_SIZE: f32 = 8.;
21const COLOR_SCHEME_DETAIL: &str = "The colors to use for Rusty Teams";
22const THEME_TITLE: &str = "Theme";
23const THEME_DETAIL: &str = "The theme to use for Teams";
24const THEME_SELECT_WIDTH: f32 = 240.;
24const THEME_SELECT_WIDTH: f32 = 240.;
25#[cfg(windows)]
25const LANGUAGE_SELECT_WIDTH: f32 = 240.;
26const APP_ICON_DETAIL: &str =
26
27 "Shown in the title bar, taskbar and tray. Pinned shortcuts keep the icon of the .exe";
27fn language_label(pref: LocalePreference) -> String {
28#[cfg(not(windows))]
28 match pref {
29const APP_ICON_DETAIL: &str = "Shown in the title bar, taskbar and tray";
29 LocalePreference::Auto => tr("settings.appearance.language.follow_system"),
30 LocalePreference::English => tr("settings.appearance.language.english"),
31 LocalePreference::German => tr("settings.appearance.language.german"),
32 }
33}
34fn app_icon_detail() -> String {
35 #[cfg(windows)]
36 {
37 tr("settings.appearance.app_icon_detail_windows")
38 }
39 #[cfg(not(windows))]
40 {
41 tr("settings.appearance.app_icon_detail")
42 }
43}
30
44
31pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
45pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
32 let current = active_appearance::current(cx);
46 let current = active_appearance::current(cx);
47 let locale_pref = active_locale::current_preference(cx);
48 let language_choices = LocalePreference::ALL
49 .into_iter()
50 .map(|pref| {
51 let app = app.clone();
52 Choice::new(language_label(pref), pref == locale_pref, move |cx| {
53 let store = app.read(cx).store.clone();
54 active_locale::set_preference(pref, &store, cx);
55 })
56 })
57 .collect();
33 let scheme_tiles = theme::SCHEMES.into_iter().map(|scheme| {
58 let scheme_tiles = theme::SCHEMES.into_iter().map(|scheme| {
34 let app = app.clone();
59 let app = app.clone();
35 tile(
60 tile(
@@ -68,10 +93,22 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
68 .collect();
93 .collect();
69 v_flex()
94 v_flex()
70 .w_full()
95 .w_full()
71 .child(caption("THEME"))
96 .child(caption(&tr("settings.caption.language")))
97 .child(control_row(
98 &tr("settings.appearance.language.title"),
99 &tr("settings.appearance.language.detail"),
100 select_with_width(
101 "settings-language",
102 language_label(locale_pref),
103 LANGUAGE_SELECT_WIDTH,
104 false,
105 language_choices,
106 ),
107 ))
108 .child(caption(tr("settings.caption.theme")))
72 .child(control_row(
109 .child(control_row(
73 THEME_TITLE,
110 tr("settings.appearance.theme"),
74 THEME_DETAIL,
111 tr("settings.appearance.theme_detail"),
75 select_with_width(
112 select_with_width(
76 "settings-theme",
113 "settings-theme",
77 current.theme.label(),
114 current.theme.label(),
@@ -81,17 +118,21 @@ pub fn render(app: &Entity<AppState>, cx: &App) -> Div {
81 ),
118 ),
82 ))
119 ))
83 .child(choice_group(
120 .child(choice_group(
84 "Color scheme",
121 tr("settings.appearance.color_scheme"),
85 COLOR_SCHEME_DETAIL,
122 tr("settings.appearance.color_scheme_detail"),
86 scheme_tiles,
123 scheme_tiles,
87 ))
124 ))
88 .child(caption("APP ICON"))
125 .child(caption(tr("settings.caption.app_icon")))
89 .child(choice_group("App icon", APP_ICON_DETAIL, icon_tiles))
126 .child(choice_group(
127 tr("settings.appearance.app_icon"),
128 app_icon_detail(),
129 icon_tiles,
130 ))
90}
131}
91
132
92fn choice_group(
133fn choice_group(
93 title: &'static str,
134 title: impl Into<SharedString>,
94 detail: &'static str,
135 detail: impl Into<SharedString>,
95 tiles: impl Iterator<Item = Stateful<Div>>,
136 tiles: impl Iterator<Item = Stateful<Div>>,
96) -> Div {
137) -> Div {
97 v_flex()
138 v_flex()
crates/app/src/settings/general.rs +33 −25
@@ -12,15 +12,11 @@ use teams_core::{ChatSettingChange, TranslationBehavior};
12 12 use super::account::{UP_ARROW, account_select};
13 13 use super::rows::{Choice, caption, control_row, select, toggle_row};
14 14 use crate::app_state::AppState;
15 use crate::i18n::tr;
15 16 use crate::notify::NotificationCenter;
16 17 use crate::theme;
17 18 use crate::views::widgets::icon;
18 19
19 const BEHAVIORS: [(&str, TranslationBehavior); 3] = [
20 ("Ask me before translating", TranslationBehavior::Ask),
21 ("Auto-translate all messages", TranslationBehavior::Auto),
22 ("Never translate", TranslationBehavior::Never),
23 ];
24 20 const CHIP_HEIGHT: f32 = 24.;
25 21 const DISABLED_OPACITY: f32 = 0.4;
26 22 const LANGUAGE_MENU_HEIGHT: f32 = 320.;
@@ -31,7 +27,7 @@ fn startup_rows(center: &Entity<NotificationCenter>, cx: &App) -> [Stateful<Div>
31 27 [
32 28 toggle_row(
33 29 "settings-auto-start",
34 "Auto-start Teams",
30 tr("settings.general.auto_start"),
35 31 "",
36 32 theme::text_muted(),
37 33 startup.auto_start,
@@ -43,7 +39,7 @@ fn startup_rows(center: &Entity<NotificationCenter>, cx: &App) -> [Stateful<Div>
43 39 }),
44 40 toggle_row(
45 41 "settings-open-in-background",
46 "Open application in background",
42 tr("settings.general.open_in_background"),
47 43 "",
48 44 theme::text_muted(),
49 45 startup.open_in_background,
@@ -64,13 +60,13 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
64 60 let toggle_center = center.clone();
65 61 v_flex()
66 62 .w_full()
67 .child(caption("SYSTEM"))
63 .child(caption(tr("settings.caption.system")))
68 64 .children(startup_rows(center, cx))
69 65 .child(
70 66 toggle_row(
71 67 "settings-close-to-tray",
72 "On close, keep the application running",
73 "The title bar X hides the window to the tray",
68 tr("settings.general.close_to_tray"),
69 tr("settings.general.close_to_tray_detail"),
74 70 theme::text_muted(),
75 71 close_to_tray,
76 72 )
@@ -82,19 +78,19 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
82 78 })
83 79 }),
84 80 )
85 .child(caption("COMPOSE BOX"))
81 .child(caption(tr("settings.caption.compose_box")))
86 82 .child(account_select(
87 83 app,
88 84 (
89 85 "settings-up-arrow",
90 "Up arrow key behaviour in compose box",
91 "Choose what happens when you press Up arrow at the beginning of the compose box.",
86 tr("settings.general.up_arrow"),
87 tr("settings.general.up_arrow_detail"),
92 88 ),
93 89 &UP_ARROW,
94 90 app.read(cx).account_chat_settings().up_arrow,
95 91 ChatSettingChange::UpArrow,
96 92 ))
97 .child(caption("TRANSLATION"))
93 .child(caption(tr("settings.caption.translation")))
98 94 .children(translation_rows(app, cx))
99 95 }
100 96
@@ -102,8 +98,12 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
102 98 let state = app.read(cx);
103 99 if state.translation.settings.is_none() {
104 100 return vec![
105 control_row("Translation", "Translation settings not loaded yet", div())
106 .into_any_element(),
101 control_row(
102 tr("settings.general.translation_title"),
103 tr("settings.general.translation_not_loaded"),
104 div(),
105 )
106 .into_any_element(),
107 107 ];
108 108 }
109 109 let translation = &state.translation;
@@ -119,7 +119,19 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
119 119 })
120 120 })
121 121 .collect();
122 let behaviors = BEHAVIORS
122 let behavior_options = [
123 (tr("settings.general.behavior_ask"), TranslationBehavior::Ask),
124 (tr("settings.general.behavior_auto"), TranslationBehavior::Auto),
125 (
126 tr("settings.general.behavior_never"),
127 TranslationBehavior::Never,
128 ),
129 ];
130 let behavior_label = behavior_options
131 .iter()
132 .find(|(_, choice)| *choice == behavior)
133 .map_or(String::new(), |(label, _)| label.clone());
134 let behaviors = behavior_options
123 135 .into_iter()
124 136 .map(|(label, choice)| {
125 137 let app = app.clone();
@@ -128,13 +140,9 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
128 140 })
129 141 })
130 142 .collect();
131 let behavior_label = BEHAVIORS
132 .iter()
133 .find(|(_, choice)| *choice == behavior)
134 .map_or("", |(label, _)| label);
135 143 vec![
136 144 control_row(
137 "Translate messages into this language",
145 tr("settings.general.translate_into"),
138 146 "Read from your Teams account",
139 147 select(
140 148 "settings-translation-target",
@@ -145,7 +153,7 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
145 153 )
146 154 .into_any_element(),
147 155 control_row(
148 "How to handle messages in other languages",
156 tr("settings.general.behavior_title"),
149 157 "",
150 158 select(
151 159 "settings-translation-behavior",
@@ -156,7 +164,7 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
156 164 )
157 165 .into_any_element(),
158 166 control_row(
159 "Never translate messages in these languages",
167 tr("settings.general.never_translate"),
160 168 "",
161 169 never_chips(app, &target, cx),
162 170 )
@@ -228,7 +236,7 @@ fn add_language_button(choices: Vec<Choice>) -> impl IntoElement {
228 236 .rounded(px(6.))
229 237 .text_size(px(12.))
230 238 .text_color(theme::accent_text())
231 .label("+ Add language")
239 .label(format!("+ {}", tr("common.add")))
232 240 .dropdown_menu(move |menu, _, _| {
233 241 choices.iter().fold(
234 242 menu.max_h(px(LANGUAGE_MENU_HEIGHT)).scrollable(true),
@@ -12,15 +12,11 @@ use teams_core::{ChatSettingChange, TranslationBehavior};
12use super::account::{UP_ARROW, account_select};
12use super::account::{UP_ARROW, account_select};
13use super::rows::{Choice, caption, control_row, select, toggle_row};
13use super::rows::{Choice, caption, control_row, select, toggle_row};
14use crate::app_state::AppState;
14use crate::app_state::AppState;
15use crate::i18n::tr;
15use crate::notify::NotificationCenter;
16use crate::notify::NotificationCenter;
16use crate::theme;
17use crate::theme;
17use crate::views::widgets::icon;
18use crate::views::widgets::icon;
18
19
19const BEHAVIORS: [(&str, TranslationBehavior); 3] = [
20 ("Ask me before translating", TranslationBehavior::Ask),
21 ("Auto-translate all messages", TranslationBehavior::Auto),
22 ("Never translate", TranslationBehavior::Never),
23];
24const CHIP_HEIGHT: f32 = 24.;
20const CHIP_HEIGHT: f32 = 24.;
25const DISABLED_OPACITY: f32 = 0.4;
21const DISABLED_OPACITY: f32 = 0.4;
26const LANGUAGE_MENU_HEIGHT: f32 = 320.;
22const LANGUAGE_MENU_HEIGHT: f32 = 320.;
@@ -31,7 +27,7 @@ fn startup_rows(center: &Entity<NotificationCenter>, cx: &App) -> [Stateful<Div>
31 [
27 [
32 toggle_row(
28 toggle_row(
33 "settings-auto-start",
29 "settings-auto-start",
34 "Auto-start Teams",
30 tr("settings.general.auto_start"),
35 "",
31 "",
36 theme::text_muted(),
32 theme::text_muted(),
37 startup.auto_start,
33 startup.auto_start,
@@ -43,7 +39,7 @@ fn startup_rows(center: &Entity<NotificationCenter>, cx: &App) -> [Stateful<Div>
43 }),
39 }),
44 toggle_row(
40 toggle_row(
45 "settings-open-in-background",
41 "settings-open-in-background",
46 "Open application in background",
42 tr("settings.general.open_in_background"),
47 "",
43 "",
48 theme::text_muted(),
44 theme::text_muted(),
49 startup.open_in_background,
45 startup.open_in_background,
@@ -64,13 +60,13 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
64 let toggle_center = center.clone();
60 let toggle_center = center.clone();
65 v_flex()
61 v_flex()
66 .w_full()
62 .w_full()
67 .child(caption("SYSTEM"))
63 .child(caption(tr("settings.caption.system")))
68 .children(startup_rows(center, cx))
64 .children(startup_rows(center, cx))
69 .child(
65 .child(
70 toggle_row(
66 toggle_row(
71 "settings-close-to-tray",
67 "settings-close-to-tray",
72 "On close, keep the application running",
68 tr("settings.general.close_to_tray"),
73 "The title bar X hides the window to the tray",
69 tr("settings.general.close_to_tray_detail"),
74 theme::text_muted(),
70 theme::text_muted(),
75 close_to_tray,
71 close_to_tray,
76 )
72 )
@@ -82,19 +78,19 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
82 })
78 })
83 }),
79 }),
84 )
80 )
85 .child(caption("COMPOSE BOX"))
81 .child(caption(tr("settings.caption.compose_box")))
86 .child(account_select(
82 .child(account_select(
87 app,
83 app,
88 (
84 (
89 "settings-up-arrow",
85 "settings-up-arrow",
90 "Up arrow key behaviour in compose box",
86 tr("settings.general.up_arrow"),
91 "Choose what happens when you press Up arrow at the beginning of the compose box.",
87 tr("settings.general.up_arrow_detail"),
92 ),
88 ),
93 &UP_ARROW,
89 &UP_ARROW,
94 app.read(cx).account_chat_settings().up_arrow,
90 app.read(cx).account_chat_settings().up_arrow,
95 ChatSettingChange::UpArrow,
91 ChatSettingChange::UpArrow,
96 ))
92 ))
97 .child(caption("TRANSLATION"))
93 .child(caption(tr("settings.caption.translation")))
98 .children(translation_rows(app, cx))
94 .children(translation_rows(app, cx))
99}
95}
100
96
@@ -102,8 +98,12 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
102 let state = app.read(cx);
98 let state = app.read(cx);
103 if state.translation.settings.is_none() {
99 if state.translation.settings.is_none() {
104 return vec![
100 return vec![
105 control_row("Translation", "Translation settings not loaded yet", div())
101 control_row(
106 .into_any_element(),
102 tr("settings.general.translation_title"),
103 tr("settings.general.translation_not_loaded"),
104 div(),
105 )
106 .into_any_element(),
107 ];
107 ];
108 }
108 }
109 let translation = &state.translation;
109 let translation = &state.translation;
@@ -119,7 +119,19 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
119 })
119 })
120 })
120 })
121 .collect();
121 .collect();
122 let behaviors = BEHAVIORS
122 let behavior_options = [
123 (tr("settings.general.behavior_ask"), TranslationBehavior::Ask),
124 (tr("settings.general.behavior_auto"), TranslationBehavior::Auto),
125 (
126 tr("settings.general.behavior_never"),
127 TranslationBehavior::Never,
128 ),
129 ];
130 let behavior_label = behavior_options
131 .iter()
132 .find(|(_, choice)| *choice == behavior)
133 .map_or(String::new(), |(label, _)| label.clone());
134 let behaviors = behavior_options
123 .into_iter()
135 .into_iter()
124 .map(|(label, choice)| {
136 .map(|(label, choice)| {
125 let app = app.clone();
137 let app = app.clone();
@@ -128,13 +140,9 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
128 })
140 })
129 })
141 })
130 .collect();
142 .collect();
131 let behavior_label = BEHAVIORS
132 .iter()
133 .find(|(_, choice)| *choice == behavior)
134 .map_or("", |(label, _)| label);
135 vec![
143 vec![
136 control_row(
144 control_row(
137 "Translate messages into this language",
145 tr("settings.general.translate_into"),
138 "Read from your Teams account",
146 "Read from your Teams account",
139 select(
147 select(
140 "settings-translation-target",
148 "settings-translation-target",
@@ -145,7 +153,7 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
145 )
153 )
146 .into_any_element(),
154 .into_any_element(),
147 control_row(
155 control_row(
148 "How to handle messages in other languages",
156 tr("settings.general.behavior_title"),
149 "",
157 "",
150 select(
158 select(
151 "settings-translation-behavior",
159 "settings-translation-behavior",
@@ -156,7 +164,7 @@ fn translation_rows(app: &Entity<AppState>, cx: &App) -> Vec<AnyElement> {
156 )
164 )
157 .into_any_element(),
165 .into_any_element(),
158 control_row(
166 control_row(
159 "Never translate messages in these languages",
167 tr("settings.general.never_translate"),
160 "",
168 "",
161 never_chips(app, &target, cx),
169 never_chips(app, &target, cx),
162 )
170 )
@@ -228,7 +236,7 @@ fn add_language_button(choices: Vec<Choice>) -> impl IntoElement {
228 .rounded(px(6.))
236 .rounded(px(6.))
229 .text_size(px(12.))
237 .text_size(px(12.))
230 .text_color(theme::accent_text())
238 .text_color(theme::accent_text())
231 .label("+ Add language")
239 .label(format!("+ {}", tr("common.add")))
232 .dropdown_menu(move |menu, _, _| {
240 .dropdown_menu(move |menu, _, _| {
233 choices.iter().fold(
241 choices.iter().fold(
234 menu.max_h(px(LANGUAGE_MENU_HEIGHT)).scrollable(true),
242 menu.max_h(px(LANGUAGE_MENU_HEIGHT)).scrollable(true),
crates/app/src/settings/nav.rs +178 −88
@@ -1,19 +1,21 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{h_flex, v_flex};
4 4 use gpui_kit::prelude::FluentBuilder as _;
5 5 use gpui_kit::*;
6 6
7 use crate::i18n::tr;
7 8 use crate::settings_section::SettingsSection;
8 9 use crate::theme;
9 10 use crate::views::widgets::icon;
10 11
11 pub const TEAMS_GROUP: [SettingsSection; 6] = [
12 pub const TEAMS_GROUP: [SettingsSection; 7] = [
12 13 SettingsSection::General,
13 14 SettingsSection::Notifications,
14 15 SettingsSection::Appearance,
15 16 SettingsSection::Chats,
16 17 SettingsSection::Calls,
18 SettingsSection::Calendar,
17 19 SettingsSection::Devices,
18 20 ];
19 21 pub const RUSTY_GROUP: [SettingsSection; 2] = [SettingsSection::Agents, SettingsSection::Mcp];
@@ -24,58 +26,71 @@ const ITEM_GAP: f32 = 2.;
24 26 const ITEM_RADIUS: f32 = 6.;
25 27 const ITEM_ICON: f32 = 16.;
26 28 const NAV_PADDING_X: f32 = 12.;
27 const NO_RESULTS: &str = "No settings found";
28 29
29 fn search_terms(section: SettingsSection) -> &'static [&'static str] {
30 fn search_terms(section: SettingsSection) -> Vec<String> {
30 31 match section {
31 SettingsSection::General => &[
32 "Auto-start Teams",
33 "Open application in background",
34 "On close, keep the application running",
35 "Up arrow key behaviour in compose box",
36 "Translate messages into this language",
37 "How to handle messages in other languages",
38 "Never translate messages in these languages",
32 SettingsSection::General => vec![
33 tr("settings.general.auto_start"),
34 tr("settings.general.open_in_background"),
35 tr("settings.general.close_to_tray"),
36 tr("settings.general.up_arrow"),
37 tr("settings.general.translate_into"),
38 tr("settings.general.behavior_title"),
39 tr("settings.general.never_translate"),
40 ],
41 SettingsSection::Notifications => vec![
42 tr("settings.notifications.chat_messages"),
43 tr("settings.notifications.meeting_chats"),
44 tr("settings.notifications.likes_reactions"),
45 tr("settings.notifications.teams_channels"),
46 tr("settings.notifications.show_preview"),
47 tr("settings.notifications.notification_sound"),
48 tr("settings.notifications.urgent_sound"),
49 tr("settings.notifications.position"),
50 tr("settings.notifications.flash_taskbar"),
51 tr("settings.notifications.hide_in_calls"),
52 tr("settings.notifications.send_test"),
53 ],
54 SettingsSection::Appearance => vec![
55 tr("settings.appearance.theme"),
56 tr("settings.appearance.color_scheme"),
57 tr("settings.appearance.app_icon"),
58 ],
59 SettingsSection::Chats => vec![
60 tr("settings.chats.density"),
61 tr("settings.chats.read_receipts"),
62 tr("settings.chats.message_actions"),
63 tr("settings.chats.muted_section"),
64 tr("settings.chats.enter_to"),
65 tr("settings.chats.markdown"),
39 66 ],
40 SettingsSection::Notifications => &[
41 "Chat message notifications",
42 "Meeting chat notifications",
43 "Likes and reactions",
44 "Teams and channels",
45 "Show message preview",
46 "Notification sound",
47 "Urgent sound",
48 "Position on the screen",
49 "Flash taskbar when notifications are received",
50 "Hide notifications during calls and meetings",
51 "Send test notification",
67 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
68 SettingsSection::Calendar => vec![
69 "Google Calendar".to_owned(),
70 "Connect Google".to_owned(),
71 "Home calendar".to_owned(),
72 "Also write to".to_owned(),
73 "Outlook".to_owned(),
52 74 ],
53 SettingsSection::Appearance => &["Theme", "Color scheme", "App icon"],
54 SettingsSection::Chats => &[
55 "Message density",
56 "Read receipts",
57 "Show message actions on right click",
58 "Show muted items in their own section",
59 "When writing a message, press Enter to",
60 "Format messages using mark-down",
75 SettingsSection::Devices => vec![
76 "Speaker".to_owned(),
77 "Microphone".to_owned(),
78 "Noise suppression".to_owned(),
79 "Music mode".to_owned(),
80 "Camera".to_owned(),
81 "Background".to_owned(),
82 "Soft focus".to_owned(),
83 "Adjust brightness".to_owned(),
84 "Mirror my video".to_owned(),
85 "Make a test call".to_owned(),
86 "Save a test report after each call".to_owned(),
61 87 ],
62 SettingsSection::Calls => &["Ringtones"],
63 SettingsSection::Devices => &[
64 "Speaker",
65 "Microphone",
66 "Noise suppression",
67 "Music mode",
68 "Camera",
69 "Background",
70 "Soft focus",
71 "Adjust brightness",
72 "Mirror my video",
73 "Make a test call",
74 "Save a test report after each call",
88 SettingsSection::Agents => vec!["Claude".to_owned(), "Agent runs".to_owned()],
89 SettingsSection::Mcp => vec![
90 "Model Context Protocol".to_owned(),
91 "Conversation access".to_owned(),
75 92 ],
76 SettingsSection::Agents => &["Claude", "Agent runs"],
77 SettingsSection::Mcp => &["Model Context Protocol", "Conversation access"],
78 SettingsSection::About => &["Version", "Build"],
93 SettingsSection::About => vec!["Version".to_owned(), "Build".to_owned()],
79 94 }
80 95 }
81 96
@@ -83,7 +98,7 @@ pub fn matches(section: SettingsSection, query: &str) -> bool {
83 98 let query = query.trim().to_lowercase();
84 99 query.is_empty()
85 100 || std::iter::once(label(section))
86 .chain(search_terms(section).iter().copied())
101 .chain(search_terms(section))
87 102 .any(|text| text.to_lowercase().contains(&query))
88 103 }
89 104
@@ -96,17 +111,18 @@ pub fn first_match(query: &str, agents_available: bool) -> Option<SettingsSectio
96 111 .find(|section| matches(*section, query))
97 112 }
98 113
99 pub fn label(section: SettingsSection) -> &'static str {
114 pub fn label(section: SettingsSection) -> String {
100 115 match section {
101 SettingsSection::General => "General",
102 SettingsSection::Notifications => "Notifications and activity",
103 SettingsSection::Appearance => "Appearance and accessibility",
104 SettingsSection::Chats => "Chats and channels",
105 SettingsSection::Calls => "Calls",
106 SettingsSection::Devices => "Devices",
107 SettingsSection::Agents => "Agents",
108 SettingsSection::Mcp => "MCP",
109 SettingsSection::About => "About",
116 SettingsSection::General => tr("settings.nav.general"),
117 SettingsSection::Notifications => tr("settings.nav.notifications"),
118 SettingsSection::Appearance => tr("settings.nav.appearance"),
119 SettingsSection::Chats => tr("settings.nav.chats"),
120 SettingsSection::Calls => tr("settings.nav.calls"),
121 SettingsSection::Calendar => tr("settings.nav.calendar"),
122 SettingsSection::Devices => tr("settings.nav.devices"),
123 SettingsSection::Agents => tr("settings.nav.agents"),
124 SettingsSection::Mcp => tr("settings.nav.mcp"),
125 SettingsSection::About => tr("settings.nav.about"),
110 126 }
111 127 }
112 128
@@ -117,6 +133,7 @@ fn icon_name(section: SettingsSection) -> IconName {
117 133 SettingsSection::Appearance => IconName::Palette,
118 134 SettingsSection::Chats => IconName::MessageSquare,
119 135 SettingsSection::Calls => IconName::Phone,
136 SettingsSection::Calendar => IconName::Calendar,
120 137 SettingsSection::Devices => IconName::Headphones,
121 138 SettingsSection::Agents => IconName::Bot,
122 139 SettingsSection::Mcp => IconName::Plug,
@@ -139,6 +156,7 @@ fn element_id(section: SettingsSection) -> &'static str {
139 156 SettingsSection::Appearance => "settings-nav-appearance",
140 157 SettingsSection::Chats => "settings-nav-chats",
141 158 SettingsSection::Calls => "settings-nav-calls",
159 SettingsSection::Calendar => "settings-nav-calendar",
142 160 SettingsSection::Devices => "settings-nav-devices",
143 161 SettingsSection::Agents => "settings-nav-agents",
144 162 SettingsSection::Mcp => "settings-nav-mcp",
@@ -203,7 +221,7 @@ pub fn render_nav(
203 221 .line_height(px(26.))
204 222 .font_weight(FontWeight::SEMIBOLD)
205 223 .text_color(theme::text())
206 .child("Settings"),
224 .child(tr("common.settings")),
207 225 )
208 226 .child(
209 227 div()
@@ -229,34 +247,45 @@ pub fn render_nav(
229 247 .py(px(ITEM_PADDING_Y))
230 248 .text_size(px(13.))
231 249 .text_color(theme::text_muted())
232 .child(NO_RESULTS),
250 .child(tr("settings.search.no_results")),
233 251 )
234 252 })
235 .when(!rusty.is_empty(), |groups| groups.child(
236 div()
237 .debug_selector(|| "settings/nav/divider".into())
238 .w_full()
239 .h(px(1.))
240 .flex_none()
241 .mt(px(10.))
242 .bg(theme::border_strong()),
243 )
244 .child(
245 div()
246 .px(px(2. * NAV_PADDING_X))
247 .pt(px(12.))
248 .pb(px(6.))
249 .text_size(px(12.))
250 .font_weight(FontWeight::SEMIBOLD)
251 .text_color(theme::text_muted())
252 .child("RUSTY TEAMS"),
253 ).child(group(rusty))),
253 .when(!rusty.is_empty(), |groups| {
254 groups
255 .child(
256 // No debug_selector: scroll content bounds are unclipped, so a
257 // tagged divider under settings/nav false-overlaps sticky About.
258 div()
259 .w_full()
260 .h(px(1.))
261 .flex_none()
262 .mt(px(10.))
263 .bg(theme::border_strong()),
264 )
265 .child(
266 div()
267 .px(px(2. * NAV_PADDING_X))
268 .pt(px(12.))
269 .pb(px(6.))
270 .text_size(px(12.))
271 .font_weight(FontWeight::SEMIBOLD)
272 .text_color(theme::text_muted())
273 .child("RUSTY TEAMS"),
274 )
275 .child(group(rusty))
276 }),
254 277 )
255 278 .when(about_shown, |nav| {
256 279 nav.child(
257 div().w_full().px(px(NAV_PADDING_X)).child(
258 item(SettingsSection::About).debug_selector(|| "settings/nav/about".into()),
259 ),
280 div()
281 .w_full()
282 .flex_none()
283 .px(px(NAV_PADDING_X))
284 .pt(px(6.))
285 .child(
286 item(SettingsSection::About)
287 .debug_selector(|| "settings/nav/about".into()),
288 ),
260 289 )
261 290 })
262 291 }
@@ -266,6 +295,7 @@ fn nav_item(
266 295 active: bool,
267 296 on_select: impl Fn(SettingsSection, &mut Window, &mut App) + 'static,
268 297 ) -> Stateful<Div> {
298 let label_text = label(section);
269 299 h_flex()
270 300 .id(element_id(section))
271 301 .debug_selector(move || item_selector(section))
@@ -301,17 +331,20 @@ fn nav_item(
301 331 .debug_selector(move || label_selector(section))
302 332 .flex_1()
303 333 .min_w_0()
304 .child(label(section)),
334 .child(label_text),
305 335 )
306 336 .on_click(move |_, window, cx| on_select(section, window, cx))
307 337 }
308 338
309 339 #[cfg(test)]
310 340 mod tests {
341 use app_base::ui_locale::apply_locale;
342
311 343 use super::{SettingsSection, first_match, label, matches, search_terms};
312 344
313 345 #[test]
314 346 fn search_finds_sections_by_name_and_by_setting() {
347 apply_locale("en");
315 348 assert!(matches(SettingsSection::Chats, "read receipts"));
316 349 assert!(matches(SettingsSection::Devices, "MICRO"));
317 350 assert!(matches(SettingsSection::Calls, "calls"));
@@ -322,18 +355,75 @@ mod tests {
322 355 assert_eq!(first_match("xyz", true), None);
323 356 }
324 357
358 fn search_term_keys(section: SettingsSection) -> &'static [&'static str] {
359 match section {
360 SettingsSection::General => &[
361 "settings.general.auto_start",
362 "settings.general.open_in_background",
363 "settings.general.close_to_tray",
364 "settings.general.up_arrow",
365 "settings.general.translate_into",
366 "settings.general.behavior_title",
367 "settings.general.never_translate",
368 ],
369 SettingsSection::Notifications => &[
370 "settings.notifications.chat_messages",
371 "settings.notifications.meeting_chats",
372 "settings.notifications.likes_reactions",
373 "settings.notifications.teams_channels",
374 "settings.notifications.show_preview",
375 "settings.notifications.notification_sound",
376 "settings.notifications.urgent_sound",
377 "settings.notifications.position",
378 "settings.notifications.flash_taskbar",
379 "settings.notifications.hide_in_calls",
380 "settings.notifications.send_test",
381 ],
382 SettingsSection::Appearance => &[
383 "settings.appearance.theme",
384 "settings.appearance.color_scheme",
385 "settings.appearance.app_icon",
386 ],
387 SettingsSection::Chats => &[
388 "settings.chats.density",
389 "settings.chats.read_receipts",
390 "settings.chats.message_actions",
391 "settings.chats.muted_section",
392 "settings.chats.enter_to",
393 "settings.chats.markdown",
394 ],
395 _ => &[],
396 }
397 }
398
325 399 #[test]
326 400 fn every_search_term_names_a_setting_on_its_page() {
401 apply_locale("en");
327 402 let pages = [
328 403 (SettingsSection::General, include_str!("general.rs")),
329 (SettingsSection::Notifications, include_str!("notifications.rs")),
404 (
405 SettingsSection::Notifications,
406 include_str!("notifications.rs"),
407 ),
330 408 (SettingsSection::Appearance, include_str!("appearance.rs")),
331 (SettingsSection::Chats, include_str!("chats.rs")),
332 409 (SettingsSection::Devices, include_str!("devices.rs")),
333 410 ];
334 411 for (section, source) in pages {
335 for term in search_terms(section) {
336 assert!(source.contains(term), "{term} is not on {}", label(section));
412 for key in search_term_keys(section) {
413 assert!(
414 source.contains(key),
415 "{key} is not wired on {}",
416 label(section)
417 );
418 }
419 if search_term_keys(section).is_empty() {
420 for term in search_terms(section) {
421 assert!(
422 source.contains(&term),
423 "{term} is not on {}",
424 label(section)
425 );
426 }
337 427 }
338 428 }
339 429 }
@@ -1,19 +1,21 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
5use gpui_kit::*;
6
6
7use crate::i18n::tr;
7use crate::settings_section::SettingsSection;
8use crate::settings_section::SettingsSection;
8use crate::theme;
9use crate::theme;
9use crate::views::widgets::icon;
10use crate::views::widgets::icon;
10
11
11pub const TEAMS_GROUP: [SettingsSection; 6] = [
12pub const TEAMS_GROUP: [SettingsSection; 7] = [
12 SettingsSection::General,
13 SettingsSection::General,
13 SettingsSection::Notifications,
14 SettingsSection::Notifications,
14 SettingsSection::Appearance,
15 SettingsSection::Appearance,
15 SettingsSection::Chats,
16 SettingsSection::Chats,
16 SettingsSection::Calls,
17 SettingsSection::Calls,
18 SettingsSection::Calendar,
17 SettingsSection::Devices,
19 SettingsSection::Devices,
18];
20];
19pub const RUSTY_GROUP: [SettingsSection; 2] = [SettingsSection::Agents, SettingsSection::Mcp];
21pub const RUSTY_GROUP: [SettingsSection; 2] = [SettingsSection::Agents, SettingsSection::Mcp];
@@ -24,58 +26,71 @@ const ITEM_GAP: f32 = 2.;
24const ITEM_RADIUS: f32 = 6.;
26const ITEM_RADIUS: f32 = 6.;
25const ITEM_ICON: f32 = 16.;
27const ITEM_ICON: f32 = 16.;
26const NAV_PADDING_X: f32 = 12.;
28const NAV_PADDING_X: f32 = 12.;
27const NO_RESULTS: &str = "No settings found";
28
29
29fn search_terms(section: SettingsSection) -> &'static [&'static str] {
30fn search_terms(section: SettingsSection) -> Vec<String> {
30 match section {
31 match section {
31 SettingsSection::General => &[
32 SettingsSection::General => vec![
32 "Auto-start Teams",
33 tr("settings.general.auto_start"),
33 "Open application in background",
34 tr("settings.general.open_in_background"),
34 "On close, keep the application running",
35 tr("settings.general.close_to_tray"),
35 "Up arrow key behaviour in compose box",
36 tr("settings.general.up_arrow"),
36 "Translate messages into this language",
37 tr("settings.general.translate_into"),
37 "How to handle messages in other languages",
38 tr("settings.general.behavior_title"),
38 "Never translate messages in these languages",
39 tr("settings.general.never_translate"),
40 ],
41 SettingsSection::Notifications => vec![
42 tr("settings.notifications.chat_messages"),
43 tr("settings.notifications.meeting_chats"),
44 tr("settings.notifications.likes_reactions"),
45 tr("settings.notifications.teams_channels"),
46 tr("settings.notifications.show_preview"),
47 tr("settings.notifications.notification_sound"),
48 tr("settings.notifications.urgent_sound"),
49 tr("settings.notifications.position"),
50 tr("settings.notifications.flash_taskbar"),
51 tr("settings.notifications.hide_in_calls"),
52 tr("settings.notifications.send_test"),
53 ],
54 SettingsSection::Appearance => vec![
55 tr("settings.appearance.theme"),
56 tr("settings.appearance.color_scheme"),
57 tr("settings.appearance.app_icon"),
58 ],
59 SettingsSection::Chats => vec![
60 tr("settings.chats.density"),
61 tr("settings.chats.read_receipts"),
62 tr("settings.chats.message_actions"),
63 tr("settings.chats.muted_section"),
64 tr("settings.chats.enter_to"),
65 tr("settings.chats.markdown"),
39 ],
66 ],
40 SettingsSection::Notifications => &[
67 SettingsSection::Calls => vec![tr("settings.calls.ringtones")],
41 "Chat message notifications",
68 SettingsSection::Calendar => vec![
42 "Meeting chat notifications",
69 "Google Calendar".to_owned(),
43 "Likes and reactions",
70 "Connect Google".to_owned(),
44 "Teams and channels",
71 "Home calendar".to_owned(),
45 "Show message preview",
72 "Also write to".to_owned(),
46 "Notification sound",
73 "Outlook".to_owned(),
47 "Urgent sound",
48 "Position on the screen",
49 "Flash taskbar when notifications are received",
50 "Hide notifications during calls and meetings",
51 "Send test notification",
52 ],
74 ],
53 SettingsSection::Appearance => &["Theme", "Color scheme", "App icon"],
75 SettingsSection::Devices => vec![
54 SettingsSection::Chats => &[
76 "Speaker".to_owned(),
55 "Message density",
77 "Microphone".to_owned(),
56 "Read receipts",
78 "Noise suppression".to_owned(),
57 "Show message actions on right click",
79 "Music mode".to_owned(),
58 "Show muted items in their own section",
80 "Camera".to_owned(),
59 "When writing a message, press Enter to",
81 "Background".to_owned(),
60 "Format messages using mark-down",
82 "Soft focus".to_owned(),
83 "Adjust brightness".to_owned(),
84 "Mirror my video".to_owned(),
85 "Make a test call".to_owned(),
86 "Save a test report after each call".to_owned(),
61 ],
87 ],
62 SettingsSection::Calls => &["Ringtones"],
88 SettingsSection::Agents => vec!["Claude".to_owned(), "Agent runs".to_owned()],
63 SettingsSection::Devices => &[
89 SettingsSection::Mcp => vec![
64 "Speaker",
90 "Model Context Protocol".to_owned(),
65 "Microphone",
91 "Conversation access".to_owned(),
66 "Noise suppression",
67 "Music mode",
68 "Camera",
69 "Background",
70 "Soft focus",
71 "Adjust brightness",
72 "Mirror my video",
73 "Make a test call",
74 "Save a test report after each call",
75 ],
92 ],
76 SettingsSection::Agents => &["Claude", "Agent runs"],
93 SettingsSection::About => vec!["Version".to_owned(), "Build".to_owned()],
77 SettingsSection::Mcp => &["Model Context Protocol", "Conversation access"],
78 SettingsSection::About => &["Version", "Build"],
79 }
94 }
80}
95}
81
96
@@ -83,7 +98,7 @@ pub fn matches(section: SettingsSection, query: &str) -> bool {
83 let query = query.trim().to_lowercase();
98 let query = query.trim().to_lowercase();
84 query.is_empty()
99 query.is_empty()
85 || std::iter::once(label(section))
100 || std::iter::once(label(section))
86 .chain(search_terms(section).iter().copied())
101 .chain(search_terms(section))
87 .any(|text| text.to_lowercase().contains(&query))
102 .any(|text| text.to_lowercase().contains(&query))
88}
103}
89
104
@@ -96,17 +111,18 @@ pub fn first_match(query: &str, agents_available: bool) -> Option<SettingsSectio
96 .find(|section| matches(*section, query))
111 .find(|section| matches(*section, query))
97}
112}
98
113
99pub fn label(section: SettingsSection) -> &'static str {
114pub fn label(section: SettingsSection) -> String {
100 match section {
115 match section {
101 SettingsSection::General => "General",
116 SettingsSection::General => tr("settings.nav.general"),
102 SettingsSection::Notifications => "Notifications and activity",
117 SettingsSection::Notifications => tr("settings.nav.notifications"),
103 SettingsSection::Appearance => "Appearance and accessibility",
118 SettingsSection::Appearance => tr("settings.nav.appearance"),
104 SettingsSection::Chats => "Chats and channels",
119 SettingsSection::Chats => tr("settings.nav.chats"),
105 SettingsSection::Calls => "Calls",
120 SettingsSection::Calls => tr("settings.nav.calls"),
106 SettingsSection::Devices => "Devices",
121 SettingsSection::Calendar => tr("settings.nav.calendar"),
107 SettingsSection::Agents => "Agents",
122 SettingsSection::Devices => tr("settings.nav.devices"),
108 SettingsSection::Mcp => "MCP",
123 SettingsSection::Agents => tr("settings.nav.agents"),
109 SettingsSection::About => "About",
124 SettingsSection::Mcp => tr("settings.nav.mcp"),
125 SettingsSection::About => tr("settings.nav.about"),
110 }
126 }
111}
127}
112
128
@@ -117,6 +133,7 @@ fn icon_name(section: SettingsSection) -> IconName {
117 SettingsSection::Appearance => IconName::Palette,
133 SettingsSection::Appearance => IconName::Palette,
118 SettingsSection::Chats => IconName::MessageSquare,
134 SettingsSection::Chats => IconName::MessageSquare,
119 SettingsSection::Calls => IconName::Phone,
135 SettingsSection::Calls => IconName::Phone,
136 SettingsSection::Calendar => IconName::Calendar,
120 SettingsSection::Devices => IconName::Headphones,
137 SettingsSection::Devices => IconName::Headphones,
121 SettingsSection::Agents => IconName::Bot,
138 SettingsSection::Agents => IconName::Bot,
122 SettingsSection::Mcp => IconName::Plug,
139 SettingsSection::Mcp => IconName::Plug,
@@ -139,6 +156,7 @@ fn element_id(section: SettingsSection) -> &'static str {
139 SettingsSection::Appearance => "settings-nav-appearance",
156 SettingsSection::Appearance => "settings-nav-appearance",
140 SettingsSection::Chats => "settings-nav-chats",
157 SettingsSection::Chats => "settings-nav-chats",
141 SettingsSection::Calls => "settings-nav-calls",
158 SettingsSection::Calls => "settings-nav-calls",
159 SettingsSection::Calendar => "settings-nav-calendar",
142 SettingsSection::Devices => "settings-nav-devices",
160 SettingsSection::Devices => "settings-nav-devices",
143 SettingsSection::Agents => "settings-nav-agents",
161 SettingsSection::Agents => "settings-nav-agents",
144 SettingsSection::Mcp => "settings-nav-mcp",
162 SettingsSection::Mcp => "settings-nav-mcp",
@@ -203,7 +221,7 @@ pub fn render_nav(
203 .line_height(px(26.))
221 .line_height(px(26.))
204 .font_weight(FontWeight::SEMIBOLD)
222 .font_weight(FontWeight::SEMIBOLD)
205 .text_color(theme::text())
223 .text_color(theme::text())
206 .child("Settings"),
224 .child(tr("common.settings")),
207 )
225 )
208 .child(
226 .child(
209 div()
227 div()
@@ -229,34 +247,45 @@ pub fn render_nav(
229 .py(px(ITEM_PADDING_Y))
247 .py(px(ITEM_PADDING_Y))
230 .text_size(px(13.))
248 .text_size(px(13.))
231 .text_color(theme::text_muted())
249 .text_color(theme::text_muted())
232 .child(NO_RESULTS),
250 .child(tr("settings.search.no_results")),
233 )
251 )
234 })
252 })
235 .when(!rusty.is_empty(), |groups| groups.child(
253 .when(!rusty.is_empty(), |groups| {
236 div()
254 groups
237 .debug_selector(|| "settings/nav/divider".into())
255 .child(
238 .w_full()
256 // No debug_selector: scroll content bounds are unclipped, so a
239 .h(px(1.))
257 // tagged divider under settings/nav false-overlaps sticky About.
240 .flex_none()
258 div()
241 .mt(px(10.))
259 .w_full()
242 .bg(theme::border_strong()),
260 .h(px(1.))
243 )
261 .flex_none()
244 .child(
262 .mt(px(10.))
245 div()
263 .bg(theme::border_strong()),
246 .px(px(2. * NAV_PADDING_X))
264 )
247 .pt(px(12.))
265 .child(
248 .pb(px(6.))
266 div()
249 .text_size(px(12.))
267 .px(px(2. * NAV_PADDING_X))
250 .font_weight(FontWeight::SEMIBOLD)
268 .pt(px(12.))
251 .text_color(theme::text_muted())
269 .pb(px(6.))
252 .child("RUSTY TEAMS"),
270 .text_size(px(12.))
253 ).child(group(rusty))),
271 .font_weight(FontWeight::SEMIBOLD)
272 .text_color(theme::text_muted())
273 .child("RUSTY TEAMS"),
274 )
275 .child(group(rusty))
276 }),
254 )
277 )
255 .when(about_shown, |nav| {
278 .when(about_shown, |nav| {
256 nav.child(
279 nav.child(
257 div().w_full().px(px(NAV_PADDING_X)).child(
280 div()
258 item(SettingsSection::About).debug_selector(|| "settings/nav/about".into()),
281 .w_full()
259 ),
282 .flex_none()
283 .px(px(NAV_PADDING_X))
284 .pt(px(6.))
285 .child(
286 item(SettingsSection::About)
287 .debug_selector(|| "settings/nav/about".into()),
288 ),
260 )
289 )
261 })
290 })
262}
291}
@@ -266,6 +295,7 @@ fn nav_item(
266 active: bool,
295 active: bool,
267 on_select: impl Fn(SettingsSection, &mut Window, &mut App) + 'static,
296 on_select: impl Fn(SettingsSection, &mut Window, &mut App) + 'static,
268) -> Stateful<Div> {
297) -> Stateful<Div> {
298 let label_text = label(section);
269 h_flex()
299 h_flex()
270 .id(element_id(section))
300 .id(element_id(section))
271 .debug_selector(move || item_selector(section))
301 .debug_selector(move || item_selector(section))
@@ -301,17 +331,20 @@ fn nav_item(
301 .debug_selector(move || label_selector(section))
331 .debug_selector(move || label_selector(section))
302 .flex_1()
332 .flex_1()
303 .min_w_0()
333 .min_w_0()
304 .child(label(section)),
334 .child(label_text),
305 )
335 )
306 .on_click(move |_, window, cx| on_select(section, window, cx))
336 .on_click(move |_, window, cx| on_select(section, window, cx))
307}
337}
308
338
309#[cfg(test)]
339#[cfg(test)]
310mod tests {
340mod tests {
341 use app_base::ui_locale::apply_locale;
342
311 use super::{SettingsSection, first_match, label, matches, search_terms};
343 use super::{SettingsSection, first_match, label, matches, search_terms};
312
344
313 #[test]
345 #[test]
314 fn search_finds_sections_by_name_and_by_setting() {
346 fn search_finds_sections_by_name_and_by_setting() {
347 apply_locale("en");
315 assert!(matches(SettingsSection::Chats, "read receipts"));
348 assert!(matches(SettingsSection::Chats, "read receipts"));
316 assert!(matches(SettingsSection::Devices, "MICRO"));
349 assert!(matches(SettingsSection::Devices, "MICRO"));
317 assert!(matches(SettingsSection::Calls, "calls"));
350 assert!(matches(SettingsSection::Calls, "calls"));
@@ -322,18 +355,75 @@ mod tests {
322 assert_eq!(first_match("xyz", true), None);
355 assert_eq!(first_match("xyz", true), None);
323 }
356 }
324
357
358 fn search_term_keys(section: SettingsSection) -> &'static [&'static str] {
359 match section {
360 SettingsSection::General => &[
361 "settings.general.auto_start",
362 "settings.general.open_in_background",
363 "settings.general.close_to_tray",
364 "settings.general.up_arrow",
365 "settings.general.translate_into",
366 "settings.general.behavior_title",
367 "settings.general.never_translate",
368 ],
369 SettingsSection::Notifications => &[
370 "settings.notifications.chat_messages",
371 "settings.notifications.meeting_chats",
372 "settings.notifications.likes_reactions",
373 "settings.notifications.teams_channels",
374 "settings.notifications.show_preview",
375 "settings.notifications.notification_sound",
376 "settings.notifications.urgent_sound",
377 "settings.notifications.position",
378 "settings.notifications.flash_taskbar",
379 "settings.notifications.hide_in_calls",
380 "settings.notifications.send_test",
381 ],
382 SettingsSection::Appearance => &[
383 "settings.appearance.theme",
384 "settings.appearance.color_scheme",
385 "settings.appearance.app_icon",
386 ],
387 SettingsSection::Chats => &[
388 "settings.chats.density",
389 "settings.chats.read_receipts",
390 "settings.chats.message_actions",
391 "settings.chats.muted_section",
392 "settings.chats.enter_to",
393 "settings.chats.markdown",
394 ],
395 _ => &[],
396 }
397 }
398
325 #[test]
399 #[test]
326 fn every_search_term_names_a_setting_on_its_page() {
400 fn every_search_term_names_a_setting_on_its_page() {
401 apply_locale("en");
327 let pages = [
402 let pages = [
328 (SettingsSection::General, include_str!("general.rs")),
403 (SettingsSection::General, include_str!("general.rs")),
329 (SettingsSection::Notifications, include_str!("notifications.rs")),
404 (
405 SettingsSection::Notifications,
406 include_str!("notifications.rs"),
407 ),
330 (SettingsSection::Appearance, include_str!("appearance.rs")),
408 (SettingsSection::Appearance, include_str!("appearance.rs")),
331 (SettingsSection::Chats, include_str!("chats.rs")),
332 (SettingsSection::Devices, include_str!("devices.rs")),
409 (SettingsSection::Devices, include_str!("devices.rs")),
333 ];
410 ];
334 for (section, source) in pages {
411 for (section, source) in pages {
335 for term in search_terms(section) {
412 for key in search_term_keys(section) {
336 assert!(source.contains(term), "{term} is not on {}", label(section));
413 assert!(
414 source.contains(key),
415 "{key} is not wired on {}",
416 label(section)
417 );
418 }
419 if search_term_keys(section).is_empty() {
420 for term in search_terms(section) {
421 assert!(
422 source.contains(&term),
423 "{term} is not on {}",
424 label(section)
425 );
426 }
337 }
427 }
338 }
428 }
339 }
429 }
crates/app/src/settings/notifications.rs +45 −36
@@ -9,10 +9,13 @@ use super::account::{
9 9 };
10 10 use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
11 11 use crate::app_state::AppState;
12 use crate::presence_follow::{MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF};
12 use crate::i18n::tr;
13 13 use crate::notify::NotificationCenter;
14 14 use crate::notify::rules::{Corner, Settings};
15 15 use crate::notify::sounds::AlertSound;
16 use crate::presence_follow::{
17 MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF,
18 };
16 19 use crate::theme;
17 20
18 21 type Accessor = fn(&mut Settings) -> &mut bool;
@@ -20,51 +23,51 @@ type SoundAccessor = fn(&mut Settings) -> &mut AlertSound;
20 23
21 24 struct Toggle {
22 25 id: &'static str,
23 title: &'static str,
24 detail: &'static str,
26 title_key: &'static str,
27 detail_key: Option<&'static str>,
25 28 field: Accessor,
26 29 }
27 30
28 31 const FLASH: Toggle = Toggle {
29 32 id: "settings-flash",
30 title: "Flash taskbar when notifications are received",
31 detail: "On new messages, until you open the window",
33 title_key: "settings.notifications.flash_taskbar",
34 detail_key: Some("settings.notifications.flash_taskbar_detail"),
32 35 field: |settings| &mut settings.flash,
33 36 };
34 37
35 38 const NOTIFICATION_SOUND: Toggle = Toggle {
36 39 id: "settings-notification-sound",
37 title: "Play sounds with notifications",
38 detail: "",
40 title_key: "settings.notifications.play_sounds",
41 detail_key: None,
39 42 field: |settings| &mut settings.sounds.notification_sound,
40 43 };
41 44
42 45 const URGENT_SOUND: Toggle = Toggle {
43 46 id: "settings-urgent-sound",
44 title: "Play sounds with urgent and priority contact notifications",
45 detail: "",
47 title_key: "settings.notifications.urgent_sounds",
48 detail_key: None,
46 49 field: |settings| &mut settings.sounds.urgent_sound,
47 50 };
48 51
49 52 const CALL_SOUNDS: [Toggle; 2] = [
50 53 Toggle {
51 54 id: "settings-call-sound",
52 title: "Play sounds with incoming calls, requests to join, and meeting start notifications",
53 detail: "",
55 title_key: "settings.notifications.call_sounds",
56 detail_key: None,
54 57 field: |settings| &mut settings.sounds.call_and_meeting_sound,
55 58 },
56 59 Toggle {
57 60 id: "settings-busy-sound",
58 title: "Play sounds when I'm busy or in a meeting",
59 detail: "",
61 title_key: "settings.notifications.busy_sounds",
62 detail_key: None,
60 63 field: |settings| &mut settings.sounds.sound_when_busy,
61 64 },
62 65 ];
63 66
64 67 const HIDE_IN_CALLS: Toggle = Toggle {
65 68 id: "settings-hide-in-calls",
66 title: "Hide notifications during calls and meetings",
67 detail: "No message toasts while a call is active",
69 title_key: "settings.notifications.hide_in_calls",
70 detail_key: Some("settings.notifications.hide_in_calls_detail"),
68 71 field: |settings| &mut settings.mute_in_calls,
69 72 };
70 73
@@ -85,12 +88,12 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
85 88 let test_center = center.clone();
86 89 v_flex()
87 90 .w_full()
88 .child(caption("APPEARANCE AND SOUND"))
91 .child(caption(tr("settings.caption.appearance_and_sound")))
89 92 .child(preview_toggle(app, account.show_preview))
90 93 .child(flash)
91 94 .child(control_row(
92 "Position on the screen",
93 "Corner of the main screen",
95 tr("settings.notifications.position"),
96 tr("settings.notifications.position_detail"),
94 97 select(
95 98 "settings-position",
96 99 corner.label(),
@@ -99,15 +102,17 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
99 102 ),
100 103 ))
101 104 .child(control_row(
102 "Test notification",
103 "Shows a toast with the settings above",
104 text_button("settings-test-notification", "Send test notification").on_click(
105 move |_, _, cx| {
106 test_center.update(cx, |center, cx| center.send_test_notification(cx))
107 },
108 ),
105 tr("settings.notifications.test"),
106 tr("settings.notifications.test_detail"),
107 text_button(
108 "settings-test-notification",
109 tr("settings.notifications.send_test"),
110 )
111 .on_click(move |_, _, cx| {
112 test_center.update(cx, |center, cx| center.send_test_notification(cx))
113 }),
109 114 ))
110 .child(caption("SOUND"))
115 .child(caption(tr("settings.caption.sound")))
111 116 .child(notification_sound)
112 117 .child(sound_row(
113 118 center,
@@ -115,7 +120,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
115 120 "settings-notification-sound-type",
116 121 "settings-notification-sound-preview",
117 122 ),
118 "Notification sound",
123 tr("settings.notifications.notification_sound"),
119 124 &AlertSound::NORMAL,
120 125 sounds.notification_sound_type,
121 126 sounds.notification_sound,
@@ -128,7 +133,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
128 133 "settings-urgent-sound-type",
129 134 "settings-urgent-sound-preview",
130 135 ),
131 "Urgent sound",
136 tr("settings.notifications.urgent_sound"),
132 137 &AlertSound::URGENT,
133 138 sounds.urgent_sound_type,
134 139 sounds.urgent_sound,
@@ -140,7 +145,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
140 145 app,
141 146 (
142 147 "settings-notification-preset",
143 "Teams and channels",
148 tr("settings.notifications.teams_channels"),
144 149 preset_detail(account.preset),
145 150 ),
146 151 &PRESETS,
@@ -150,7 +155,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
150 155 .child(caption("CHAT"))
151 156 .child(account_select(
152 157 app,
153 ("settings-chat-messages", "Chat message notifications", ""),
158 ("settings-chat-messages", tr("settings.notifications.chat_messages"), ""),
154 159 &CHAT_MESSAGES,
155 160 account.chat_messages,
156 161 ChatSettingChange::ChatMessages,
@@ -175,7 +180,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
175 180 ))
176 181 .child(account_select(
177 182 app,
178 ("settings-likes", "Likes and reactions", ""),
183 ("settings-likes", tr("settings.notifications.likes_reactions"), ""),
179 184 &ACTIVITY_OR_OFF,
180 185 account.likes,
181 186 ChatSettingChange::Likes,
@@ -185,7 +190,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
185 190 app,
186 191 (
187 192 "settings-meeting-chats",
188 "Meeting chat notifications",
193 tr("settings.notifications.meeting_chats"),
189 194 meeting_chats_detail(account.meeting_chats),
190 195 ),
191 196 &MEETING_CHATS,
@@ -228,7 +233,7 @@ fn preview_toggle(app: &Entity<AppState>, on: bool) -> Stateful<Div> {
228 233 let app = app.clone();
229 234 toggle_row(
230 235 "settings-preview",
231 "Show message preview",
236 tr("settings.notifications.show_preview"),
232 237 "Off: only \"New message\"",
233 238 theme::text_muted(),
234 239 on,
@@ -243,10 +248,14 @@ fn preview_toggle(app: &Entity<AppState>, on: bool) -> Stateful<Div> {
243 248 fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {
244 249 let center = center.clone();
245 250 let field = toggle.field;
251 let detail = toggle
252 .detail_key
253 .map(tr)
254 .unwrap_or_default();
246 255 toggle_row(
247 256 toggle.id,
248 toggle.title,
249 toggle.detail,
257 tr(toggle.title_key),
258 detail,
250 259 theme::text_muted(),
251 260 on,
252 261 )
@@ -277,7 +286,7 @@ fn corner_choices(center: &Entity<NotificationCenter>, current: Corner) -> Vec<C
277 286 fn sound_row(
278 287 center: &Entity<NotificationCenter>,
279 288 (id, preview_id): (&'static str, &'static str),
280 title: &'static str,
289 title: impl Into<SharedString>,
281 290 options: &'static [AlertSound],
282 291 current: AlertSound,
283 292 enabled: bool,
@@ -9,10 +9,13 @@ use super::account::{
9};
9};
10use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
10use super::rows::{Choice, caption, control_row, select, text_button, toggle_row};
11use crate::app_state::AppState;
11use crate::app_state::AppState;
12use crate::presence_follow::{MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF};
12use crate::i18n::tr;
13use crate::notify::NotificationCenter;
13use crate::notify::NotificationCenter;
14use crate::notify::rules::{Corner, Settings};
14use crate::notify::rules::{Corner, Settings};
15use crate::notify::sounds::AlertSound;
15use crate::notify::sounds::AlertSound;
16use crate::presence_follow::{
17 MANAGE_STATUS_NOTIFICATIONS, STATUS_NOTIFICATIONS_DESCRIPTION, TURN_OFF,
18};
16use crate::theme;
19use crate::theme;
17
20
18type Accessor = fn(&mut Settings) -> &mut bool;
21type Accessor = fn(&mut Settings) -> &mut bool;
@@ -20,51 +23,51 @@ type SoundAccessor = fn(&mut Settings) -> &mut AlertSound;
20
23
21struct Toggle {
24struct Toggle {
22 id: &'static str,
25 id: &'static str,
23 title: &'static str,
26 title_key: &'static str,
24 detail: &'static str,
27 detail_key: Option<&'static str>,
25 field: Accessor,
28 field: Accessor,
26}
29}
27
30
28const FLASH: Toggle = Toggle {
31const FLASH: Toggle = Toggle {
29 id: "settings-flash",
32 id: "settings-flash",
30 title: "Flash taskbar when notifications are received",
33 title_key: "settings.notifications.flash_taskbar",
31 detail: "On new messages, until you open the window",
34 detail_key: Some("settings.notifications.flash_taskbar_detail"),
32 field: |settings| &mut settings.flash,
35 field: |settings| &mut settings.flash,
33};
36};
34
37
35const NOTIFICATION_SOUND: Toggle = Toggle {
38const NOTIFICATION_SOUND: Toggle = Toggle {
36 id: "settings-notification-sound",
39 id: "settings-notification-sound",
37 title: "Play sounds with notifications",
40 title_key: "settings.notifications.play_sounds",
38 detail: "",
41 detail_key: None,
39 field: |settings| &mut settings.sounds.notification_sound,
42 field: |settings| &mut settings.sounds.notification_sound,
40};
43};
41
44
42const URGENT_SOUND: Toggle = Toggle {
45const URGENT_SOUND: Toggle = Toggle {
43 id: "settings-urgent-sound",
46 id: "settings-urgent-sound",
44 title: "Play sounds with urgent and priority contact notifications",
47 title_key: "settings.notifications.urgent_sounds",
45 detail: "",
48 detail_key: None,
46 field: |settings| &mut settings.sounds.urgent_sound,
49 field: |settings| &mut settings.sounds.urgent_sound,
47};
50};
48
51
49const CALL_SOUNDS: [Toggle; 2] = [
52const CALL_SOUNDS: [Toggle; 2] = [
50 Toggle {
53 Toggle {
51 id: "settings-call-sound",
54 id: "settings-call-sound",
52 title: "Play sounds with incoming calls, requests to join, and meeting start notifications",
55 title_key: "settings.notifications.call_sounds",
53 detail: "",
56 detail_key: None,
54 field: |settings| &mut settings.sounds.call_and_meeting_sound,
57 field: |settings| &mut settings.sounds.call_and_meeting_sound,
55 },
58 },
56 Toggle {
59 Toggle {
57 id: "settings-busy-sound",
60 id: "settings-busy-sound",
58 title: "Play sounds when I'm busy or in a meeting",
61 title_key: "settings.notifications.busy_sounds",
59 detail: "",
62 detail_key: None,
60 field: |settings| &mut settings.sounds.sound_when_busy,
63 field: |settings| &mut settings.sounds.sound_when_busy,
61 },
64 },
62];
65];
63
66
64const HIDE_IN_CALLS: Toggle = Toggle {
67const HIDE_IN_CALLS: Toggle = Toggle {
65 id: "settings-hide-in-calls",
68 id: "settings-hide-in-calls",
66 title: "Hide notifications during calls and meetings",
69 title_key: "settings.notifications.hide_in_calls",
67 detail: "No message toasts while a call is active",
70 detail_key: Some("settings.notifications.hide_in_calls_detail"),
68 field: |settings| &mut settings.mute_in_calls,
71 field: |settings| &mut settings.mute_in_calls,
69};
72};
70
73
@@ -85,12 +88,12 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
85 let test_center = center.clone();
88 let test_center = center.clone();
86 v_flex()
89 v_flex()
87 .w_full()
90 .w_full()
88 .child(caption("APPEARANCE AND SOUND"))
91 .child(caption(tr("settings.caption.appearance_and_sound")))
89 .child(preview_toggle(app, account.show_preview))
92 .child(preview_toggle(app, account.show_preview))
90 .child(flash)
93 .child(flash)
91 .child(control_row(
94 .child(control_row(
92 "Position on the screen",
95 tr("settings.notifications.position"),
93 "Corner of the main screen",
96 tr("settings.notifications.position_detail"),
94 select(
97 select(
95 "settings-position",
98 "settings-position",
96 corner.label(),
99 corner.label(),
@@ -99,15 +102,17 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
99 ),
102 ),
100 ))
103 ))
101 .child(control_row(
104 .child(control_row(
102 "Test notification",
105 tr("settings.notifications.test"),
103 "Shows a toast with the settings above",
106 tr("settings.notifications.test_detail"),
104 text_button("settings-test-notification", "Send test notification").on_click(
107 text_button(
105 move |_, _, cx| {
108 "settings-test-notification",
106 test_center.update(cx, |center, cx| center.send_test_notification(cx))
109 tr("settings.notifications.send_test"),
107 },
110 )
108 ),
111 .on_click(move |_, _, cx| {
112 test_center.update(cx, |center, cx| center.send_test_notification(cx))
113 }),
109 ))
114 ))
110 .child(caption("SOUND"))
115 .child(caption(tr("settings.caption.sound")))
111 .child(notification_sound)
116 .child(notification_sound)
112 .child(sound_row(
117 .child(sound_row(
113 center,
118 center,
@@ -115,7 +120,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
115 "settings-notification-sound-type",
120 "settings-notification-sound-type",
116 "settings-notification-sound-preview",
121 "settings-notification-sound-preview",
117 ),
122 ),
118 "Notification sound",
123 tr("settings.notifications.notification_sound"),
119 &AlertSound::NORMAL,
124 &AlertSound::NORMAL,
120 sounds.notification_sound_type,
125 sounds.notification_sound_type,
121 sounds.notification_sound,
126 sounds.notification_sound,
@@ -128,7 +133,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
128 "settings-urgent-sound-type",
133 "settings-urgent-sound-type",
129 "settings-urgent-sound-preview",
134 "settings-urgent-sound-preview",
130 ),
135 ),
131 "Urgent sound",
136 tr("settings.notifications.urgent_sound"),
132 &AlertSound::URGENT,
137 &AlertSound::URGENT,
133 sounds.urgent_sound_type,
138 sounds.urgent_sound_type,
134 sounds.urgent_sound,
139 sounds.urgent_sound,
@@ -140,7 +145,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
140 app,
145 app,
141 (
146 (
142 "settings-notification-preset",
147 "settings-notification-preset",
143 "Teams and channels",
148 tr("settings.notifications.teams_channels"),
144 preset_detail(account.preset),
149 preset_detail(account.preset),
145 ),
150 ),
146 &PRESETS,
151 &PRESETS,
@@ -150,7 +155,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
150 .child(caption("CHAT"))
155 .child(caption("CHAT"))
151 .child(account_select(
156 .child(account_select(
152 app,
157 app,
153 ("settings-chat-messages", "Chat message notifications", ""),
158 ("settings-chat-messages", tr("settings.notifications.chat_messages"), ""),
154 &CHAT_MESSAGES,
159 &CHAT_MESSAGES,
155 account.chat_messages,
160 account.chat_messages,
156 ChatSettingChange::ChatMessages,
161 ChatSettingChange::ChatMessages,
@@ -175,7 +180,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
175 ))
180 ))
176 .child(account_select(
181 .child(account_select(
177 app,
182 app,
178 ("settings-likes", "Likes and reactions", ""),
183 ("settings-likes", tr("settings.notifications.likes_reactions"), ""),
179 &ACTIVITY_OR_OFF,
184 &ACTIVITY_OR_OFF,
180 account.likes,
185 account.likes,
181 ChatSettingChange::Likes,
186 ChatSettingChange::Likes,
@@ -185,7 +190,7 @@ pub fn render(center: &Entity<NotificationCenter>, app: &Entity<AppState>, cx: &
185 app,
190 app,
186 (
191 (
187 "settings-meeting-chats",
192 "settings-meeting-chats",
188 "Meeting chat notifications",
193 tr("settings.notifications.meeting_chats"),
189 meeting_chats_detail(account.meeting_chats),
194 meeting_chats_detail(account.meeting_chats),
190 ),
195 ),
191 &MEETING_CHATS,
196 &MEETING_CHATS,
@@ -228,7 +233,7 @@ fn preview_toggle(app: &Entity<AppState>, on: bool) -> Stateful<Div> {
228 let app = app.clone();
233 let app = app.clone();
229 toggle_row(
234 toggle_row(
230 "settings-preview",
235 "settings-preview",
231 "Show message preview",
236 tr("settings.notifications.show_preview"),
232 "Off: only \"New message\"",
237 "Off: only \"New message\"",
233 theme::text_muted(),
238 theme::text_muted(),
234 on,
239 on,
@@ -243,10 +248,14 @@ fn preview_toggle(app: &Entity<AppState>, on: bool) -> Stateful<Div> {
243fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {
248fn toggle_element(center: &Entity<NotificationCenter>, toggle: &Toggle, on: bool) -> Stateful<Div> {
244 let center = center.clone();
249 let center = center.clone();
245 let field = toggle.field;
250 let field = toggle.field;
251 let detail = toggle
252 .detail_key
253 .map(tr)
254 .unwrap_or_default();
246 toggle_row(
255 toggle_row(
247 toggle.id,
256 toggle.id,
248 toggle.title,
257 tr(toggle.title_key),
249 toggle.detail,
258 detail,
250 theme::text_muted(),
259 theme::text_muted(),
251 on,
260 on,
252 )
261 )
@@ -277,7 +286,7 @@ fn corner_choices(center: &Entity<NotificationCenter>, current: Corner) -> Vec<C
277fn sound_row(
286fn sound_row(
278 center: &Entity<NotificationCenter>,
287 center: &Entity<NotificationCenter>,
279 (id, preview_id): (&'static str, &'static str),
288 (id, preview_id): (&'static str, &'static str),
280 title: &'static str,
289 title: impl Into<SharedString>,
281 options: &'static [AlertSound],
290 options: &'static [AlertSound],
282 current: AlertSound,
291 current: AlertSound,
283 enabled: bool,
292 enabled: bool,
crates/app/src/views/add_people_dialog.rs +3 −2
@@ -9,6 +9,7 @@ use gpui_kit::*;
9 9 use store::MemberRecord;
10 10
11 11 use super::new_chat::{NewChatDraft, Pick};
12 use crate::i18n::tr;
12 13 use crate::app_state::AppState;
13 14 use crate::theme;
14 15
@@ -242,13 +243,13 @@ pub fn open_add_people(
242 243 let footer = DialogFooter::new()
243 244 .child(
244 245 Button::new("add-people-cancel")
245 .label("Cancel")
246 .label(tr("common.cancel"))
246 247 .on_click(|_, window, cx| window.close_dialog(cx)),
247 248 )
248 249 .child(
249 250 Button::new("add-people-confirm")
250 251 .primary()
251 .label("Add")
252 .label(tr("common.add"))
252 253 .disabled(!can_add)
253 254 .on_click(move |_, window, cx| {
254 255 submit_form.update(cx, |form, cx| form.submit(window, cx));
@@ -9,6 +9,7 @@ use gpui_kit::*;
9use store::MemberRecord;
9use store::MemberRecord;
10
10
11use super::new_chat::{NewChatDraft, Pick};
11use super::new_chat::{NewChatDraft, Pick};
12use crate::i18n::tr;
12use crate::app_state::AppState;
13use crate::app_state::AppState;
13use crate::theme;
14use crate::theme;
14
15
@@ -242,13 +243,13 @@ pub fn open_add_people(
242 let footer = DialogFooter::new()
243 let footer = DialogFooter::new()
243 .child(
244 .child(
244 Button::new("add-people-cancel")
245 Button::new("add-people-cancel")
245 .label("Cancel")
246 .label(tr("common.cancel"))
246 .on_click(|_, window, cx| window.close_dialog(cx)),
247 .on_click(|_, window, cx| window.close_dialog(cx)),
247 )
248 )
248 .child(
249 .child(
249 Button::new("add-people-confirm")
250 Button::new("add-people-confirm")
250 .primary()
251 .primary()
251 .label("Add")
252 .label(tr("common.add"))
252 .disabled(!can_add)
253 .disabled(!can_add)
253 .on_click(move |_, window, cx| {
254 .on_click(move |_, window, cx| {
254 submit_form.update(cx, |form, cx| form.submit(window, cx));
255 submit_form.update(cx, |form, cx| form.submit(window, cx));
crates/app/src/views/calendar_event_dialog.rs added +210 −0
@@ -0,0 +1,210 @@
1 use chatsvc::{CalendarEvent, ResponseType, join_info_text};
2 use chrono::{Local, Offset};
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::Sizable as _;
5 use gpui_kit::component::button::{Button, ButtonVariants as _};
6 use gpui_kit::component::dialog::{Dialog, DialogFooter};
7 use gpui_kit::component::menu::DropdownMenu as _;
8 use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
9 use gpui_kit::*;
10
11 use super::rsvp_menu::rsvp_menu;
12 use crate::i18n::tr;
13 use crate::app_state::AppState;
14 use crate::call::week_grid::is_effective_all_day;
15 use crate::theme;
16
17 const DIALOG_WIDTH: f32 = 440.;
18 const FIELD_GAP: f32 = 12.;
19 const LABEL_SIZE: f32 = 12.;
20 const COPY_JOIN_INFO: &str = "Copy join info";
21
22 fn when_label(event: &CalendarEvent) -> String {
23 let offset = Local::now().offset().fix();
24 if is_effective_all_day(event, offset) {
25 let start = event.start.with_timezone(&offset).date_naive();
26 let end = event.end.with_timezone(&offset).date_naive();
27 if end > start + chrono::Duration::days(1) {
28 return format!(
29 "All day · {} – {}",
30 start.format("%a, %b %-d"),
31 (end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
32 );
33 }
34 return format!("All day · {}", start.format("%a, %b %-d, %Y"));
35 }
36 let start = event.start.with_timezone(&offset);
37 let end = event.end.with_timezone(&offset);
38 if start.date_naive() == end.date_naive() {
39 format!(
40 "{} · {} – {}",
41 start.format("%a, %b %-d, %Y"),
42 start.format(app_base::format::clock_format()),
43 end.format(app_base::format::clock_format())
44 )
45 } else {
46 format!(
47 "{} {} – {} {}",
48 start.format("%a, %b %-d"),
49 start.format(app_base::format::clock_format()),
50 end.format("%a, %b %-d, %Y"),
51 end.format(app_base::format::clock_format())
52 )
53 }
54 }
55
56 fn source_label(event: &CalendarEvent) -> String {
57 let mut sources = event.sources.clone();
58 if sources.is_empty() {
59 sources.push(event.source);
60 }
61 sources.sort_by_key(|source| source.label());
62 sources.dedup();
63 sources
64 .iter()
65 .map(|source| source.label())
66 .collect::<Vec<_>>()
67 .join(" + ")
68 }
69
70 fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {
71 v_flex()
72 .gap(px(2.))
73 .child(
74 div()
75 .text_size(px(LABEL_SIZE))
76 .text_color(theme::text_muted())
77 .child(label.to_owned()),
78 )
79 .child(
80 div()
81 .text_size(px(14.))
82 .text_color(theme::text())
83 .child(value.into()),
84 )
85 }
86
87 pub fn open_calendar_event(
88 state: Entity<AppState>,
89 event: CalendarEvent,
90 window: &mut Window,
91 cx: &mut App,
92 ) {
93 let send_response = state.read(cx).rsvp_send_response;
94 // Show Join whenever a Teams link exists — not only inside the join window.
95 let can_join = event.online && !event.cancelled && event.join_url.is_some();
96 let subject = if event.cancelled {
97 format!("Canceled: {}", event.subject)
98 } else if event.subject.is_empty() {
99 "(No title)".to_owned()
100 } else {
101 event.subject.clone()
102 };
103 let when = when_label(&event);
104 let source = source_label(&event);
105 let organizer = event
106 .organizer_name
107 .clone()
108 .or_else(|| event.organizer_address.clone());
109 let join_url = event.join_url.clone();
110 let dial_in = event.dial_in.clone();
111 let thread_id = event.thread_id.clone();
112 let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
113 let response = event.response;
114 let event_key = event.object_id.clone();
115 let meeting_title = event.subject.clone();
116 let online = event.online;
117
118 window.open_dialog(cx, move |dialog: Dialog, _, _| {
119 let delete_state = state.clone();
120 let delete_key = event_key.clone();
121 let mut footer = DialogFooter::new()
122 .child(
123 Button::new("calendar-event-delete")
124 .danger()
125 .label(tr("common.delete"))
126 .on_click(move |_, window, cx| {
127 delete_state
128 .update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));
129 window.close_dialog(cx);
130 }),
131 )
132 .child(
133 Button::new("calendar-event-close")
134 .label(tr("common.close"))
135 .on_click(|_, window, cx| window.close_dialog(cx)),
136 );
137 if can_rsvp {
138 let menu_state = state.clone();
139 let menu_key = event_key.clone();
140 footer = footer.child(
141 Button::new("calendar-event-rsvp")
142 .label("RSVP")
143 .dropdown_menu(move |menu, _, _| {
144 rsvp_menu(menu, &menu_state, &menu_key, response, send_response)
145 }),
146 );
147 }
148 if thread_id.is_some() {
149 let chat_state = state.clone();
150 let chat_thread = thread_id.clone();
151 footer = footer.child(Button::new("calendar-event-chat").label(tr("common.chat")).on_click(
152 move |_, window, cx| {
153 chat_state.update(cx, |state, cx| {
154 state.open_meeting_chat(chat_thread.as_deref(), cx)
155 });
156 window.close_dialog(cx);
157 },
158 ));
159 }
160 if can_join {
161 let join_state = state.clone();
162 let url = join_url.clone();
163 let title = meeting_title.clone();
164 footer = footer.child(
165 Button::new("calendar-event-join")
166 .primary()
167 .label(tr("common.join"))
168 .on_click(move |_, window, cx| {
169 join_state.update(cx, |state, cx| {
170 state.join_calendar_meeting(url.as_deref(), &title, cx)
171 });
172 window.close_dialog(cx);
173 }),
174 );
175 }
176
177 let mut body = v_flex()
178 .gap(px(FIELD_GAP))
179 .child(detail_row("When", when.clone()))
180 .child(detail_row("Calendar", source.clone()));
181 if let Some(name) = organizer.clone() {
182 body = body.child(detail_row("Organizer", name));
183 }
184 if let Some(url) = join_url.clone().filter(|_| online) {
185 let info = join_info_text(&url, dial_in.as_ref());
186 body = body.child(
187 v_flex()
188 .gap(px(6.))
189 .child(detail_row("Join link", url))
190 .child(
191 h_flex().child(
192 Button::new("calendar-event-copy-join")
193 .small()
194 .label(COPY_JOIN_INFO)
195 .icon(IconName::Copy)
196 .on_click(move |_, _, cx| {
197 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
198 }),
199 ),
200 ),
201 );
202 }
203
204 dialog
205 .title(subject.clone())
206 .w(px(DIALOG_WIDTH))
207 .child(body)
208 .footer(footer)
209 });
210 }
@@ -0,0 +1,210 @@
1use chatsvc::{CalendarEvent, ResponseType, join_info_text};
2use chrono::{Local, Offset};
3use gpui_kit::assets::IconName;
4use gpui_kit::component::Sizable as _;
5use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::dialog::{Dialog, DialogFooter};
7use gpui_kit::component::menu::DropdownMenu as _;
8use gpui_kit::component::{WindowExt as _, h_flex, v_flex};
9use gpui_kit::*;
10
11use super::rsvp_menu::rsvp_menu;
12use crate::i18n::tr;
13use crate::app_state::AppState;
14use crate::call::week_grid::is_effective_all_day;
15use crate::theme;
16
17const DIALOG_WIDTH: f32 = 440.;
18const FIELD_GAP: f32 = 12.;
19const LABEL_SIZE: f32 = 12.;
20const COPY_JOIN_INFO: &str = "Copy join info";
21
22fn when_label(event: &CalendarEvent) -> String {
23 let offset = Local::now().offset().fix();
24 if is_effective_all_day(event, offset) {
25 let start = event.start.with_timezone(&offset).date_naive();
26 let end = event.end.with_timezone(&offset).date_naive();
27 if end > start + chrono::Duration::days(1) {
28 return format!(
29 "All day · {} – {}",
30 start.format("%a, %b %-d"),
31 (end - chrono::Duration::days(1)).format("%a, %b %-d, %Y")
32 );
33 }
34 return format!("All day · {}", start.format("%a, %b %-d, %Y"));
35 }
36 let start = event.start.with_timezone(&offset);
37 let end = event.end.with_timezone(&offset);
38 if start.date_naive() == end.date_naive() {
39 format!(
40 "{} · {} – {}",
41 start.format("%a, %b %-d, %Y"),
42 start.format(app_base::format::clock_format()),
43 end.format(app_base::format::clock_format())
44 )
45 } else {
46 format!(
47 "{} {} – {} {}",
48 start.format("%a, %b %-d"),
49 start.format(app_base::format::clock_format()),
50 end.format("%a, %b %-d, %Y"),
51 end.format(app_base::format::clock_format())
52 )
53 }
54}
55
56fn source_label(event: &CalendarEvent) -> String {
57 let mut sources = event.sources.clone();
58 if sources.is_empty() {
59 sources.push(event.source);
60 }
61 sources.sort_by_key(|source| source.label());
62 sources.dedup();
63 sources
64 .iter()
65 .map(|source| source.label())
66 .collect::<Vec<_>>()
67 .join(" + ")
68}
69
70fn detail_row(label: &str, value: impl Into<SharedString>) -> Div {
71 v_flex()
72 .gap(px(2.))
73 .child(
74 div()
75 .text_size(px(LABEL_SIZE))
76 .text_color(theme::text_muted())
77 .child(label.to_owned()),
78 )
79 .child(
80 div()
81 .text_size(px(14.))
82 .text_color(theme::text())
83 .child(value.into()),
84 )
85}
86
87pub fn open_calendar_event(
88 state: Entity<AppState>,
89 event: CalendarEvent,
90 window: &mut Window,
91 cx: &mut App,
92) {
93 let send_response = state.read(cx).rsvp_send_response;
94 // Show Join whenever a Teams link exists — not only inside the join window.
95 let can_join = event.online && !event.cancelled && event.join_url.is_some();
96 let subject = if event.cancelled {
97 format!("Canceled: {}", event.subject)
98 } else if event.subject.is_empty() {
99 "(No title)".to_owned()
100 } else {
101 event.subject.clone()
102 };
103 let when = when_label(&event);
104 let source = source_label(&event);
105 let organizer = event
106 .organizer_name
107 .clone()
108 .or_else(|| event.organizer_address.clone());
109 let join_url = event.join_url.clone();
110 let dial_in = event.dial_in.clone();
111 let thread_id = event.thread_id.clone();
112 let can_rsvp = event.response != ResponseType::Organizer && event.organizer_name.is_some();
113 let response = event.response;
114 let event_key = event.object_id.clone();
115 let meeting_title = event.subject.clone();
116 let online = event.online;
117
118 window.open_dialog(cx, move |dialog: Dialog, _, _| {
119 let delete_state = state.clone();
120 let delete_key = event_key.clone();
121 let mut footer = DialogFooter::new()
122 .child(
123 Button::new("calendar-event-delete")
124 .danger()
125 .label(tr("common.delete"))
126 .on_click(move |_, window, cx| {
127 delete_state
128 .update(cx, |state, cx| state.delete_calendar_event(&delete_key, cx));
129 window.close_dialog(cx);
130 }),
131 )
132 .child(
133 Button::new("calendar-event-close")
134 .label(tr("common.close"))
135 .on_click(|_, window, cx| window.close_dialog(cx)),
136 );
137 if can_rsvp {
138 let menu_state = state.clone();
139 let menu_key = event_key.clone();
140 footer = footer.child(
141 Button::new("calendar-event-rsvp")
142 .label("RSVP")
143 .dropdown_menu(move |menu, _, _| {
144 rsvp_menu(menu, &menu_state, &menu_key, response, send_response)
145 }),
146 );
147 }
148 if thread_id.is_some() {
149 let chat_state = state.clone();
150 let chat_thread = thread_id.clone();
151 footer = footer.child(Button::new("calendar-event-chat").label(tr("common.chat")).on_click(
152 move |_, window, cx| {
153 chat_state.update(cx, |state, cx| {
154 state.open_meeting_chat(chat_thread.as_deref(), cx)
155 });
156 window.close_dialog(cx);
157 },
158 ));
159 }
160 if can_join {
161 let join_state = state.clone();
162 let url = join_url.clone();
163 let title = meeting_title.clone();
164 footer = footer.child(
165 Button::new("calendar-event-join")
166 .primary()
167 .label(tr("common.join"))
168 .on_click(move |_, window, cx| {
169 join_state.update(cx, |state, cx| {
170 state.join_calendar_meeting(url.as_deref(), &title, cx)
171 });
172 window.close_dialog(cx);
173 }),
174 );
175 }
176
177 let mut body = v_flex()
178 .gap(px(FIELD_GAP))
179 .child(detail_row("When", when.clone()))
180 .child(detail_row("Calendar", source.clone()));
181 if let Some(name) = organizer.clone() {
182 body = body.child(detail_row("Organizer", name));
183 }
184 if let Some(url) = join_url.clone().filter(|_| online) {
185 let info = join_info_text(&url, dial_in.as_ref());
186 body = body.child(
187 v_flex()
188 .gap(px(6.))
189 .child(detail_row("Join link", url))
190 .child(
191 h_flex().child(
192 Button::new("calendar-event-copy-join")
193 .small()
194 .label(COPY_JOIN_INFO)
195 .icon(IconName::Copy)
196 .on_click(move |_, _, cx| {
197 cx.write_to_clipboard(ClipboardItem::new_string(info.clone()))
198 }),
199 ),
200 ),
201 );
202 }
203
204 dialog
205 .title(subject.clone())
206 .w(px(DIALOG_WIDTH))
207 .child(body)
208 .footer(footer)
209 });
210}
crates/app/src/views/calendar_view.rs +228 −59
@@ -1,3 +1,5 @@
1 use std::time::Duration;
2
1 3 use app_base::format::{self, clock_format};
2 4 use chatsvc::{CalendarEvent, ResponseType, join_info_text};
3 5 use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};
@@ -10,13 +12,19 @@ use gpui_kit::prelude::FluentBuilder as _;
10 12 use gpui_kit::*;
11 13
12 14 use super::calendar_date_picker::date_picker_button;
15 use super::calendar_event_dialog::open_calendar_event;
13 16 use super::calendar_month::month_grid;
14 use super::meeting_proposal_card::meeting_proposal_cards;
15 use super::rsvp_menu::rsvp_menu;
17 use super::calendar_picker;
16 18 use super::join_dialog::open_join_with_id;
17 19 use super::new_meeting_dialog::open_new_meeting;
20 use super::rsvp_menu::rsvp_menu;
21 use super::scroll_edge::scroll_offset;
22 use crate::i18n::tr;
18 23 use crate::app_state::AppState;
19 use crate::call::join_available;
24 use crate::call::calendar_now::{
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
26 now_scroll_offset_y, offset_differs, shows_hour_grid,
27 };
20 28 use crate::call::week_grid::{
21 29 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
22 30 };
@@ -30,7 +38,6 @@ const HEADER_HEIGHT: f32 = 52.;
30 38 const DAY_HEADER_HEIGHT: f32 = 56.;
31 39 const ALL_DAY_HEIGHT: f32 = 26.;
32 40 const BLOCK_GAP: f32 = 2.;
33 const FIRST_VISIBLE_HOUR: f32 = 8.;
34 41 const CANCELED_PREFIX: &str = "Canceled: ";
35 42 const COPY_JOIN_INFO: &str = "Copy join info";
36 43 const COMPACT_HEADER_WIDTH: f32 = 960.;
@@ -42,28 +49,132 @@ const HATCH_GAP: f32 = 2.5;
42 49 const SMALL_TITLE_HEIGHT: f32 = 20.;
43 50 const TODAY_MARK_HEIGHT: f32 = 3.;
44 51 const NOW_DOT_SIZE: f32 = 8.;
52 const CLOCK_TICK: Duration = Duration::from_secs(30);
53 const CHROME_HEIGHT: f32 = HEADER_HEIGHT + DAY_HEADER_HEIGHT + ALL_DAY_HEIGHT;
45 54
46 55 pub struct CalendarView {
47 56 state: Entity<AppState>,
48 57 scroll: ScrollHandle,
49 scrolled_to_morning: bool,
58 follow_now: FollowNow,
59 seen_scroll_to_now: u64,
60 last_programmatic_offset: f32,
61 skip_manual_check: bool,
62 clock_running: bool,
50 63 _observation: Subscription,
51 _agent_observation: Option<Subscription>,
52 64 }
53 65
54 66 impl CalendarView {
55 67 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
56 68 let observation = cx.observe(&state, |_, _, cx| cx.notify());
57 let agent_observation = crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
58 69 CalendarView {
59 70 state,
60 71 scroll: ScrollHandle::new(),
61 scrolled_to_morning: false,
72 follow_now: FollowNow { active: true },
73 seen_scroll_to_now: 0,
74 last_programmatic_offset: 0.,
75 skip_manual_check: false,
76 clock_running: false,
62 77 _observation: observation,
63 _agent_observation: agent_observation,
64 78 }
65 79 }
66 80
81 fn grid_viewport_height(window: &Window) -> f32 {
82 (f32::from(window.viewport_size().height) - CHROME_HEIGHT).max(DEFAULT_GRID_VIEWPORT * 0.5)
83 }
84
85 fn align_scroll_to_now(&mut self, window: &Window) {
86 let local = Local::now();
87 let offset = now_scroll_offset_y(
88 local.hour(),
89 local.minute(),
90 HOUR_HEIGHT,
91 Self::grid_viewport_height(window),
92 NOW_BIAS_FRACTION,
93 );
94 self.scroll.set_offset(point(px(0.), px(offset)));
95 self.last_programmatic_offset = offset;
96 self.skip_manual_check = true;
97 }
98
99 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
100 let (scroll_to_now, span, today_visible) = {
101 let state = self.state.read(cx);
102 let start = state.calendar_start();
103 let today = Local::now().date_naive();
104 let today_visible = start <= today
105 && today < start + chrono::Duration::days(state.calendar_week.span.days());
106 (
107 state.calendar_scroll_to_now,
108 state.calendar_week.span,
109 today_visible,
110 )
111 };
112 if !shows_hour_grid(span) {
113 self.stop_clock();
114 return;
115 }
116 self.ensure_clock(cx);
117 if scroll_to_now != self.seen_scroll_to_now {
118 self.seen_scroll_to_now = scroll_to_now;
119 self.follow_now.request_align();
120 }
121 if self.skip_manual_check {
122 self.skip_manual_check = false;
123 } else if self.follow_now.active
124 && offset_differs(
125 f32::from(scroll_offset(&self.scroll).y),
126 self.last_programmatic_offset,
127 MANUAL_SCROLL_EPSILON,
128 )
129 {
130 self.follow_now.note_manual_scroll();
131 }
132 if self.follow_now.should_follow(today_visible) {
133 self.align_scroll_to_now(window);
134 }
135 }
136
137 fn ensure_clock(&mut self, cx: &mut Context<Self>) {
138 if self.clock_running {
139 return;
140 }
141 self.clock_running = true;
142 cx.spawn(async move |this, cx| {
143 loop {
144 cx.background_executor().timer(CLOCK_TICK).await;
145 let keep = this
146 .update(cx, |view, cx| {
147 let span = view.state.read(cx).calendar_week.span;
148 if !shows_hour_grid(span) {
149 view.clock_running = false;
150 return false;
151 }
152 cx.notify();
153 true
154 })
155 .unwrap_or(false);
156 if !keep {
157 break;
158 }
159 }
160 })
161 .detach();
162 }
163
164 fn stop_clock(&mut self) {
165 self.clock_running = false;
166 }
167
168 fn on_grid_scroll_wheel(
169 &mut self,
170 _event: &ScrollWheelEvent,
171 _window: &mut Window,
172 cx: &mut Context<Self>,
173 ) {
174 self.follow_now.note_manual_scroll();
175 cx.notify();
176 }
177
67 178 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
68 179 let span_state = self.state.clone();
69 180 let label = |text: &'static str| (!compact).then_some(text);
@@ -123,19 +234,17 @@ impl CalendarView {
123 234 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
124 235 }),
125 236 )
126 .child(
127 h_flex().flex_1().min_w_0().child(date_picker_button(
128 &self.state,
129 span.title(start),
130 start,
131 span.days(),
132 if span == CalendarSpan::Month {
133 month_shown(start)
134 } else {
135 start
136 },
137 )),
138 )
237 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
238 &self.state,
239 span.title(start),
240 start,
241 span.days(),
242 if span == CalendarSpan::Month {
243 month_shown(start)
244 } else {
245 start
246 },
247 )))
139 248 .child(
140 249 Button::new("calendar-span")
141 250 .small()
@@ -240,7 +349,12 @@ impl CalendarView {
240 349 }))
241 350 }
242 351
243 fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {
352 fn all_day_row(
353 &self,
354 days: &[WeekDay],
355 events: &[CalendarEvent],
356 send_response: bool,
357 ) -> Option<Div> {
244 358 if days.iter().all(|day| day.all_day.is_empty()) {
245 359 return None;
246 360 }
@@ -259,16 +373,36 @@ impl CalendarView {
259 373 .border_l_1()
260 374 .border_color(theme::border())
261 375 .children(day.all_day.iter().map(|&index| {
376 let event = events[index].clone();
377 let open_state = self.state.clone();
378 let (menu_state, menu_event) = (self.state.clone(), event.clone());
379 // Day-qualified id: multi-day all-day chips share object_id.
262 380 div()
381 .id(SharedString::from(format!(
382 "calendar-all-day-{}-{}",
383 event.object_id, day.date
384 )))
263 385 .h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
264 386 .px(px(6.))
265 387 .flex()
266 388 .items_center()
267 389 .rounded(px(4.))
268 .bg(event_fill(event_look(&events[index])))
390 .bg(event_fill(event_look(&event)))
269 391 .text_size(px(12.))
270 392 .truncate()
271 .child(event_title(&events[index]))
393 .cursor_pointer()
394 .child(event_title(&event))
395 .on_click(move |_, window, cx| {
396 open_calendar_event(
397 open_state.clone(),
398 event.clone(),
399 window,
400 cx,
401 );
402 })
403 .context_menu(move |menu, _, _| {
404 event_menu(menu, &menu_state, &menu_event, send_response)
405 })
272 406 }))
273 407 })),
274 408 )
@@ -278,7 +412,7 @@ impl CalendarView {
278 412 &self,
279 413 block: &WeekBlock,
280 414 event: &CalendarEvent,
281 now: DateTime<Utc>,
415 day: NaiveDate,
282 416 send_response: bool,
283 417 ) -> impl IntoElement {
284 418 let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
@@ -289,11 +423,10 @@ impl CalendarView {
289 423 let compact = height < 36.;
290 424 let small = height < SMALL_TITLE_HEIGHT;
291 425 let look = event_look(event);
292 let can_join = event.online
293 && !event.cancelled
294 && event.join_url.is_some()
295 && join_available(event.start, event.end, now);
296 let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());
426 // Join on the block whenever a Teams link exists (same as detail dialog).
427 let can_join = event.online && !event.cancelled && event.join_url.is_some();
428 let open_state = self.state.clone();
429 let open_event = event.clone();
297 430 let (menu_state, menu_event) = (self.state.clone(), event.clone());
298 431 let (join_state, join_url, subject) = (
299 432 self.state.clone(),
@@ -304,10 +437,11 @@ impl CalendarView {
304 437 EventLook::Busy => (theme::text(), theme::text_soft()),
305 438 EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
306 439 };
440 // Day-qualified id: overnight / multi-day spans reuse object_id per column.
307 441 div()
308 442 .id(SharedString::from(format!(
309 "calendar-event-{}",
310 event.object_id
443 "calendar-event-{}-{}",
444 event.object_id, day
311 445 )))
312 446 .absolute()
313 447 .top(px(top))
@@ -359,12 +493,12 @@ impl CalendarView {
359 493 block.child(
360 494 div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
361 495 Button::new(SharedString::from(format!(
362 "calendar-join-{}",
363 event.object_id
496 "calendar-join-{}-{}",
497 event.object_id, day
364 498 )))
365 499 .xsmall()
366 500 .primary()
367 .label("Join")
501 .label(tr("common.join"))
368 502 .on_click(move |_, _, cx| {
369 503 cx.stop_propagation();
370 504 join_state.update(cx, |state, cx| {
@@ -379,10 +513,8 @@ impl CalendarView {
379 513 )
380 514 }),
381 515 )
382 .on_click(move |_, _, cx| {
383 open_state.update(cx, |state, cx| {
384 state.open_meeting_chat(thread_id.as_deref(), cx)
385 });
516 .on_click(move |_, window, cx| {
517 open_calendar_event(open_state.clone(), open_event.clone(), window, cx);
386 518 })
387 519 .context_menu(move |menu, _, _| {
388 520 event_menu(menu, &menu_state, &menu_event, send_response)
@@ -396,6 +528,7 @@ impl CalendarView {
396 528 today: NaiveDate,
397 529 now: DateTime<Utc>,
398 530 send_response: bool,
531 cx: &mut Context<Self>,
399 532 ) -> impl IntoElement {
400 533 let total_height = 24. * HOUR_HEIGHT;
401 534 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
@@ -409,6 +542,7 @@ impl CalendarView {
409 542 .min_h_0()
410 543 .overflow_y_scroll()
411 544 .track_scroll(&self.scroll)
545 .on_scroll_wheel(cx.listener(Self::on_grid_scroll_wheel))
412 546 .child(
413 547 h_flex()
414 548 .h(px(total_height))
@@ -457,7 +591,7 @@ impl CalendarView {
457 591 self.event_block(
458 592 block,
459 593 &events[block.event_index],
460 now,
594 day.date,
461 595 send_response,
462 596 )
463 597 }))
@@ -566,21 +700,40 @@ fn status_bar(look: EventLook) -> Option<Div> {
566 700 }
567 701
568 702 fn event_title(event: &CalendarEvent) -> String {
569 if event.cancelled {
703 let subject = if event.cancelled {
570 704 format!("{CANCELED_PREFIX}{}", event.subject)
571 705 } else {
572 706 event.subject.clone()
707 };
708 let label = source_label(event);
709 if label.is_empty() {
710 subject
711 } else {
712 format!("{subject} · {label}")
573 713 }
574 714 }
575 715
716 fn source_label(event: &CalendarEvent) -> String {
717 let mut sources = event.sources.clone();
718 if sources.is_empty() {
719 sources.push(event.source);
720 }
721 sources.sort_by_key(|source| source.label());
722 sources.dedup();
723 if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
724 return String::new();
725 }
726 sources
727 .iter()
728 .map(|source| source.label())
729 .collect::<Vec<_>>()
730 .join("+")
731 }
732
576 733 impl Render for CalendarView {
577 734 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
578 735 let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
579 if !self.scrolled_to_morning {
580 self.scrolled_to_morning = true;
581 self.scroll
582 .set_offset(point(px(0.), px(-FIRST_VISIBLE_HOUR * HOUR_HEIGHT)));
583 }
736 self.sync_follow_from_state(window, cx);
584 737 let state = self.state.read(cx);
585 738 let start = state.calendar_start();
586 739 let events = state.calendar_week.events.clone();
@@ -590,7 +743,8 @@ impl Render for CalendarView {
590 743 let days = week_days(&events, start, span.days(), offset);
591 744 let today = Local::now().date_naive();
592 745 let now = Utc::now();
593 v_flex()
746 let show_picker = !compact;
747 h_flex()
594 748 .debug_selector(|| "shell/islands/calendar".into())
595 749 .flex_1()
596 750 .w_full()
@@ -599,17 +753,32 @@ impl Render for CalendarView {
599 753 .rounded(px(10.))
600 754 .bg(theme::surface())
601 755 .overflow_hidden()
602 .child(self.header(start, span, compact))
603 .children(meeting_proposal_cards(cx))
604 .map(|calendar| {
605 if span == CalendarSpan::Month {
606 calendar.child(month_grid(&self.state, start, &days, &events, today, offset))
607 } else {
608 calendar
609 .child(self.day_headers(&days, today))
610 .children(self.all_day_row(&days, &events))
611 .child(self.grid(&days, &events, today, now, send_response))
612 }
756 .when(show_picker, |row| {
757 row.child(calendar_picker::render(&self.state, cx))
613 758 })
759 .child(
760 v_flex()
761 .flex_1()
762 .min_w_0()
763 .h_full()
764 .child(self.header(start, span, compact))
765 .map(|calendar| {
766 if span == CalendarSpan::Month {
767 calendar.child(month_grid(
768 &self.state,
769 start,
770 &days,
771 &events,
772 today,
773 offset,
774 ))
775 } else {
776 calendar
777 .child(self.day_headers(&days, today))
778 .children(self.all_day_row(&days, &events, send_response))
779 .child(self.grid(&days, &events, today, now, send_response, cx))
780 }
781 }),
782 )
614 783 }
615 784 }
@@ -1,3 +1,5 @@
1use std::time::Duration;
2
1use app_base::format::{self, clock_format};
3use app_base::format::{self, clock_format};
2use chatsvc::{CalendarEvent, ResponseType, join_info_text};
4use chatsvc::{CalendarEvent, ResponseType, join_info_text};
3use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};
5use chrono::{DateTime, Local, NaiveDate, Offset, Timelike, Utc};
@@ -10,13 +12,19 @@ use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
12use gpui_kit::*;
11
13
12use super::calendar_date_picker::date_picker_button;
14use super::calendar_date_picker::date_picker_button;
15use super::calendar_event_dialog::open_calendar_event;
13use super::calendar_month::month_grid;
16use super::calendar_month::month_grid;
14use super::meeting_proposal_card::meeting_proposal_cards;
17use super::calendar_picker;
15use super::rsvp_menu::rsvp_menu;
16use super::join_dialog::open_join_with_id;
18use super::join_dialog::open_join_with_id;
17use super::new_meeting_dialog::open_new_meeting;
19use super::new_meeting_dialog::open_new_meeting;
20use super::rsvp_menu::rsvp_menu;
21use super::scroll_edge::scroll_offset;
22use crate::i18n::tr;
18use crate::app_state::AppState;
23use crate::app_state::AppState;
19use crate::call::join_available;
24use crate::call::calendar_now::{
25 DEFAULT_GRID_VIEWPORT, FollowNow, MANUAL_SCROLL_EPSILON, NOW_BIAS_FRACTION,
26 now_scroll_offset_y, offset_differs, shows_hour_grid,
27};
20use crate::call::week_grid::{
28use crate::call::week_grid::{
21 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
29 CalendarSpan, EventLook, WeekBlock, WeekDay, event_look, hour_label, month_shown, week_days,
22};
30};
@@ -30,7 +38,6 @@ const HEADER_HEIGHT: f32 = 52.;
30const DAY_HEADER_HEIGHT: f32 = 56.;
38const DAY_HEADER_HEIGHT: f32 = 56.;
31const ALL_DAY_HEIGHT: f32 = 26.;
39const ALL_DAY_HEIGHT: f32 = 26.;
32const BLOCK_GAP: f32 = 2.;
40const BLOCK_GAP: f32 = 2.;
33const FIRST_VISIBLE_HOUR: f32 = 8.;
34const CANCELED_PREFIX: &str = "Canceled: ";
41const CANCELED_PREFIX: &str = "Canceled: ";
35const COPY_JOIN_INFO: &str = "Copy join info";
42const COPY_JOIN_INFO: &str = "Copy join info";
36const COMPACT_HEADER_WIDTH: f32 = 960.;
43const COMPACT_HEADER_WIDTH: f32 = 960.;
@@ -42,28 +49,132 @@ const HATCH_GAP: f32 = 2.5;
42const SMALL_TITLE_HEIGHT: f32 = 20.;
49const SMALL_TITLE_HEIGHT: f32 = 20.;
43const TODAY_MARK_HEIGHT: f32 = 3.;
50const TODAY_MARK_HEIGHT: f32 = 3.;
44const NOW_DOT_SIZE: f32 = 8.;
51const NOW_DOT_SIZE: f32 = 8.;
52const CLOCK_TICK: Duration = Duration::from_secs(30);
53const CHROME_HEIGHT: f32 = HEADER_HEIGHT + DAY_HEADER_HEIGHT + ALL_DAY_HEIGHT;
45
54
46pub struct CalendarView {
55pub struct CalendarView {
47 state: Entity<AppState>,
56 state: Entity<AppState>,
48 scroll: ScrollHandle,
57 scroll: ScrollHandle,
49 scrolled_to_morning: bool,
58 follow_now: FollowNow,
59 seen_scroll_to_now: u64,
60 last_programmatic_offset: f32,
61 skip_manual_check: bool,
62 clock_running: bool,
50 _observation: Subscription,
63 _observation: Subscription,
51 _agent_observation: Option<Subscription>,
52}
64}
53
65
54impl CalendarView {
66impl CalendarView {
55 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
67 pub fn new(state: Entity<AppState>, cx: &mut Context<Self>) -> Self {
56 let observation = cx.observe(&state, |_, _, cx| cx.notify());
68 let observation = cx.observe(&state, |_, _, cx| cx.notify());
57 let agent_observation = crate::agent_api::handle(cx).map(|api| cx.observe(&api, |_, _, cx| cx.notify()));
58 CalendarView {
69 CalendarView {
59 state,
70 state,
60 scroll: ScrollHandle::new(),
71 scroll: ScrollHandle::new(),
61 scrolled_to_morning: false,
72 follow_now: FollowNow { active: true },
73 seen_scroll_to_now: 0,
74 last_programmatic_offset: 0.,
75 skip_manual_check: false,
76 clock_running: false,
62 _observation: observation,
77 _observation: observation,
63 _agent_observation: agent_observation,
64 }
78 }
65 }
79 }
66
80
81 fn grid_viewport_height(window: &Window) -> f32 {
82 (f32::from(window.viewport_size().height) - CHROME_HEIGHT).max(DEFAULT_GRID_VIEWPORT * 0.5)
83 }
84
85 fn align_scroll_to_now(&mut self, window: &Window) {
86 let local = Local::now();
87 let offset = now_scroll_offset_y(
88 local.hour(),
89 local.minute(),
90 HOUR_HEIGHT,
91 Self::grid_viewport_height(window),
92 NOW_BIAS_FRACTION,
93 );
94 self.scroll.set_offset(point(px(0.), px(offset)));
95 self.last_programmatic_offset = offset;
96 self.skip_manual_check = true;
97 }
98
99 fn sync_follow_from_state(&mut self, window: &Window, cx: &mut Context<Self>) {
100 let (scroll_to_now, span, today_visible) = {
101 let state = self.state.read(cx);
102 let start = state.calendar_start();
103 let today = Local::now().date_naive();
104 let today_visible = start <= today
105 && today < start + chrono::Duration::days(state.calendar_week.span.days());
106 (
107 state.calendar_scroll_to_now,
108 state.calendar_week.span,
109 today_visible,
110 )
111 };
112 if !shows_hour_grid(span) {
113 self.stop_clock();
114 return;
115 }
116 self.ensure_clock(cx);
117 if scroll_to_now != self.seen_scroll_to_now {
118 self.seen_scroll_to_now = scroll_to_now;
119 self.follow_now.request_align();
120 }
121 if self.skip_manual_check {
122 self.skip_manual_check = false;
123 } else if self.follow_now.active
124 && offset_differs(
125 f32::from(scroll_offset(&self.scroll).y),
126 self.last_programmatic_offset,
127 MANUAL_SCROLL_EPSILON,
128 )
129 {
130 self.follow_now.note_manual_scroll();
131 }
132 if self.follow_now.should_follow(today_visible) {
133 self.align_scroll_to_now(window);
134 }
135 }
136
137 fn ensure_clock(&mut self, cx: &mut Context<Self>) {
138 if self.clock_running {
139 return;
140 }
141 self.clock_running = true;
142 cx.spawn(async move |this, cx| {
143 loop {
144 cx.background_executor().timer(CLOCK_TICK).await;
145 let keep = this
146 .update(cx, |view, cx| {
147 let span = view.state.read(cx).calendar_week.span;
148 if !shows_hour_grid(span) {
149 view.clock_running = false;
150 return false;
151 }
152 cx.notify();
153 true
154 })
155 .unwrap_or(false);
156 if !keep {
157 break;
158 }
159 }
160 })
161 .detach();
162 }
163
164 fn stop_clock(&mut self) {
165 self.clock_running = false;
166 }
167
168 fn on_grid_scroll_wheel(
169 &mut self,
170 _event: &ScrollWheelEvent,
171 _window: &mut Window,
172 cx: &mut Context<Self>,
173 ) {
174 self.follow_now.note_manual_scroll();
175 cx.notify();
176 }
177
67 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
178 fn header(&self, start: NaiveDate, span: CalendarSpan, compact: bool) -> impl IntoElement {
68 let span_state = self.state.clone();
179 let span_state = self.state.clone();
69 let label = |text: &'static str| (!compact).then_some(text);
180 let label = |text: &'static str| (!compact).then_some(text);
@@ -123,19 +234,17 @@ impl CalendarView {
123 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
234 forward.update(cx, |state, cx| state.shift_calendar_week(1, cx))
124 }),
235 }),
125 )
236 )
126 .child(
237 .child(h_flex().flex_1().min_w_0().child(date_picker_button(
127 h_flex().flex_1().min_w_0().child(date_picker_button(
238 &self.state,
128 &self.state,
239 span.title(start),
129 span.title(start),
240 start,
130 start,
241 span.days(),
131 span.days(),
242 if span == CalendarSpan::Month {
132 if span == CalendarSpan::Month {
243 month_shown(start)
133 month_shown(start)
244 } else {
134 } else {
245 start
135 start
246 },
136 },
247 )))
137 )),
138 )
139 .child(
248 .child(
140 Button::new("calendar-span")
249 Button::new("calendar-span")
141 .small()
250 .small()
@@ -240,7 +349,12 @@ impl CalendarView {
240 }))
349 }))
241 }
350 }
242
351
243 fn all_day_row(&self, days: &[WeekDay], events: &[CalendarEvent]) -> Option<Div> {
352 fn all_day_row(
353 &self,
354 days: &[WeekDay],
355 events: &[CalendarEvent],
356 send_response: bool,
357 ) -> Option<Div> {
244 if days.iter().all(|day| day.all_day.is_empty()) {
358 if days.iter().all(|day| day.all_day.is_empty()) {
245 return None;
359 return None;
246 }
360 }
@@ -259,16 +373,36 @@ impl CalendarView {
259 .border_l_1()
373 .border_l_1()
260 .border_color(theme::border())
374 .border_color(theme::border())
261 .children(day.all_day.iter().map(|&index| {
375 .children(day.all_day.iter().map(|&index| {
376 let event = events[index].clone();
377 let open_state = self.state.clone();
378 let (menu_state, menu_event) = (self.state.clone(), event.clone());
379 // Day-qualified id: multi-day all-day chips share object_id.
262 div()
380 div()
381 .id(SharedString::from(format!(
382 "calendar-all-day-{}-{}",
383 event.object_id, day.date
384 )))
263 .h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
385 .h(px(ALL_DAY_HEIGHT - 2. * BLOCK_GAP))
264 .px(px(6.))
386 .px(px(6.))
265 .flex()
387 .flex()
266 .items_center()
388 .items_center()
267 .rounded(px(4.))
389 .rounded(px(4.))
268 .bg(event_fill(event_look(&events[index])))
390 .bg(event_fill(event_look(&event)))
269 .text_size(px(12.))
391 .text_size(px(12.))
270 .truncate()
392 .truncate()
271 .child(event_title(&events[index]))
393 .cursor_pointer()
394 .child(event_title(&event))
395 .on_click(move |_, window, cx| {
396 open_calendar_event(
397 open_state.clone(),
398 event.clone(),
399 window,
400 cx,
401 );
402 })
403 .context_menu(move |menu, _, _| {
404 event_menu(menu, &menu_state, &menu_event, send_response)
405 })
272 }))
406 }))
273 })),
407 })),
274 )
408 )
@@ -278,7 +412,7 @@ impl CalendarView {
278 &self,
412 &self,
279 block: &WeekBlock,
413 block: &WeekBlock,
280 event: &CalendarEvent,
414 event: &CalendarEvent,
281 now: DateTime<Utc>,
415 day: NaiveDate,
282 send_response: bool,
416 send_response: bool,
283 ) -> impl IntoElement {
417 ) -> impl IntoElement {
284 let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
418 let top = block.start_minute as f32 / 60. * HOUR_HEIGHT;
@@ -289,11 +423,10 @@ impl CalendarView {
289 let compact = height < 36.;
423 let compact = height < 36.;
290 let small = height < SMALL_TITLE_HEIGHT;
424 let small = height < SMALL_TITLE_HEIGHT;
291 let look = event_look(event);
425 let look = event_look(event);
292 let can_join = event.online
426 // Join on the block whenever a Teams link exists (same as detail dialog).
293 && !event.cancelled
427 let can_join = event.online && !event.cancelled && event.join_url.is_some();
294 && event.join_url.is_some()
428 let open_state = self.state.clone();
295 && join_available(event.start, event.end, now);
429 let open_event = event.clone();
296 let (open_state, thread_id) = (self.state.clone(), event.thread_id.clone());
297 let (menu_state, menu_event) = (self.state.clone(), event.clone());
430 let (menu_state, menu_event) = (self.state.clone(), event.clone());
298 let (join_state, join_url, subject) = (
431 let (join_state, join_url, subject) = (
299 self.state.clone(),
432 self.state.clone(),
@@ -304,10 +437,11 @@ impl CalendarView {
304 EventLook::Busy => (theme::text(), theme::text_soft()),
437 EventLook::Busy => (theme::text(), theme::text_soft()),
305 EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
438 EventLook::Free | EventLook::Tentative => (theme::text_soft(), theme::text_muted()),
306 };
439 };
440 // Day-qualified id: overnight / multi-day spans reuse object_id per column.
307 div()
441 div()
308 .id(SharedString::from(format!(
442 .id(SharedString::from(format!(
309 "calendar-event-{}",
443 "calendar-event-{}-{}",
310 event.object_id
444 event.object_id, day
311 )))
445 )))
312 .absolute()
446 .absolute()
313 .top(px(top))
447 .top(px(top))
@@ -359,12 +493,12 @@ impl CalendarView {
359 block.child(
493 block.child(
360 div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
494 div().flex_none().pr(px(4.)).pt(px(3.)).h_full().child(
361 Button::new(SharedString::from(format!(
495 Button::new(SharedString::from(format!(
362 "calendar-join-{}",
496 "calendar-join-{}-{}",
363 event.object_id
497 event.object_id, day
364 )))
498 )))
365 .xsmall()
499 .xsmall()
366 .primary()
500 .primary()
367 .label("Join")
501 .label(tr("common.join"))
368 .on_click(move |_, _, cx| {
502 .on_click(move |_, _, cx| {
369 cx.stop_propagation();
503 cx.stop_propagation();
370 join_state.update(cx, |state, cx| {
504 join_state.update(cx, |state, cx| {
@@ -379,10 +513,8 @@ impl CalendarView {
379 )
513 )
380 }),
514 }),
381 )
515 )
382 .on_click(move |_, _, cx| {
516 .on_click(move |_, window, cx| {
383 open_state.update(cx, |state, cx| {
517 open_calendar_event(open_state.clone(), open_event.clone(), window, cx);
384 state.open_meeting_chat(thread_id.as_deref(), cx)
385 });
386 })
518 })
387 .context_menu(move |menu, _, _| {
519 .context_menu(move |menu, _, _| {
388 event_menu(menu, &menu_state, &menu_event, send_response)
520 event_menu(menu, &menu_state, &menu_event, send_response)
@@ -396,6 +528,7 @@ impl CalendarView {
396 today: NaiveDate,
528 today: NaiveDate,
397 now: DateTime<Utc>,
529 now: DateTime<Utc>,
398 send_response: bool,
530 send_response: bool,
531 cx: &mut Context<Self>,
399 ) -> impl IntoElement {
532 ) -> impl IntoElement {
400 let total_height = 24. * HOUR_HEIGHT;
533 let total_height = 24. * HOUR_HEIGHT;
401 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
534 let twelve_hour = clock_format().contains("%p") || clock_format().contains("%P");
@@ -409,6 +542,7 @@ impl CalendarView {
409 .min_h_0()
542 .min_h_0()
410 .overflow_y_scroll()
543 .overflow_y_scroll()
411 .track_scroll(&self.scroll)
544 .track_scroll(&self.scroll)
545 .on_scroll_wheel(cx.listener(Self::on_grid_scroll_wheel))
412 .child(
546 .child(
413 h_flex()
547 h_flex()
414 .h(px(total_height))
548 .h(px(total_height))
@@ -457,7 +591,7 @@ impl CalendarView {
457 self.event_block(
591 self.event_block(
458 block,
592 block,
459 &events[block.event_index],
593 &events[block.event_index],
460 now,
594 day.date,
461 send_response,
595 send_response,
462 )
596 )
463 }))
597 }))
@@ -566,21 +700,40 @@ fn status_bar(look: EventLook) -> Option<Div> {
566}
700}
567
701
568fn event_title(event: &CalendarEvent) -> String {
702fn event_title(event: &CalendarEvent) -> String {
569 if event.cancelled {
703 let subject = if event.cancelled {
570 format!("{CANCELED_PREFIX}{}", event.subject)
704 format!("{CANCELED_PREFIX}{}", event.subject)
571 } else {
705 } else {
572 event.subject.clone()
706 event.subject.clone()
707 };
708 let label = source_label(event);
709 if label.is_empty() {
710 subject
711 } else {
712 format!("{subject} · {label}")
573 }
713 }
574}
714}
575
715
716fn source_label(event: &CalendarEvent) -> String {
717 let mut sources = event.sources.clone();
718 if sources.is_empty() {
719 sources.push(event.source);
720 }
721 sources.sort_by_key(|source| source.label());
722 sources.dedup();
723 if sources.len() == 1 && sources[0] == chatsvc::CalendarSource::Outlook {
724 return String::new();
725 }
726 sources
727 .iter()
728 .map(|source| source.label())
729 .collect::<Vec<_>>()
730 .join("+")
731}
732
576impl Render for CalendarView {
733impl Render for CalendarView {
577 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
734 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
578 let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
735 let compact = f32::from(window.viewport_size().width) < COMPACT_HEADER_WIDTH;
579 if !self.scrolled_to_morning {
736 self.sync_follow_from_state(window, cx);
580 self.scrolled_to_morning = true;
581 self.scroll
582 .set_offset(point(px(0.), px(-FIRST_VISIBLE_HOUR * HOUR_HEIGHT)));
583 }
584 let state = self.state.read(cx);
737 let state = self.state.read(cx);
585 let start = state.calendar_start();
738 let start = state.calendar_start();
586 let events = state.calendar_week.events.clone();
739 let events = state.calendar_week.events.clone();
@@ -590,7 +743,8 @@ impl Render for CalendarView {
590 let days = week_days(&events, start, span.days(), offset);
743 let days = week_days(&events, start, span.days(), offset);
591 let today = Local::now().date_naive();
744 let today = Local::now().date_naive();
592 let now = Utc::now();
745 let now = Utc::now();
593 v_flex()
746 let show_picker = !compact;
747 h_flex()
594 .debug_selector(|| "shell/islands/calendar".into())
748 .debug_selector(|| "shell/islands/calendar".into())
595 .flex_1()
749 .flex_1()
596 .w_full()
750 .w_full()
@@ -599,17 +753,32 @@ impl Render for CalendarView {
599 .rounded(px(10.))
753 .rounded(px(10.))
600 .bg(theme::surface())
754 .bg(theme::surface())
601 .overflow_hidden()
755 .overflow_hidden()
602 .child(self.header(start, span, compact))
756 .when(show_picker, |row| {
603 .children(meeting_proposal_cards(cx))
757 row.child(calendar_picker::render(&self.state, cx))
604 .map(|calendar| {
605 if span == CalendarSpan::Month {
606 calendar.child(month_grid(&self.state, start, &days, &events, today, offset))
607 } else {
608 calendar
609 .child(self.day_headers(&days, today))
610 .children(self.all_day_row(&days, &events))
611 .child(self.grid(&days, &events, today, now, send_response))
612 }
613 })
758 })
759 .child(
760 v_flex()
761 .flex_1()
762 .min_w_0()
763 .h_full()
764 .child(self.header(start, span, compact))
765 .map(|calendar| {
766 if span == CalendarSpan::Month {
767 calendar.child(month_grid(
768 &self.state,
769 start,
770 &days,
771 &events,
772 today,
773 offset,
774 ))
775 } else {
776 calendar
777 .child(self.day_headers(&days, today))
778 .children(self.all_day_row(&days, &events, send_response))
779 .child(self.grid(&days, &events, today, now, send_response, cx))
780 }
781 }),
782 )
614 }
783 }
615}
784}
crates/app/src/views/call_controls.rs +26 −13
@@ -11,6 +11,7 @@ use super::shortcuts::{StartAudioCall, StartVideoCall};
11 11 use super::widgets::{icon, menu_icon};
12 12 use crate::app_state::{AppState, Selection};
13 13 use crate::call::{is_echo_chat, plan_for_chat};
14 use crate::i18n::tr;
14 15 use crate::theme;
15 16
16 17 const BUTTON_SIZE: f32 = 30.;
@@ -20,10 +21,6 @@ const CHEVRON_WIDTH: f32 = 18.;
20 21 const CHEVRON_GLYPH: f32 = 12.;
21 22 pub const HEADER_VIDEO_CALL_TAG: &str = "header-video-call";
22 23 pub const HEADER_CALL_OPTIONS_TAG: &str = "header-call-options";
23 const VIDEO_CALL_LABEL: &str = "Video call";
24 const AUDIO_CALL_LABEL: &str = "Audio call";
25 const CALL_OPTIONS_LABEL: &str = "Call options";
26 const MEET_NOW_LABEL: &str = "Meet now";
27 24 const GROUP_KIND: &str = "group";
28 25 const MEETING_KIND: &str = "meeting";
29 26
@@ -64,8 +61,10 @@ pub fn header_call_controls(
64 61 .font_weight(FontWeight::SEMIBOLD)
65 62 .cursor_pointer()
66 63 .hover(|button| button.opacity(0.85))
67 .when(running, |button| button.child(icon(IconName::Phone, 14., foreground)))
68 .child("Join")
64 .when(running, |button| {
65 button.child(icon(IconName::Phone, 14., foreground))
66 })
67 .child(tr("common.join"))
69 68 .on_click(move |_, _, cx| {
70 69 join_app.update(cx, |state, cx| state.join_chat_meeting(&join_id, cx));
71 70 })
@@ -105,8 +104,18 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
105 104 Button::new(HEADER_VIDEO_CALL_TAG)
106 105 .ghost()
107 106 .h(px(BUTTON_SIZE))
108 .map(|button| if labelled { button.px(px(8.)) } else { button.p_0().w(px(BUTTON_SIZE)) })
109 .tooltip(if meet_now { MEET_NOW_LABEL } else { VIDEO_CALL_LABEL })
107 .map(|button| {
108 if labelled {
109 button.px(px(8.))
110 } else {
111 button.p_0().w(px(BUTTON_SIZE))
112 }
113 })
114 .tooltip(if meet_now {
115 tr("calls.chrome.meet_now")
116 } else {
117 tr("calls.chrome.video_call")
118 })
110 119 .debug_selector(|| HEADER_VIDEO_CALL_TAG.into())
111 120 .child(
112 121 h_flex()
@@ -119,7 +128,7 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
119 128 .text_size(px(14.))
120 129 .font_weight(FontWeight::SEMIBOLD)
121 130 .text_color(theme::text())
122 .child(MEET_NOW_LABEL),
131 .child(tr("calls.chrome.meet_now")),
123 132 )
124 133 }),
125 134 )
@@ -131,23 +140,27 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
131 140 .p_0()
132 141 .w(px(CHEVRON_WIDTH))
133 142 .h(px(BUTTON_SIZE))
134 .tooltip(CALL_OPTIONS_LABEL)
143 .tooltip(tr("calls.chrome.call_options"))
135 144 .debug_selector(|| HEADER_CALL_OPTIONS_TAG.into())
136 .child(icon(IconName::ChevronDown, CHEVRON_GLYPH, theme::text_soft()))
145 .child(icon(
146 IconName::ChevronDown,
147 CHEVRON_GLYPH,
148 theme::text_soft(),
149 ))
137 150 .dropdown_menu(move |popup, _, _| {
138 151 let (video, audio) = (menu_app.clone(), menu_app.clone());
139 152 let popup = if meet_now {
140 153 popup
141 154 } else {
142 155 popup.item(
143 PopupMenuItem::new(VIDEO_CALL_LABEL)
156 PopupMenuItem::new(tr("calls.chrome.video_call"))
144 157 .icon(menu_icon(IconName::Video))
145 158 .action(Box::new(StartVideoCall))
146 159 .on_click(move |_, _, cx| start_call(&video, true, cx)),
147 160 )
148 161 };
149 162 popup.item(
150 PopupMenuItem::new(AUDIO_CALL_LABEL)
163 PopupMenuItem::new(tr("calls.chrome.audio_call"))
151 164 .icon(menu_icon(IconName::Phone))
152 165 .action(Box::new(StartAudioCall))
153 166 .on_click(move |_, _, cx| start_call(&audio, false, cx)),
@@ -11,6 +11,7 @@ use super::shortcuts::{StartAudioCall, StartVideoCall};
11use super::widgets::{icon, menu_icon};
11use super::widgets::{icon, menu_icon};
12use crate::app_state::{AppState, Selection};
12use crate::app_state::{AppState, Selection};
13use crate::call::{is_echo_chat, plan_for_chat};
13use crate::call::{is_echo_chat, plan_for_chat};
14use crate::i18n::tr;
14use crate::theme;
15use crate::theme;
15
16
16const BUTTON_SIZE: f32 = 30.;
17const BUTTON_SIZE: f32 = 30.;
@@ -20,10 +21,6 @@ const CHEVRON_WIDTH: f32 = 18.;
20const CHEVRON_GLYPH: f32 = 12.;
21const CHEVRON_GLYPH: f32 = 12.;
21pub const HEADER_VIDEO_CALL_TAG: &str = "header-video-call";
22pub const HEADER_VIDEO_CALL_TAG: &str = "header-video-call";
22pub const HEADER_CALL_OPTIONS_TAG: &str = "header-call-options";
23pub const HEADER_CALL_OPTIONS_TAG: &str = "header-call-options";
23const VIDEO_CALL_LABEL: &str = "Video call";
24const AUDIO_CALL_LABEL: &str = "Audio call";
25const CALL_OPTIONS_LABEL: &str = "Call options";
26const MEET_NOW_LABEL: &str = "Meet now";
27const GROUP_KIND: &str = "group";
24const GROUP_KIND: &str = "group";
28const MEETING_KIND: &str = "meeting";
25const MEETING_KIND: &str = "meeting";
29
26
@@ -64,8 +61,10 @@ pub fn header_call_controls(
64 .font_weight(FontWeight::SEMIBOLD)
61 .font_weight(FontWeight::SEMIBOLD)
65 .cursor_pointer()
62 .cursor_pointer()
66 .hover(|button| button.opacity(0.85))
63 .hover(|button| button.opacity(0.85))
67 .when(running, |button| button.child(icon(IconName::Phone, 14., foreground)))
64 .when(running, |button| {
68 .child("Join")
65 button.child(icon(IconName::Phone, 14., foreground))
66 })
67 .child(tr("common.join"))
69 .on_click(move |_, _, cx| {
68 .on_click(move |_, _, cx| {
70 join_app.update(cx, |state, cx| state.join_chat_meeting(&join_id, cx));
69 join_app.update(cx, |state, cx| state.join_chat_meeting(&join_id, cx));
71 })
70 })
@@ -105,8 +104,18 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
105 Button::new(HEADER_VIDEO_CALL_TAG)
104 Button::new(HEADER_VIDEO_CALL_TAG)
106 .ghost()
105 .ghost()
107 .h(px(BUTTON_SIZE))
106 .h(px(BUTTON_SIZE))
108 .map(|button| if labelled { button.px(px(8.)) } else { button.p_0().w(px(BUTTON_SIZE)) })
107 .map(|button| {
109 .tooltip(if meet_now { MEET_NOW_LABEL } else { VIDEO_CALL_LABEL })
108 if labelled {
109 button.px(px(8.))
110 } else {
111 button.p_0().w(px(BUTTON_SIZE))
112 }
113 })
114 .tooltip(if meet_now {
115 tr("calls.chrome.meet_now")
116 } else {
117 tr("calls.chrome.video_call")
118 })
110 .debug_selector(|| HEADER_VIDEO_CALL_TAG.into())
119 .debug_selector(|| HEADER_VIDEO_CALL_TAG.into())
111 .child(
120 .child(
112 h_flex()
121 h_flex()
@@ -119,7 +128,7 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
119 .text_size(px(14.))
128 .text_size(px(14.))
120 .font_weight(FontWeight::SEMIBOLD)
129 .font_weight(FontWeight::SEMIBOLD)
121 .text_color(theme::text())
130 .text_color(theme::text())
122 .child(MEET_NOW_LABEL),
131 .child(tr("calls.chrome.meet_now")),
123 )
132 )
124 }),
133 }),
125 )
134 )
@@ -131,23 +140,27 @@ fn video_split_button(app: &Entity<AppState>, meet_now: bool, compact: bool) ->
131 .p_0()
140 .p_0()
132 .w(px(CHEVRON_WIDTH))
141 .w(px(CHEVRON_WIDTH))
133 .h(px(BUTTON_SIZE))
142 .h(px(BUTTON_SIZE))
134 .tooltip(CALL_OPTIONS_LABEL)
143 .tooltip(tr("calls.chrome.call_options"))
135 .debug_selector(|| HEADER_CALL_OPTIONS_TAG.into())
144 .debug_selector(|| HEADER_CALL_OPTIONS_TAG.into())
136 .child(icon(IconName::ChevronDown, CHEVRON_GLYPH, theme::text_soft()))
145 .child(icon(
146 IconName::ChevronDown,
147 CHEVRON_GLYPH,
148 theme::text_soft(),
149 ))
137 .dropdown_menu(move |popup, _, _| {
150 .dropdown_menu(move |popup, _, _| {
138 let (video, audio) = (menu_app.clone(), menu_app.clone());
151 let (video, audio) = (menu_app.clone(), menu_app.clone());
139 let popup = if meet_now {
152 let popup = if meet_now {
140 popup
153 popup
141 } else {
154 } else {
142 popup.item(
155 popup.item(
143 PopupMenuItem::new(VIDEO_CALL_LABEL)
156 PopupMenuItem::new(tr("calls.chrome.video_call"))
144 .icon(menu_icon(IconName::Video))
157 .icon(menu_icon(IconName::Video))
145 .action(Box::new(StartVideoCall))
158 .action(Box::new(StartVideoCall))
146 .on_click(move |_, _, cx| start_call(&video, true, cx)),
159 .on_click(move |_, _, cx| start_call(&video, true, cx)),
147 )
160 )
148 };
161 };
149 popup.item(
162 popup.item(
150 PopupMenuItem::new(AUDIO_CALL_LABEL)
163 PopupMenuItem::new(tr("calls.chrome.audio_call"))
151 .icon(menu_icon(IconName::Phone))
164 .icon(menu_icon(IconName::Phone))
152 .action(Box::new(StartAudioCall))
165 .action(Box::new(StartAudioCall))
153 .on_click(move |_, _, cx| start_call(&audio, false, cx)),
166 .on_click(move |_, _, cx| start_call(&audio, false, cx)),
crates/app/src/views/call_extras.rs +84 −29
@@ -1,3 +1,4 @@
1 use crate::i18n::{tr, tr_args};
1 2 use crate::views::image_memory::bounded;
2 3 use std::path::PathBuf;
3 4
@@ -32,7 +33,11 @@ fn dark_text() -> Hsla {
32 33 }
33 34
34 35 pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
35 let chip = crate::call::recording_chip(model.recording, model.recording_audio_only, model.transcribing)?;
36 let chip = crate::call::recording_chip(
37 model.recording,
38 model.recording_audio_only,
39 model.transcribing,
40 )?;
36 41 let color = match chip {
37 42 RecordingChip::Transcribing => theme::accent_text(),
38 43 RecordingChip::Recording | RecordingChip::RecordingAudio => theme::red(),
@@ -57,7 +62,7 @@ pub fn return_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEle
57 62 let app = app.clone();
58 63 Some(
59 64 Button::new("call-return-main")
60 .label("Return to main meeting")
65 .label(tr("calls.chrome.return_main"))
61 66 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.return_to_main_meeting(cx)))
62 67 .into_any_element(),
63 68 )
@@ -70,7 +75,7 @@ pub fn room_chip(model: &CallModel) -> Option<AnyElement> {
70 75 .flex_none()
71 76 .text_size(px(13.))
72 77 .text_color(theme::text_muted())
73 .child("Breakout room")
78 .child(tr("calls.chrome.breakout_room"))
74 79 .into_any_element(),
75 80 )
76 81 }
@@ -79,21 +84,21 @@ pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
79 84 let (title, detail) = match model.hold {
80 85 HoldState::Active => return None,
81 86 HoldState::Local => (
82 "On hold".to_owned(),
87 tr("calls.chrome.on_hold"),
83 88 format!(
84 89 "{} cannot hear you and you cannot hear them.",
85 90 model.peer_name
86 91 ),
87 92 ),
88 93 HoldState::Remote => (
89 "You're on hold".to_owned(),
94 tr("calls.chrome.you_on_hold"),
90 95 format!("{} put the call on hold.", model.peer_name),
91 96 ),
92 97 };
93 98 let resume = (model.hold == HoldState::Local).then(|| {
94 99 let app = app.clone();
95 100 Button::new("call-resume")
96 .label("Resume")
101 .label(tr("common.resume"))
97 102 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))
98 103 });
99 104 Some(
@@ -136,7 +141,7 @@ pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<Any
136 141 let open = model.whiteboard_url().is_some().then(|| {
137 142 let app = app.clone();
138 143 Button::new("call-whiteboard-open")
139 .label("Open in browser")
144 .label(tr("calls.chrome.open_in_browser"))
140 145 .icon(IconName::ExternalLink)
141 146 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_whiteboard(cx)))
142 147 });
@@ -176,7 +181,7 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle
176 181 .unwrap_or("call")
177 182 .to_owned();
178 183 let (transfer_app, resume_app) = (app.clone(), app.clone());
179 let transfer = pill("call-consult-transfer", "Transfer", true)
184 let transfer = pill("call-consult-transfer", tr("calls.chrome.transfer"), true)
180 185 .debug_selector(|| "shell/islands/main/call-header/call-consult/transfer".into());
181 186 let transfer = if ready {
182 187 transfer.on_click(move |_, _, cx| {
@@ -185,7 +190,15 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle
185 190 } else {
186 191 transfer.opacity(0.5).cursor_default()
187 192 };
188 let resume = pill("call-consult-resume", format!("Resume {first_name}"), false)
193 let resume = {
194 let mut args = std::collections::HashMap::new();
195 args.insert("name".to_owned(), first_name);
196 pill(
197 "call-consult-resume",
198 tr_args("calls.chrome.resume_person", &args),
199 false,
200 )
201 }
189 202 .debug_selector(|| "shell/islands/main/call-header/call-consult/resume".into())
190 203 .on_click(move |_, _, cx| resume_app.update(cx, |state, cx| state.resume_held_call(cx)));
191 204 Some(
@@ -255,19 +268,19 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
255 268 div()
256 269 .text_size(px(16.))
257 270 .font_weight(FontWeight::SEMIBOLD)
258 .child("This meeting is being recorded"),
271 .child(tr("calls.chrome.recording_notice")),
259 272 ),
260 273 )
261 274 .child(
262 275 div()
263 276 .text_size(px(13.))
264 277 .text_color(theme::text_muted())
265 .child("Your microphone and camera stay off until you accept."),
278 .child(tr("calls.chrome.recording_accept_hint")),
266 279 )
267 280 .child(
268 281 h_flex().w_full().justify_end().child(
269 282 Button::new("call-consent-ok")
270 .label("OK")
283 .label(tr("common.ok"))
271 284 .on_click(move |_, _, cx| {
272 285 app.update(cx, |state, cx| state.accept_recording_notice(cx))
273 286 }),
@@ -278,7 +291,12 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
278 291 )
279 292 }
280 293
281 pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, window: &mut Window, cx: &mut App) {
294 pub fn confirm_record_action(
295 app: &Entity<AppState>,
296 action: RecordAction,
297 window: &mut Window,
298 cx: &mut App,
299 ) {
282 300 let Some(title) = action.confirm_title() else {
283 301 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
284 302 return;
@@ -286,8 +304,8 @@ pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, windo
286 304 let app = app.clone();
287 305 window.open_alert_dialog(cx, move |alert, _, _| {
288 306 let app = app.clone();
289 let cancel = Button::new("recording-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));
290 let stop = Button::new("recording-stop").label("Stop").danger().on_click(move |_, window, cx| {
307 let cancel = Button::new("recording-cancel").label(tr("common.cancel")).on_click(|_, window, cx| window.close_dialog(cx));
308 let stop = Button::new("recording-stop").label(tr("common.stop")).danger().on_click(move |_, window, cx| {
291 309 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
292 310 window.close_dialog(cx);
293 311 });
@@ -302,14 +320,18 @@ pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, windo
302 320 pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
303 321 let candidates = app.read(cx).transfer_candidates();
304 322 let picker_app = app.clone();
305 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
306 app.update(cx, |state, cx| state.open_transfer_picker(picker.into(), cx));
323 let picker =
324 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
325 app.update(cx, |state, cx| {
326 state.open_transfer_picker(picker.into(), cx)
327 });
307 328 }
308 329
309 330 pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
310 331 let candidates = app.read(cx).invite_candidates();
311 332 let picker_app = app.clone();
312 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
333 let picker =
334 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
313 335 app.update(cx, |state, cx| state.open_invite_picker(picker.into(), cx));
314 336 }
315 337
@@ -319,6 +341,7 @@ pub struct CameraMenu {
319 341 pub images: Vec<(String, String, Option<PathBuf>)>,
320 342 pub customs: Vec<PathBuf>,
321 343 pub effects: CameraEffects,
344 pub quality: calling::VideoQuality,
322 345 }
323 346
324 347 impl CameraMenu {
@@ -339,10 +362,42 @@ impl CameraMenu {
339 362 .collect(),
340 363 customs: library.customs.clone(),
341 364 effects: state.call_effects,
365 quality: state.call_video_quality,
342 366 }
343 367 }
344 368 }
345 369
370 pub fn quality_items(
371 popup: PopupMenu,
372 app: &Entity<AppState>,
373 current: calling::VideoQuality,
374 ) -> PopupMenu {
375 let choices = [
376 (calling::VideoQuality::Auto, "Auto"),
377 (calling::VideoQuality::P720, "720p"),
378 (calling::VideoQuality::P1080, "1080p"),
379 ];
380 let mut popup = popup
381 .separator()
382 .item(PopupMenuItem::label(tr("calls.chrome.video_quality")));
383 for (quality, label) in choices {
384 let app = app.clone();
385 let menu_label = if quality == calling::VideoQuality::Auto {
386 tr("calls.chrome.auto")
387 } else {
388 label.to_owned()
389 };
390 popup = popup.item(
391 PopupMenuItem::new(menu_label)
392 .checked(current == quality)
393 .on_click(move |_, _, cx| {
394 app.update(cx, |state, cx| state.set_call_video_quality(quality, cx))
395 }),
396 );
397 }
398 popup
399 }
400
346 401 fn thumbnail(
347 402 app: &Entity<AppState>,
348 403 index: usize,
@@ -399,7 +454,7 @@ fn effect_change(
399 454 fn effect_switch_item(
400 455 app: &Entity<AppState>,
401 456 id: &'static str,
402 label: &'static str,
457 label: String,
403 458 on: bool,
404 459 change: fn(&mut CameraEffects),
405 460 ) -> PopupMenuItem {
@@ -410,7 +465,7 @@ fn effect_switch_item(
410 465 .gap(px(16.))
411 466 .items_center()
412 467 .justify_between()
413 .child(label)
468 .child(label.clone())
414 469 .child(Switch::new(id).checked(on))
415 470 })
416 471 .on_click(effect_change(app, change))
@@ -419,32 +474,32 @@ fn effect_switch_item(
419 474 pub fn effect_items(popup: PopupMenu, app: &Entity<AppState>, effects: CameraEffects) -> PopupMenu {
420 475 popup
421 476 .separator()
422 .item(PopupMenuItem::label("Effects"))
477 .item(PopupMenuItem::label(tr("calls.chrome.effects")))
423 478 .item(effect_switch_item(
424 479 app,
425 480 "call-effect-mirror",
426 "Mirror my video",
481 tr("calls.chrome.mirror_video"),
427 482 effects.mirror,
428 483 |effects| effects.mirror = !effects.mirror,
429 484 ))
430 485 .item(effect_switch_item(
431 486 app,
432 487 "call-effect-framing",
433 "Auto framing",
488 tr("calls.chrome.auto_framing"),
434 489 effects.auto_framing,
435 490 |effects| effects.auto_framing = !effects.auto_framing,
436 491 ))
437 492 .item(effect_switch_item(
438 493 app,
439 494 "call-effect-brightness",
440 "Adjust brightness",
495 tr("calls.chrome.adjust_brightness"),
441 496 effects.adjust_brightness,
442 497 |effects| effects.adjust_brightness = !effects.adjust_brightness,
443 498 ))
444 499 .item(effect_switch_item(
445 500 app,
446 501 "call-effect-soft-focus",
447 "Soft focus",
502 tr("calls.chrome.soft_focus"),
448 503 effects.soft_focus,
449 504 |effects| effects.soft_focus = !effects.soft_focus,
450 505 ))
@@ -456,9 +511,9 @@ pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraM
456 511 let grid_menu = menu.clone();
457 512 let mut popup = popup
458 513 .separator()
459 .item(PopupMenuItem::label("Background"))
514 .item(PopupMenuItem::label(tr("calls.chrome.background")))
460 515 .item(
461 PopupMenuItem::new("None")
516 PopupMenuItem::new(tr("calls.chrome.background_none"))
462 517 .checked(menu.pick == BackgroundPick::None)
463 518 .on_click(move |_, _, cx| {
464 519 none_app.update(cx, |state, cx| {
@@ -467,7 +522,7 @@ pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraM
467 522 }),
468 523 )
469 524 .item(
470 PopupMenuItem::new("Blur")
525 PopupMenuItem::new(tr("calls.chrome.background_blur"))
471 526 .checked(menu.pick.is_blur())
472 527 .on_click(move |_, _, cx| {
473 528 blur_app.update(cx, |state, cx| {
@@ -514,7 +569,7 @@ pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraM
514 569 }));
515 570 }
516 571 popup.item(
517 PopupMenuItem::new("Add image...")
572 PopupMenuItem::new(tr("calls.chrome.add_image"))
518 573 .icon(IconName::Plus)
519 574 .on_click(move |_, _, cx| {
520 575 add_app.update(cx, |state, cx| state.add_call_background(cx))
@@ -1,3 +1,4 @@
1use crate::i18n::{tr, tr_args};
1use crate::views::image_memory::bounded;
2use crate::views::image_memory::bounded;
2use std::path::PathBuf;
3use std::path::PathBuf;
3
4
@@ -32,7 +33,11 @@ fn dark_text() -> Hsla {
32}
33}
33
34
34pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
35pub fn recording_chip(model: &CallModel) -> Option<AnyElement> {
35 let chip = crate::call::recording_chip(model.recording, model.recording_audio_only, model.transcribing)?;
36 let chip = crate::call::recording_chip(
37 model.recording,
38 model.recording_audio_only,
39 model.transcribing,
40 )?;
36 let color = match chip {
41 let color = match chip {
37 RecordingChip::Transcribing => theme::accent_text(),
42 RecordingChip::Transcribing => theme::accent_text(),
38 RecordingChip::Recording | RecordingChip::RecordingAudio => theme::red(),
43 RecordingChip::Recording | RecordingChip::RecordingAudio => theme::red(),
@@ -57,7 +62,7 @@ pub fn return_button(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEle
57 let app = app.clone();
62 let app = app.clone();
58 Some(
63 Some(
59 Button::new("call-return-main")
64 Button::new("call-return-main")
60 .label("Return to main meeting")
65 .label(tr("calls.chrome.return_main"))
61 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.return_to_main_meeting(cx)))
66 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.return_to_main_meeting(cx)))
62 .into_any_element(),
67 .into_any_element(),
63 )
68 )
@@ -70,7 +75,7 @@ pub fn room_chip(model: &CallModel) -> Option<AnyElement> {
70 .flex_none()
75 .flex_none()
71 .text_size(px(13.))
76 .text_size(px(13.))
72 .text_color(theme::text_muted())
77 .text_color(theme::text_muted())
73 .child("Breakout room")
78 .child(tr("calls.chrome.breakout_room"))
74 .into_any_element(),
79 .into_any_element(),
75 )
80 )
76}
81}
@@ -79,21 +84,21 @@ pub fn hold_panel(app: &Entity<AppState>, model: &CallModel) -> Option<AnyElemen
79 let (title, detail) = match model.hold {
84 let (title, detail) = match model.hold {
80 HoldState::Active => return None,
85 HoldState::Active => return None,
81 HoldState::Local => (
86 HoldState::Local => (
82 "On hold".to_owned(),
87 tr("calls.chrome.on_hold"),
83 format!(
88 format!(
84 "{} cannot hear you and you cannot hear them.",
89 "{} cannot hear you and you cannot hear them.",
85 model.peer_name
90 model.peer_name
86 ),
91 ),
87 ),
92 ),
88 HoldState::Remote => (
93 HoldState::Remote => (
89 "You're on hold".to_owned(),
94 tr("calls.chrome.you_on_hold"),
90 format!("{} put the call on hold.", model.peer_name),
95 format!("{} put the call on hold.", model.peer_name),
91 ),
96 ),
92 };
97 };
93 let resume = (model.hold == HoldState::Local).then(|| {
98 let resume = (model.hold == HoldState::Local).then(|| {
94 let app = app.clone();
99 let app = app.clone();
95 Button::new("call-resume")
100 Button::new("call-resume")
96 .label("Resume")
101 .label(tr("common.resume"))
97 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))
102 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_hold(cx)))
98 });
103 });
99 Some(
104 Some(
@@ -136,7 +141,7 @@ pub fn whiteboard_stage(app: &Entity<AppState>, model: &CallModel) -> Option<Any
136 let open = model.whiteboard_url().is_some().then(|| {
141 let open = model.whiteboard_url().is_some().then(|| {
137 let app = app.clone();
142 let app = app.clone();
138 Button::new("call-whiteboard-open")
143 Button::new("call-whiteboard-open")
139 .label("Open in browser")
144 .label(tr("calls.chrome.open_in_browser"))
140 .icon(IconName::ExternalLink)
145 .icon(IconName::ExternalLink)
141 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_whiteboard(cx)))
146 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.open_call_whiteboard(cx)))
142 });
147 });
@@ -176,7 +181,7 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle
176 .unwrap_or("call")
181 .unwrap_or("call")
177 .to_owned();
182 .to_owned();
178 let (transfer_app, resume_app) = (app.clone(), app.clone());
183 let (transfer_app, resume_app) = (app.clone(), app.clone());
179 let transfer = pill("call-consult-transfer", "Transfer", true)
184 let transfer = pill("call-consult-transfer", tr("calls.chrome.transfer"), true)
180 .debug_selector(|| "shell/islands/main/call-header/call-consult/transfer".into());
185 .debug_selector(|| "shell/islands/main/call-header/call-consult/transfer".into());
181 let transfer = if ready {
186 let transfer = if ready {
182 transfer.on_click(move |_, _, cx| {
187 transfer.on_click(move |_, _, cx| {
@@ -185,7 +190,15 @@ pub fn consult_banner(app: &Entity<AppState>, state: &AppState) -> Option<AnyEle
185 } else {
190 } else {
186 transfer.opacity(0.5).cursor_default()
191 transfer.opacity(0.5).cursor_default()
187 };
192 };
188 let resume = pill("call-consult-resume", format!("Resume {first_name}"), false)
193 let resume = {
194 let mut args = std::collections::HashMap::new();
195 args.insert("name".to_owned(), first_name);
196 pill(
197 "call-consult-resume",
198 tr_args("calls.chrome.resume_person", &args),
199 false,
200 )
201 }
189 .debug_selector(|| "shell/islands/main/call-header/call-consult/resume".into())
202 .debug_selector(|| "shell/islands/main/call-header/call-consult/resume".into())
190 .on_click(move |_, _, cx| resume_app.update(cx, |state, cx| state.resume_held_call(cx)));
203 .on_click(move |_, _, cx| resume_app.update(cx, |state, cx| state.resume_held_call(cx)));
191 Some(
204 Some(
@@ -255,19 +268,19 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
255 div()
268 div()
256 .text_size(px(16.))
269 .text_size(px(16.))
257 .font_weight(FontWeight::SEMIBOLD)
270 .font_weight(FontWeight::SEMIBOLD)
258 .child("This meeting is being recorded"),
271 .child(tr("calls.chrome.recording_notice")),
259 ),
272 ),
260 )
273 )
261 .child(
274 .child(
262 div()
275 div()
263 .text_size(px(13.))
276 .text_size(px(13.))
264 .text_color(theme::text_muted())
277 .text_color(theme::text_muted())
265 .child("Your microphone and camera stay off until you accept."),
278 .child(tr("calls.chrome.recording_accept_hint")),
266 )
279 )
267 .child(
280 .child(
268 h_flex().w_full().justify_end().child(
281 h_flex().w_full().justify_end().child(
269 Button::new("call-consent-ok")
282 Button::new("call-consent-ok")
270 .label("OK")
283 .label(tr("common.ok"))
271 .on_click(move |_, _, cx| {
284 .on_click(move |_, _, cx| {
272 app.update(cx, |state, cx| state.accept_recording_notice(cx))
285 app.update(cx, |state, cx| state.accept_recording_notice(cx))
273 }),
286 }),
@@ -278,7 +291,12 @@ pub fn consent_overlay(app: &Entity<AppState>, model: &CallModel) -> Option<AnyE
278 )
291 )
279}
292}
280
293
281pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, window: &mut Window, cx: &mut App) {
294pub fn confirm_record_action(
295 app: &Entity<AppState>,
296 action: RecordAction,
297 window: &mut Window,
298 cx: &mut App,
299) {
282 let Some(title) = action.confirm_title() else {
300 let Some(title) = action.confirm_title() else {
283 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
301 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
284 return;
302 return;
@@ -286,8 +304,8 @@ pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, windo
286 let app = app.clone();
304 let app = app.clone();
287 window.open_alert_dialog(cx, move |alert, _, _| {
305 window.open_alert_dialog(cx, move |alert, _, _| {
288 let app = app.clone();
306 let app = app.clone();
289 let cancel = Button::new("recording-cancel").label("Cancel").on_click(|_, window, cx| window.close_dialog(cx));
307 let cancel = Button::new("recording-cancel").label(tr("common.cancel")).on_click(|_, window, cx| window.close_dialog(cx));
290 let stop = Button::new("recording-stop").label("Stop").danger().on_click(move |_, window, cx| {
308 let stop = Button::new("recording-stop").label(tr("common.stop")).danger().on_click(move |_, window, cx| {
291 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
309 app.update(cx, |state, cx| state.run_call_record_action(action, cx));
292 window.close_dialog(cx);
310 window.close_dialog(cx);
293 });
311 });
@@ -302,14 +320,18 @@ pub fn confirm_record_action(app: &Entity<AppState>, action: RecordAction, windo
302pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
320pub fn open_transfer_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
303 let candidates = app.read(cx).transfer_candidates();
321 let candidates = app.read(cx).transfer_candidates();
304 let picker_app = app.clone();
322 let picker_app = app.clone();
305 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
323 let picker =
306 app.update(cx, |state, cx| state.open_transfer_picker(picker.into(), cx));
324 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Transfer, window, cx));
325 app.update(cx, |state, cx| {
326 state.open_transfer_picker(picker.into(), cx)
327 });
307}
328}
308
329
309pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
330pub fn open_invite_picker(app: &Entity<AppState>, window: &mut Window, cx: &mut App) {
310 let candidates = app.read(cx).invite_candidates();
331 let candidates = app.read(cx).invite_candidates();
311 let picker_app = app.clone();
332 let picker_app = app.clone();
312 let picker = cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
333 let picker =
334 cx.new(|cx| TransferPicker::new(picker_app, candidates, PickerMode::Invite, window, cx));
313 app.update(cx, |state, cx| state.open_invite_picker(picker.into(), cx));
335 app.update(cx, |state, cx| state.open_invite_picker(picker.into(), cx));
314}
336}
315
337
@@ -319,6 +341,7 @@ pub struct CameraMenu {
319 pub images: Vec<(String, String, Option<PathBuf>)>,
341 pub images: Vec<(String, String, Option<PathBuf>)>,
320 pub customs: Vec<PathBuf>,
342 pub customs: Vec<PathBuf>,
321 pub effects: CameraEffects,
343 pub effects: CameraEffects,
344 pub quality: calling::VideoQuality,
322}
345}
323
346
324impl CameraMenu {
347impl CameraMenu {
@@ -339,10 +362,42 @@ impl CameraMenu {
339 .collect(),
362 .collect(),
340 customs: library.customs.clone(),
363 customs: library.customs.clone(),
341 effects: state.call_effects,
364 effects: state.call_effects,
365 quality: state.call_video_quality,
342 }
366 }
343 }
367 }
344}
368}
345
369
370pub fn quality_items(
371 popup: PopupMenu,
372 app: &Entity<AppState>,
373 current: calling::VideoQuality,
374) -> PopupMenu {
375 let choices = [
376 (calling::VideoQuality::Auto, "Auto"),
377 (calling::VideoQuality::P720, "720p"),
378 (calling::VideoQuality::P1080, "1080p"),
379 ];
380 let mut popup = popup
381 .separator()
382 .item(PopupMenuItem::label(tr("calls.chrome.video_quality")));
383 for (quality, label) in choices {
384 let app = app.clone();
385 let menu_label = if quality == calling::VideoQuality::Auto {
386 tr("calls.chrome.auto")
387 } else {
388 label.to_owned()
389 };
390 popup = popup.item(
391 PopupMenuItem::new(menu_label)
392 .checked(current == quality)
393 .on_click(move |_, _, cx| {
394 app.update(cx, |state, cx| state.set_call_video_quality(quality, cx))
395 }),
396 );
397 }
398 popup
399}
400
346fn thumbnail(
401fn thumbnail(
347 app: &Entity<AppState>,
402 app: &Entity<AppState>,
348 index: usize,
403 index: usize,
@@ -399,7 +454,7 @@ fn effect_change(
399fn effect_switch_item(
454fn effect_switch_item(
400 app: &Entity<AppState>,
455 app: &Entity<AppState>,
401 id: &'static str,
456 id: &'static str,
402 label: &'static str,
457 label: String,
403 on: bool,
458 on: bool,
404 change: fn(&mut CameraEffects),
459 change: fn(&mut CameraEffects),
405) -> PopupMenuItem {
460) -> PopupMenuItem {
@@ -410,7 +465,7 @@ fn effect_switch_item(
410 .gap(px(16.))
465 .gap(px(16.))
411 .items_center()
466 .items_center()
412 .justify_between()
467 .justify_between()
413 .child(label)
468 .child(label.clone())
414 .child(Switch::new(id).checked(on))
469 .child(Switch::new(id).checked(on))
415 })
470 })
416 .on_click(effect_change(app, change))
471 .on_click(effect_change(app, change))
@@ -419,32 +474,32 @@ fn effect_switch_item(
419pub fn effect_items(popup: PopupMenu, app: &Entity<AppState>, effects: CameraEffects) -> PopupMenu {
474pub fn effect_items(popup: PopupMenu, app: &Entity<AppState>, effects: CameraEffects) -> PopupMenu {
420 popup
475 popup
421 .separator()
476 .separator()
422 .item(PopupMenuItem::label("Effects"))
477 .item(PopupMenuItem::label(tr("calls.chrome.effects")))
423 .item(effect_switch_item(
478 .item(effect_switch_item(
424 app,
479 app,
425 "call-effect-mirror",
480 "call-effect-mirror",
426 "Mirror my video",
481 tr("calls.chrome.mirror_video"),
427 effects.mirror,
482 effects.mirror,
428 |effects| effects.mirror = !effects.mirror,
483 |effects| effects.mirror = !effects.mirror,
429 ))
484 ))
430 .item(effect_switch_item(
485 .item(effect_switch_item(
431 app,
486 app,
432 "call-effect-framing",
487 "call-effect-framing",
433 "Auto framing",
488 tr("calls.chrome.auto_framing"),
434 effects.auto_framing,
489 effects.auto_framing,
435 |effects| effects.auto_framing = !effects.auto_framing,
490 |effects| effects.auto_framing = !effects.auto_framing,
436 ))
491 ))
437 .item(effect_switch_item(
492 .item(effect_switch_item(
438 app,
493 app,
439 "call-effect-brightness",
494 "call-effect-brightness",
440 "Adjust brightness",
495 tr("calls.chrome.adjust_brightness"),
441 effects.adjust_brightness,
496 effects.adjust_brightness,
442 |effects| effects.adjust_brightness = !effects.adjust_brightness,
497 |effects| effects.adjust_brightness = !effects.adjust_brightness,
443 ))
498 ))
444 .item(effect_switch_item(
499 .item(effect_switch_item(
445 app,
500 app,
446 "call-effect-soft-focus",
501 "call-effect-soft-focus",
447 "Soft focus",
502 tr("calls.chrome.soft_focus"),
448 effects.soft_focus,
503 effects.soft_focus,
449 |effects| effects.soft_focus = !effects.soft_focus,
504 |effects| effects.soft_focus = !effects.soft_focus,
450 ))
505 ))
@@ -456,9 +511,9 @@ pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraM
456 let grid_menu = menu.clone();
511 let grid_menu = menu.clone();
457 let mut popup = popup
512 let mut popup = popup
458 .separator()
513 .separator()
459 .item(PopupMenuItem::label("Background"))
514 .item(PopupMenuItem::label(tr("calls.chrome.background")))
460 .item(
515 .item(
461 PopupMenuItem::new("None")
516 PopupMenuItem::new(tr("calls.chrome.background_none"))
462 .checked(menu.pick == BackgroundPick::None)
517 .checked(menu.pick == BackgroundPick::None)
463 .on_click(move |_, _, cx| {
518 .on_click(move |_, _, cx| {
464 none_app.update(cx, |state, cx| {
519 none_app.update(cx, |state, cx| {
@@ -467,7 +522,7 @@ pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraM
467 }),
522 }),
468 )
523 )
469 .item(
524 .item(
470 PopupMenuItem::new("Blur")
525 PopupMenuItem::new(tr("calls.chrome.background_blur"))
471 .checked(menu.pick.is_blur())
526 .checked(menu.pick.is_blur())
472 .on_click(move |_, _, cx| {
527 .on_click(move |_, _, cx| {
473 blur_app.update(cx, |state, cx| {
528 blur_app.update(cx, |state, cx| {
@@ -514,7 +569,7 @@ pub fn background_items(popup: PopupMenu, app: &Entity<AppState>, menu: &CameraM
514 }));
569 }));
515 }
570 }
516 popup.item(
571 popup.item(
517 PopupMenuItem::new("Add image...")
572 PopupMenuItem::new(tr("calls.chrome.add_image"))
518 .icon(IconName::Plus)
573 .icon(IconName::Plus)
519 .on_click(move |_, _, cx| {
574 .on_click(move |_, _, cx| {
520 add_app.update(cx, |state, cx| state.add_call_background(cx))
575 add_app.update(cx, |state, cx| state.add_call_background(cx))
crates/app/src/views/call_organizer.rs +5 −4
@@ -20,6 +20,7 @@ use super::call_record::{record_items, transcript_and_settings_items};
20 20 use super::call_toolbar::{split_chevron, tool_face, tool_trigger};
21 21 use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
22 22 use super::widgets::{Corner, corner_badge, count_badge, icon};
23 use crate::i18n::tr;
23 24 use crate::app_state::AppState;
24 25 use crate::call::{CAPTION_SHOWN, CallModel, CaptionPosition, Focus, contain_size};
25 26 use crate::notice::truncated;
@@ -96,7 +97,7 @@ fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {
96 97 )
97 98 .child(
98 99 Button::new(SharedString::from(format!("lobby-admit-{mri}")))
99 .label("Admit")
100 .label(tr("common.admit"))
100 101 .on_click(move |_, _, cx| {
101 102 admit_app.update(cx, |state, cx| {
102 103 state.admit_call_guest(admit_mri.clone(), cx)
@@ -105,7 +106,7 @@ fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {
105 106 )
106 107 .child(
107 108 Button::new(SharedString::from(format!("lobby-deny-{mri}")))
108 .label("Deny")
109 .label(tr("common.deny"))
109 110 .ghost()
110 111 .on_click(move |_, _, cx| {
111 112 deny_app
@@ -190,10 +191,10 @@ fn confirm_remove(
190 191 let app = app.clone();
191 192 let mri = mri.clone();
192 193 let cancel = Button::new("remove-cancel")
193 .label("Cancel")
194 .label(tr("common.cancel"))
194 195 .on_click(|_, window, cx| window.close_dialog(cx));
195 196 let remove = Button::new("remove-confirm")
196 .label("Remove")
197 .label(tr("common.remove"))
197 198 .danger()
198 199 .on_click(move |_, window, cx| {
199 200 app.update(cx, |state, cx| {
@@ -20,6 +20,7 @@ use super::call_record::{record_items, transcript_and_settings_items};
20use super::call_toolbar::{split_chevron, tool_face, tool_trigger};
20use super::call_toolbar::{split_chevron, tool_face, tool_trigger};
21use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
21use super::call_view::{BANNER_HEIGHT, MENU_WIDTH};
22use super::widgets::{Corner, corner_badge, count_badge, icon};
22use super::widgets::{Corner, corner_badge, count_badge, icon};
23use crate::i18n::tr;
23use crate::app_state::AppState;
24use crate::app_state::AppState;
24use crate::call::{CAPTION_SHOWN, CallModel, CaptionPosition, Focus, contain_size};
25use crate::call::{CAPTION_SHOWN, CallModel, CaptionPosition, Focus, contain_size};
25use crate::notice::truncated;
26use crate::notice::truncated;
@@ -96,7 +97,7 @@ fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {
96 )
97 )
97 .child(
98 .child(
98 Button::new(SharedString::from(format!("lobby-admit-{mri}")))
99 Button::new(SharedString::from(format!("lobby-admit-{mri}")))
99 .label("Admit")
100 .label(tr("common.admit"))
100 .on_click(move |_, _, cx| {
101 .on_click(move |_, _, cx| {
101 admit_app.update(cx, |state, cx| {
102 admit_app.update(cx, |state, cx| {
102 state.admit_call_guest(admit_mri.clone(), cx)
103 state.admit_call_guest(admit_mri.clone(), cx)
@@ -105,7 +106,7 @@ fn lobby_list(app: &Entity<AppState>, guests: &[(String, String)]) -> Div {
105 )
106 )
106 .child(
107 .child(
107 Button::new(SharedString::from(format!("lobby-deny-{mri}")))
108 Button::new(SharedString::from(format!("lobby-deny-{mri}")))
108 .label("Deny")
109 .label(tr("common.deny"))
109 .ghost()
110 .ghost()
110 .on_click(move |_, _, cx| {
111 .on_click(move |_, _, cx| {
111 deny_app
112 deny_app
@@ -190,10 +191,10 @@ fn confirm_remove(
190 let app = app.clone();
191 let app = app.clone();
191 let mri = mri.clone();
192 let mri = mri.clone();
192 let cancel = Button::new("remove-cancel")
193 let cancel = Button::new("remove-cancel")
193 .label("Cancel")
194 .label(tr("common.cancel"))
194 .on_click(|_, window, cx| window.close_dialog(cx));
195 .on_click(|_, window, cx| window.close_dialog(cx));
195 let remove = Button::new("remove-confirm")
196 let remove = Button::new("remove-confirm")
196 .label("Remove")
197 .label(tr("common.remove"))
197 .danger()
198 .danger()
198 .on_click(move |_, window, cx| {
199 .on_click(move |_, window, cx| {
199 app.update(cx, |state, cx| {
200 app.update(cx, |state, cx| {
crates/app/src/views/call_people.rs +219 −90
@@ -1,5 +1,5 @@
1 use gpui_kit::component::scroll::ScrollableElement as _;
2 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::scroll::ScrollableElement as _;
3 3 use gpui_kit::component::{
4 4 Sizable as _,
5 5 button::{Button, ButtonVariants as _},
@@ -15,10 +15,10 @@ use gpui_kit::*;
15 15 use super::avatar::person_avatar;
16 16 use super::call_extras::open_invite_picker;
17 17 use super::call_organizer::{pill, tile_menu};
18 use super::call_toolbar::tool_face;
19 use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH};
20 use super::widgets::{Corner, corner_badge, count_badge, icon};
18 use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH, round_control};
21 19 use super::scroll_edge::with_top_edge;
20 use super::widgets::{Corner, corner_badge, count_badge, icon};
21 use crate::i18n::tr;
22 22 use crate::app_state::AppState;
23 23 use crate::call::{
24 24 ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
@@ -46,10 +46,20 @@ fn dark_text() -> Hsla {
46 46
47 47 pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
48 48 let app = app.clone();
49 tool_face("call-people", IconName::Users, "People", open)
49 let (background, foreground) = if open {
50 (theme::accent(), theme::on_accent())
51 } else {
52 (theme::surface_raised(), theme::text())
53 };
54 round_control("call-people", IconName::Users, background, foreground)
50 55 .relative()
51 56 .tooltip(move |window, cx| {
52 Tooltip::new(if open { "Close the people list" } else { "Show people" }).build(window, cx)
57 Tooltip::new(if open {
58 "Close the people list"
59 } else {
60 "Show people"
61 })
62 .build(window, cx)
53 63 })
54 64 .when(raised_hands > 0, |button| {
55 65 button.child(
@@ -100,8 +110,9 @@ pub fn lock_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
100 110 .font_weight(FontWeight::SEMIBOLD)
101 111 .child("The meeting is locked. Nobody new can join.")
102 112 .child(
103 pill("call-lock-unlock", "Unlock", false)
104 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_lock(false, cx))),
113 pill("call-lock-unlock", "Unlock", false).on_click(move |_, _, cx| {
114 app.update(cx, |state, cx| state.set_call_lock(false, cx))
115 }),
105 116 )
106 117 .into_any_element(),
107 118 )
@@ -113,8 +124,13 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
113 124 return popup;
114 125 }
115 126 let capability = model.capability;
116 let (mute_app, lock_app, mic_app, camera_app, options_app) =
117 (app.clone(), app.clone(), app.clone(), app.clone(), app.clone());
127 let (mute_app, lock_app, mic_app, camera_app, options_app) = (
128 app.clone(),
129 app.clone(),
130 app.clone(),
131 app.clone(),
132 app.clone(),
133 );
118 134 popup
119 135 .item(
120 136 PopupMenuItem::new("Mute all")
@@ -122,11 +138,19 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
122 138 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
123 139 )
124 140 .item(
125 PopupMenuItem::new(if capability.locked { "Unlock meeting" } else { "Lock meeting" })
126 .icon(if capability.locked { IconName::LockOpen } else { IconName::Lock })
127 .on_click(move |_, _, cx| {
128 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
129 }),
141 PopupMenuItem::new(if capability.locked {
142 "Unlock meeting"
143 } else {
144 "Lock meeting"
145 })
146 .icon(if capability.locked {
147 IconName::LockOpen
148 } else {
149 IconName::Lock
150 })
151 .on_click(move |_, _, cx| {
152 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
153 }),
130 154 )
131 155 .item(
132 156 PopupMenuItem::new(if capability.attendee_mic_off {
@@ -199,7 +223,7 @@ fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div
199 223 .when(model.can_invite(), |header| {
200 224 header.child(
201 225 Button::new("call-people-invite")
202 .label("Invite")
226 .label(tr("common.invite"))
203 227 .icon(IconName::UserPlus)
204 228 .xsmall()
205 229 .on_click(move |_, window, cx| open_invite_picker(&invite_app, window, cx)),
@@ -230,7 +254,9 @@ fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div
230 254 .hover(|button| button.bg(theme::row_hover()))
231 255 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
232 256 .child(icon(IconName::Close, 14., theme::text_muted()))
233 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.toggle_call_people(cx))),
257 .on_click(move |_, _, cx| {
258 close_app.update(cx, |state, cx| state.toggle_call_people(cx))
259 }),
234 260 )
235 261 }
236 262
@@ -293,19 +319,27 @@ fn person_row(
293 319 row: &PersonRow,
294 320 ) -> AnyElement {
295 321 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
296 let user_id = row
297 .user_id
298 .clone()
299 .or_else(|| {
300 row.own
301 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
302 .flatten()
303 });
304 let subtitle = if row.ringing { Some("Ringing") } else { row.label };
305 let (more_app, more_model, more_mri, more_name) =
306 (app.clone(), model.clone(), row.mri.clone(), row.name.clone());
322 let user_id = row.user_id.clone().or_else(|| {
323 row.own
324 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
325 .flatten()
326 });
327 let subtitle = if row.ringing {
328 Some("Ringing")
329 } else {
330 row.label
331 };
332 let (more_app, more_model, more_mri, more_name) = (
333 app.clone(),
334 model.clone(),
335 row.mri.clone(),
336 row.name.clone(),
337 );
307 338 h_flex()
308 .id(SharedString::from(format!("call-people-row-{section}-{}", row.mri)))
339 .id(SharedString::from(format!(
340 "call-people-row-{section}-{}",
341 row.mri
342 )))
309 343 .group(group.clone())
310 344 .w_full()
311 345 .h(px(ROW_HEIGHT))
@@ -314,7 +348,12 @@ fn person_row(
314 348 .gap(px(8.))
315 349 .items_center()
316 350 .hover(|row| row.bg(theme::row_hover()))
317 .child(person_avatar(&state.directory, user_id.as_deref(), &row.name, AVATAR_SIZE))
351 .child(person_avatar(
352 &state.directory,
353 user_id.as_deref(),
354 &row.name,
355 AVATAR_SIZE,
356 ))
318 357 .child(
319 358 v_flex()
320 359 .flex_1()
@@ -354,16 +393,30 @@ fn person_row(
354 393 .xsmall()
355 394 .size(px(MORE_SIZE))
356 395 .tooltip("More")
357 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
358 tile_menu(popup, &more_app, &more_model, &more_mri, &more_name, false)
359 }),
396 .dropdown_menu_with_anchor(
397 Anchor::TopRight,
398 move |popup, _, _| {
399 tile_menu(
400 popup,
401 &more_app,
402 &more_model,
403 &more_mri,
404 &more_name,
405 false,
406 )
407 },
408 ),
360 409 )
361 410 }),
362 411 )
363 412 .into_any_element()
364 413 }
365 414
366 fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSections) -> Option<Div> {
415 fn lobby_section(
416 app: &Entity<AppState>,
417 state: &AppState,
418 sections: &PeopleSections,
419 ) -> Option<Div> {
367 420 if sections.lobby.is_empty() {
368 421 return None;
369 422 }
@@ -372,24 +425,37 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
372 425 .label("Admit all")
373 426 .ghost()
374 427 .xsmall()
375 .on_click(move |_, _, cx| admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx)))
428 .on_click(move |_, _, cx| {
429 admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx))
430 })
376 431 .into_any_element();
377 432 Some(
378 433 v_flex()
379 434 .w_full()
380 .child(section_header(format!("Waiting in lobby ({})", sections.lobby.len()), Some(action)))
435 .child(section_header(
436 format!("Waiting in lobby ({})", sections.lobby.len()),
437 Some(action),
438 ))
381 439 .children(sections.lobby.iter().map(|guest| {
382 440 let (admit_app, deny_app) = (app.clone(), app.clone());
383 441 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
384 442 h_flex()
385 .id(SharedString::from(format!("call-people-lobby-{}", guest.mri)))
443 .id(SharedString::from(format!(
444 "call-people-lobby-{}",
445 guest.mri
446 )))
386 447 .w_full()
387 448 .h(px(ROW_HEIGHT))
388 449 .flex_none()
389 450 .px(px(20.))
390 451 .gap(px(8.))
391 452 .items_center()
392 .child(person_avatar(&state.directory, guest.user_id.as_deref(), &guest.name, AVATAR_SIZE))
453 .child(person_avatar(
454 &state.directory,
455 guest.user_id.as_deref(),
456 &guest.name,
457 AVATAR_SIZE,
458 ))
393 459 .child(
394 460 div()
395 461 .flex_1()
@@ -400,27 +466,40 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
400 466 .child(truncated(&guest.name, NAME_LIMIT)),
401 467 )
402 468 .child(
403 Button::new(SharedString::from(format!("call-people-admit-{}", guest.mri)))
404 .label("Admit")
405 .xsmall()
406 .on_click(move |_, _, cx| {
407 admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))
408 }),
469 Button::new(SharedString::from(format!(
470 "call-people-admit-{}",
471 guest.mri
472 )))
473 .label(tr("common.admit"))
474 .xsmall()
475 .on_click(move |_, _, cx| {
476 admit_app.update(cx, |state, cx| {
477 state.admit_call_guest(admit_mri.clone(), cx)
478 })
479 }),
409 480 )
410 481 .child(
411 Button::new(SharedString::from(format!("call-people-deny-{}", guest.mri)))
412 .label("Deny")
413 .ghost()
414 .xsmall()
415 .on_click(move |_, _, cx| {
416 deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
417 }),
482 Button::new(SharedString::from(format!(
483 "call-people-deny-{}",
484 guest.mri
485 )))
486 .label(tr("common.deny"))
487 .ghost()
488 .xsmall()
489 .on_click(move |_, _, cx| {
490 deny_app
491 .update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
492 }),
418 493 )
419 494 })),
420 495 )
421 496 }
422 497
423 pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
498 pub fn people_panel(
499 app: &Entity<AppState>,
500 state: &AppState,
501 call: &ActiveCall,
502 ) -> Option<AnyElement> {
424 503 call.people_open.then_some(())?;
425 504 let model = &call.model;
426 505 let sections = people_sections(model);
@@ -441,21 +520,37 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
441 520 .overflow_y_scrollbar()
442 521 .track_scroll(&call.people_scroll)
443 522 .pb(px(12.))
444 .children(model.can_admit().then(|| lobby_section(app, state, &sections)).flatten())
523 .children(
524 model
525 .can_admit()
526 .then(|| lobby_section(app, state, &sections))
527 .flatten(),
528 )
445 529 .when(!sections.hands.is_empty(), |list| {
446 list.child(section_header(format!("Raised hands ({})", sections.hands.len()), lower_all))
447 .children(
448 sections
449 .hands
450 .iter()
451 .map(|row| person_row(app, state, model, "hands", row)),
452 )
530 list.child(section_header(
531 format!("Raised hands ({})", sections.hands.len()),
532 lower_all,
533 ))
534 .children(
535 sections
536 .hands
537 .iter()
538 .map(|row| person_row(app, state, model, "hands", row)),
539 )
453 540 })
454 541 .children(sections.groups.iter().map(|group| {
455 542 v_flex()
456 543 .w_full()
457 .child(section_header(format!("{} ({})", group.title, group.rows.len()), None))
458 .children(group.rows.iter().map(|row| person_row(app, state, model, "group", row)))
544 .child(section_header(
545 format!("{} ({})", group.title, group.rows.len()),
546 None,
547 ))
548 .children(
549 group
550 .rows
551 .iter()
552 .map(|row| person_row(app, state, model, "group", row)),
553 )
459 554 }));
460 555 Some(
461 556 v_flex()
@@ -469,7 +564,11 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
469 564 .overflow_hidden()
470 565 .bg(theme::surface())
471 566 .child(panel_header(app, model, sections.count))
472 .child(with_top_edge(body, &call.people_scroll, PEOPLE_SCROLL_DIVIDER))
567 .child(with_top_edge(
568 body,
569 &call.people_scroll,
570 PEOPLE_SCROLL_DIVIDER,
571 ))
473 572 .into_any_element(),
474 573 )
475 574 }
@@ -502,13 +601,15 @@ fn choice_dropdown(
502 601 }
503 602 for (wire, label) in choices {
504 603 let app = app.clone();
505 popup = popup.item(PopupMenuItem::new(*label).checked(*wire == current).on_click(
506 move |_, _, cx| {
507 app.update(cx, |state, cx| {
508 state.edit_meeting_options(|options| edit(options, wire), cx)
509 })
510 },
511 ));
604 popup = popup.item(
605 PopupMenuItem::new(*label)
606 .checked(*wire == current)
607 .on_click(move |_, _, cx| {
608 app.update(cx, |state, cx| {
609 state.edit_meeting_options(|options| edit(options, wire), cx)
610 })
611 }),
612 );
512 613 }
513 614 popup
514 615 })
@@ -551,41 +652,66 @@ fn options_fields(app: &Entity<AppState>, options: &MeetingOptions) -> Div {
551 652 .gap(px(6.))
552 653 .child(option_row(
553 654 "Who can bypass the lobby",
554 choice_dropdown("options-bypass", app, &BYPASS_CHOICES, &options.bypass_lobby, |options, value| {
555 options.bypass_lobby = value.to_owned()
556 }),
655 choice_dropdown(
656 "options-bypass",
657 app,
658 &BYPASS_CHOICES,
659 &options.bypass_lobby,
660 |options, value| options.bypass_lobby = value.to_owned(),
661 ),
557 662 ))
558 663 .child(option_row(
559 664 "Who can present",
560 choice_dropdown("options-present", app, &PRESENTER_CHOICES, &options.presenters, |options, value| {
561 options.presenters = value.to_owned()
562 }),
665 choice_dropdown(
666 "options-present",
667 app,
668 &PRESENTER_CHOICES,
669 &options.presenters,
670 |options, value| options.presenters = value.to_owned(),
671 ),
563 672 ))
564 673 .child(option_row(
565 674 "Allow mic for attendees",
566 switch_field("options-mic", app, options.attendee_mic, |options, on| options.attendee_mic = on),
675 switch_field("options-mic", app, options.attendee_mic, |options, on| {
676 options.attendee_mic = on
677 }),
567 678 ))
568 679 .child(option_row(
569 680 "Allow camera for attendees",
570 switch_field("options-camera", app, options.attendee_camera, |options, on| {
571 options.attendee_camera = on
572 }),
681 switch_field(
682 "options-camera",
683 app,
684 options.attendee_camera,
685 |options, on| options.attendee_camera = on,
686 ),
573 687 ))
574 688 .child(option_row(
575 689 "Meeting chat",
576 choice_dropdown("options-chat", app, &CHAT_CHOICES, &options.meeting_chat, |options, value| {
577 options.meeting_chat = value.to_owned()
578 }),
690 choice_dropdown(
691 "options-chat",
692 app,
693 &CHAT_CHOICES,
694 &options.meeting_chat,
695 |options, value| options.meeting_chat = value.to_owned(),
696 ),
579 697 ))
580 698 .child(option_row(
581 699 "Allow reactions",
582 switch_field("options-reactions", app, options.reactions, |options, on| options.reactions = on),
700 switch_field(
701 "options-reactions",
702 app,
703 options.reactions,
704 |options, on| options.reactions = on,
705 ),
583 706 ))
584 707 .child(option_row(
585 708 "Record automatically",
586 switch_field("options-record", app, options.record_automatically, |options, on| {
587 options.record_automatically = on
588 }),
709 switch_field(
710 "options-record",
711 app,
712 options.record_automatically,
713 |options, on| options.record_automatically = on,
714 ),
589 715 ))
590 716 }
591 717
@@ -642,7 +768,9 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
642 768 .size_full()
643 769 .bg(black().opacity(DIALOG_BACKDROP))
644 770 .occlude()
645 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.close_meeting_options(cx))),
771 .on_click(move |_, _, cx| {
772 close_app.update(cx, |state, cx| state.close_meeting_options(cx))
773 }),
646 774 )
647 775 .child(
648 776 v_flex()
@@ -669,10 +797,11 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
669 797 .gap(px(8.))
670 798 .child(
671 799 Button::new("options-cancel")
672 .label("Cancel")
800 .label(tr("common.cancel"))
673 801 .ghost()
674 802 .on_click(move |_, _, cx| {
675 cancel_app.update(cx, |state, cx| state.close_meeting_options(cx))
803 cancel_app
804 .update(cx, |state, cx| state.close_meeting_options(cx))
676 805 }),
677 806 )
678 807 .child(save),
@@ -1,5 +1,5 @@
1use gpui_kit::component::scroll::ScrollableElement as _;
2use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::scroll::ScrollableElement as _;
3use gpui_kit::component::{
3use gpui_kit::component::{
4 Sizable as _,
4 Sizable as _,
5 button::{Button, ButtonVariants as _},
5 button::{Button, ButtonVariants as _},
@@ -15,10 +15,10 @@ use gpui_kit::*;
15use super::avatar::person_avatar;
15use super::avatar::person_avatar;
16use super::call_extras::open_invite_picker;
16use super::call_extras::open_invite_picker;
17use super::call_organizer::{pill, tile_menu};
17use super::call_organizer::{pill, tile_menu};
18use super::call_toolbar::tool_face;
18use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH, round_control};
19use super::call_view::{BANNER_HEIGHT, CHAT_PANEL_WIDTH, MENU_WIDTH};
20use super::widgets::{Corner, corner_badge, count_badge, icon};
21use super::scroll_edge::with_top_edge;
19use super::scroll_edge::with_top_edge;
20use super::widgets::{Corner, corner_badge, count_badge, icon};
21use crate::i18n::tr;
22use crate::app_state::AppState;
22use crate::app_state::AppState;
23use crate::call::{
23use crate::call::{
24 ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
24 ActiveCall, CallModel, OptionsDialog, PeopleSections, PersonRow, people_sections,
@@ -46,10 +46,20 @@ fn dark_text() -> Hsla {
46
46
47pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
47pub fn people_button(app: &Entity<AppState>, open: bool, raised_hands: usize) -> Stateful<Div> {
48 let app = app.clone();
48 let app = app.clone();
49 tool_face("call-people", IconName::Users, "People", open)
49 let (background, foreground) = if open {
50 (theme::accent(), theme::on_accent())
51 } else {
52 (theme::surface_raised(), theme::text())
53 };
54 round_control("call-people", IconName::Users, background, foreground)
50 .relative()
55 .relative()
51 .tooltip(move |window, cx| {
56 .tooltip(move |window, cx| {
52 Tooltip::new(if open { "Close the people list" } else { "Show people" }).build(window, cx)
57 Tooltip::new(if open {
58 "Close the people list"
59 } else {
60 "Show people"
61 })
62 .build(window, cx)
53 })
63 })
54 .when(raised_hands > 0, |button| {
64 .when(raised_hands > 0, |button| {
55 button.child(
65 button.child(
@@ -100,8 +110,9 @@ pub fn lock_banner(app: &Entity<AppState>, model: &CallModel) -> Option<AnyEleme
100 .font_weight(FontWeight::SEMIBOLD)
110 .font_weight(FontWeight::SEMIBOLD)
101 .child("The meeting is locked. Nobody new can join.")
111 .child("The meeting is locked. Nobody new can join.")
102 .child(
112 .child(
103 pill("call-lock-unlock", "Unlock", false)
113 pill("call-lock-unlock", "Unlock", false).on_click(move |_, _, cx| {
104 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_lock(false, cx))),
114 app.update(cx, |state, cx| state.set_call_lock(false, cx))
115 }),
105 )
116 )
106 .into_any_element(),
117 .into_any_element(),
107 )
118 )
@@ -113,8 +124,13 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
113 return popup;
124 return popup;
114 }
125 }
115 let capability = model.capability;
126 let capability = model.capability;
116 let (mute_app, lock_app, mic_app, camera_app, options_app) =
127 let (mute_app, lock_app, mic_app, camera_app, options_app) = (
117 (app.clone(), app.clone(), app.clone(), app.clone(), app.clone());
128 app.clone(),
129 app.clone(),
130 app.clone(),
131 app.clone(),
132 app.clone(),
133 );
118 popup
134 popup
119 .item(
135 .item(
120 PopupMenuItem::new("Mute all")
136 PopupMenuItem::new("Mute all")
@@ -122,11 +138,19 @@ fn people_menu(popup: PopupMenu, app: &Entity<AppState>, model: &CallModel) -> P
122 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
138 .on_click(move |_, _, cx| mute_app.update(cx, |state, cx| state.mute_all_call(cx))),
123 )
139 )
124 .item(
140 .item(
125 PopupMenuItem::new(if capability.locked { "Unlock meeting" } else { "Lock meeting" })
141 PopupMenuItem::new(if capability.locked {
126 .icon(if capability.locked { IconName::LockOpen } else { IconName::Lock })
142 "Unlock meeting"
127 .on_click(move |_, _, cx| {
143 } else {
128 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
144 "Lock meeting"
129 }),
145 })
146 .icon(if capability.locked {
147 IconName::LockOpen
148 } else {
149 IconName::Lock
150 })
151 .on_click(move |_, _, cx| {
152 lock_app.update(cx, |state, cx| state.set_call_lock(!capability.locked, cx))
153 }),
130 )
154 )
131 .item(
155 .item(
132 PopupMenuItem::new(if capability.attendee_mic_off {
156 PopupMenuItem::new(if capability.attendee_mic_off {
@@ -199,7 +223,7 @@ fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div
199 .when(model.can_invite(), |header| {
223 .when(model.can_invite(), |header| {
200 header.child(
224 header.child(
201 Button::new("call-people-invite")
225 Button::new("call-people-invite")
202 .label("Invite")
226 .label(tr("common.invite"))
203 .icon(IconName::UserPlus)
227 .icon(IconName::UserPlus)
204 .xsmall()
228 .xsmall()
205 .on_click(move |_, window, cx| open_invite_picker(&invite_app, window, cx)),
229 .on_click(move |_, window, cx| open_invite_picker(&invite_app, window, cx)),
@@ -230,7 +254,9 @@ fn panel_header(app: &Entity<AppState>, model: &CallModel, count: usize) -> Div
230 .hover(|button| button.bg(theme::row_hover()))
254 .hover(|button| button.bg(theme::row_hover()))
231 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
255 .tooltip(|window, cx| Tooltip::new("Close the people list").build(window, cx))
232 .child(icon(IconName::Close, 14., theme::text_muted()))
256 .child(icon(IconName::Close, 14., theme::text_muted()))
233 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.toggle_call_people(cx))),
257 .on_click(move |_, _, cx| {
258 close_app.update(cx, |state, cx| state.toggle_call_people(cx))
259 }),
234 )
260 )
235}
261}
236
262
@@ -293,19 +319,27 @@ fn person_row(
293 row: &PersonRow,
319 row: &PersonRow,
294) -> AnyElement {
320) -> AnyElement {
295 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
321 let group = SharedString::from(format!("call-people-{section}-{}", row.mri));
296 let user_id = row
322 let user_id = row.user_id.clone().or_else(|| {
297 .user_id
323 row.own
298 .clone()
324 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
299 .or_else(|| {
325 .flatten()
300 row.own
326 });
301 .then(|| state.directory.me.as_ref().map(|me| me.user_id.clone()))
327 let subtitle = if row.ringing {
302 .flatten()
328 Some("Ringing")
303 });
329 } else {
304 let subtitle = if row.ringing { Some("Ringing") } else { row.label };
330 row.label
305 let (more_app, more_model, more_mri, more_name) =
331 };
306 (app.clone(), model.clone(), row.mri.clone(), row.name.clone());
332 let (more_app, more_model, more_mri, more_name) = (
333 app.clone(),
334 model.clone(),
335 row.mri.clone(),
336 row.name.clone(),
337 );
307 h_flex()
338 h_flex()
308 .id(SharedString::from(format!("call-people-row-{section}-{}", row.mri)))
339 .id(SharedString::from(format!(
340 "call-people-row-{section}-{}",
341 row.mri
342 )))
309 .group(group.clone())
343 .group(group.clone())
310 .w_full()
344 .w_full()
311 .h(px(ROW_HEIGHT))
345 .h(px(ROW_HEIGHT))
@@ -314,7 +348,12 @@ fn person_row(
314 .gap(px(8.))
348 .gap(px(8.))
315 .items_center()
349 .items_center()
316 .hover(|row| row.bg(theme::row_hover()))
350 .hover(|row| row.bg(theme::row_hover()))
317 .child(person_avatar(&state.directory, user_id.as_deref(), &row.name, AVATAR_SIZE))
351 .child(person_avatar(
352 &state.directory,
353 user_id.as_deref(),
354 &row.name,
355 AVATAR_SIZE,
356 ))
318 .child(
357 .child(
319 v_flex()
358 v_flex()
320 .flex_1()
359 .flex_1()
@@ -354,16 +393,30 @@ fn person_row(
354 .xsmall()
393 .xsmall()
355 .size(px(MORE_SIZE))
394 .size(px(MORE_SIZE))
356 .tooltip("More")
395 .tooltip("More")
357 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
396 .dropdown_menu_with_anchor(
358 tile_menu(popup, &more_app, &more_model, &more_mri, &more_name, false)
397 Anchor::TopRight,
359 }),
398 move |popup, _, _| {
399 tile_menu(
400 popup,
401 &more_app,
402 &more_model,
403 &more_mri,
404 &more_name,
405 false,
406 )
407 },
408 ),
360 )
409 )
361 }),
410 }),
362 )
411 )
363 .into_any_element()
412 .into_any_element()
364}
413}
365
414
366fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSections) -> Option<Div> {
415fn lobby_section(
416 app: &Entity<AppState>,
417 state: &AppState,
418 sections: &PeopleSections,
419) -> Option<Div> {
367 if sections.lobby.is_empty() {
420 if sections.lobby.is_empty() {
368 return None;
421 return None;
369 }
422 }
@@ -372,24 +425,37 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
372 .label("Admit all")
425 .label("Admit all")
373 .ghost()
426 .ghost()
374 .xsmall()
427 .xsmall()
375 .on_click(move |_, _, cx| admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx)))
428 .on_click(move |_, _, cx| {
429 admit_all_app.update(cx, |state, cx| state.admit_all_call_guests(cx))
430 })
376 .into_any_element();
431 .into_any_element();
377 Some(
432 Some(
378 v_flex()
433 v_flex()
379 .w_full()
434 .w_full()
380 .child(section_header(format!("Waiting in lobby ({})", sections.lobby.len()), Some(action)))
435 .child(section_header(
436 format!("Waiting in lobby ({})", sections.lobby.len()),
437 Some(action),
438 ))
381 .children(sections.lobby.iter().map(|guest| {
439 .children(sections.lobby.iter().map(|guest| {
382 let (admit_app, deny_app) = (app.clone(), app.clone());
440 let (admit_app, deny_app) = (app.clone(), app.clone());
383 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
441 let (admit_mri, deny_mri) = (guest.mri.clone(), guest.mri.clone());
384 h_flex()
442 h_flex()
385 .id(SharedString::from(format!("call-people-lobby-{}", guest.mri)))
443 .id(SharedString::from(format!(
444 "call-people-lobby-{}",
445 guest.mri
446 )))
386 .w_full()
447 .w_full()
387 .h(px(ROW_HEIGHT))
448 .h(px(ROW_HEIGHT))
388 .flex_none()
449 .flex_none()
389 .px(px(20.))
450 .px(px(20.))
390 .gap(px(8.))
451 .gap(px(8.))
391 .items_center()
452 .items_center()
392 .child(person_avatar(&state.directory, guest.user_id.as_deref(), &guest.name, AVATAR_SIZE))
453 .child(person_avatar(
454 &state.directory,
455 guest.user_id.as_deref(),
456 &guest.name,
457 AVATAR_SIZE,
458 ))
393 .child(
459 .child(
394 div()
460 div()
395 .flex_1()
461 .flex_1()
@@ -400,27 +466,40 @@ fn lobby_section(app: &Entity<AppState>, state: &AppState, sections: &PeopleSect
400 .child(truncated(&guest.name, NAME_LIMIT)),
466 .child(truncated(&guest.name, NAME_LIMIT)),
401 )
467 )
402 .child(
468 .child(
403 Button::new(SharedString::from(format!("call-people-admit-{}", guest.mri)))
469 Button::new(SharedString::from(format!(
404 .label("Admit")
470 "call-people-admit-{}",
405 .xsmall()
471 guest.mri
406 .on_click(move |_, _, cx| {
472 )))
407 admit_app.update(cx, |state, cx| state.admit_call_guest(admit_mri.clone(), cx))
473 .label(tr("common.admit"))
408 }),
474 .xsmall()
475 .on_click(move |_, _, cx| {
476 admit_app.update(cx, |state, cx| {
477 state.admit_call_guest(admit_mri.clone(), cx)
478 })
479 }),
409 )
480 )
410 .child(
481 .child(
411 Button::new(SharedString::from(format!("call-people-deny-{}", guest.mri)))
482 Button::new(SharedString::from(format!(
412 .label("Deny")
483 "call-people-deny-{}",
413 .ghost()
484 guest.mri
414 .xsmall()
485 )))
415 .on_click(move |_, _, cx| {
486 .label(tr("common.deny"))
416 deny_app.update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
487 .ghost()
417 }),
488 .xsmall()
489 .on_click(move |_, _, cx| {
490 deny_app
491 .update(cx, |state, cx| state.deny_call_guest(deny_mri.clone(), cx))
492 }),
418 )
493 )
419 })),
494 })),
420 )
495 )
421}
496}
422
497
423pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
498pub fn people_panel(
499 app: &Entity<AppState>,
500 state: &AppState,
501 call: &ActiveCall,
502) -> Option<AnyElement> {
424 call.people_open.then_some(())?;
503 call.people_open.then_some(())?;
425 let model = &call.model;
504 let model = &call.model;
426 let sections = people_sections(model);
505 let sections = people_sections(model);
@@ -441,21 +520,37 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
441 .overflow_y_scrollbar()
520 .overflow_y_scrollbar()
442 .track_scroll(&call.people_scroll)
521 .track_scroll(&call.people_scroll)
443 .pb(px(12.))
522 .pb(px(12.))
444 .children(model.can_admit().then(|| lobby_section(app, state, &sections)).flatten())
523 .children(
524 model
525 .can_admit()
526 .then(|| lobby_section(app, state, &sections))
527 .flatten(),
528 )
445 .when(!sections.hands.is_empty(), |list| {
529 .when(!sections.hands.is_empty(), |list| {
446 list.child(section_header(format!("Raised hands ({})", sections.hands.len()), lower_all))
530 list.child(section_header(
447 .children(
531 format!("Raised hands ({})", sections.hands.len()),
448 sections
532 lower_all,
449 .hands
533 ))
450 .iter()
534 .children(
451 .map(|row| person_row(app, state, model, "hands", row)),
535 sections
452 )
536 .hands
537 .iter()
538 .map(|row| person_row(app, state, model, "hands", row)),
539 )
453 })
540 })
454 .children(sections.groups.iter().map(|group| {
541 .children(sections.groups.iter().map(|group| {
455 v_flex()
542 v_flex()
456 .w_full()
543 .w_full()
457 .child(section_header(format!("{} ({})", group.title, group.rows.len()), None))
544 .child(section_header(
458 .children(group.rows.iter().map(|row| person_row(app, state, model, "group", row)))
545 format!("{} ({})", group.title, group.rows.len()),
546 None,
547 ))
548 .children(
549 group
550 .rows
551 .iter()
552 .map(|row| person_row(app, state, model, "group", row)),
553 )
459 }));
554 }));
460 Some(
555 Some(
461 v_flex()
556 v_flex()
@@ -469,7 +564,11 @@ pub fn people_panel(app: &Entity<AppState>, state: &AppState, call: &ActiveCall)
469 .overflow_hidden()
564 .overflow_hidden()
470 .bg(theme::surface())
565 .bg(theme::surface())
471 .child(panel_header(app, model, sections.count))
566 .child(panel_header(app, model, sections.count))
472 .child(with_top_edge(body, &call.people_scroll, PEOPLE_SCROLL_DIVIDER))
567 .child(with_top_edge(
568 body,
569 &call.people_scroll,
570 PEOPLE_SCROLL_DIVIDER,
571 ))
473 .into_any_element(),
572 .into_any_element(),
474 )
573 )
475}
574}
@@ -502,13 +601,15 @@ fn choice_dropdown(
502 }
601 }
503 for (wire, label) in choices {
602 for (wire, label) in choices {
504 let app = app.clone();
603 let app = app.clone();
505 popup = popup.item(PopupMenuItem::new(*label).checked(*wire == current).on_click(
604 popup = popup.item(
506 move |_, _, cx| {
605 PopupMenuItem::new(*label)
507 app.update(cx, |state, cx| {
606 .checked(*wire == current)
508 state.edit_meeting_options(|options| edit(options, wire), cx)
607 .on_click(move |_, _, cx| {
509 })
608 app.update(cx, |state, cx| {
510 },
609 state.edit_meeting_options(|options| edit(options, wire), cx)
511 ));
610 })
611 }),
612 );
512 }
613 }
513 popup
614 popup
514 })
615 })
@@ -551,41 +652,66 @@ fn options_fields(app: &Entity<AppState>, options: &MeetingOptions) -> Div {
551 .gap(px(6.))
652 .gap(px(6.))
552 .child(option_row(
653 .child(option_row(
553 "Who can bypass the lobby",
654 "Who can bypass the lobby",
554 choice_dropdown("options-bypass", app, &BYPASS_CHOICES, &options.bypass_lobby, |options, value| {
655 choice_dropdown(
555 options.bypass_lobby = value.to_owned()
656 "options-bypass",
556 }),
657 app,
658 &BYPASS_CHOICES,
659 &options.bypass_lobby,
660 |options, value| options.bypass_lobby = value.to_owned(),
661 ),
557 ))
662 ))
558 .child(option_row(
663 .child(option_row(
559 "Who can present",
664 "Who can present",
560 choice_dropdown("options-present", app, &PRESENTER_CHOICES, &options.presenters, |options, value| {
665 choice_dropdown(
561 options.presenters = value.to_owned()
666 "options-present",
562 }),
667 app,
668 &PRESENTER_CHOICES,
669 &options.presenters,
670 |options, value| options.presenters = value.to_owned(),
671 ),
563 ))
672 ))
564 .child(option_row(
673 .child(option_row(
565 "Allow mic for attendees",
674 "Allow mic for attendees",
566 switch_field("options-mic", app, options.attendee_mic, |options, on| options.attendee_mic = on),
675 switch_field("options-mic", app, options.attendee_mic, |options, on| {
676 options.attendee_mic = on
677 }),
567 ))
678 ))
568 .child(option_row(
679 .child(option_row(
569 "Allow camera for attendees",
680 "Allow camera for attendees",
570 switch_field("options-camera", app, options.attendee_camera, |options, on| {
681 switch_field(
571 options.attendee_camera = on
682 "options-camera",
572 }),
683 app,
684 options.attendee_camera,
685 |options, on| options.attendee_camera = on,
686 ),
573 ))
687 ))
574 .child(option_row(
688 .child(option_row(
575 "Meeting chat",
689 "Meeting chat",
576 choice_dropdown("options-chat", app, &CHAT_CHOICES, &options.meeting_chat, |options, value| {
690 choice_dropdown(
577 options.meeting_chat = value.to_owned()
691 "options-chat",
578 }),
692 app,
693 &CHAT_CHOICES,
694 &options.meeting_chat,
695 |options, value| options.meeting_chat = value.to_owned(),
696 ),
579 ))
697 ))
580 .child(option_row(
698 .child(option_row(
581 "Allow reactions",
699 "Allow reactions",
582 switch_field("options-reactions", app, options.reactions, |options, on| options.reactions = on),
700 switch_field(
701 "options-reactions",
702 app,
703 options.reactions,
704 |options, on| options.reactions = on,
705 ),
583 ))
706 ))
584 .child(option_row(
707 .child(option_row(
585 "Record automatically",
708 "Record automatically",
586 switch_field("options-record", app, options.record_automatically, |options, on| {
709 switch_field(
587 options.record_automatically = on
710 "options-record",
588 }),
711 app,
712 options.record_automatically,
713 |options, on| options.record_automatically = on,
714 ),
589 ))
715 ))
590}
716}
591
717
@@ -642,7 +768,9 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
642 .size_full()
768 .size_full()
643 .bg(black().opacity(DIALOG_BACKDROP))
769 .bg(black().opacity(DIALOG_BACKDROP))
644 .occlude()
770 .occlude()
645 .on_click(move |_, _, cx| close_app.update(cx, |state, cx| state.close_meeting_options(cx))),
771 .on_click(move |_, _, cx| {
772 close_app.update(cx, |state, cx| state.close_meeting_options(cx))
773 }),
646 )
774 )
647 .child(
775 .child(
648 v_flex()
776 v_flex()
@@ -669,10 +797,11 @@ pub fn options_dialog(app: &Entity<AppState>, call: &ActiveCall) -> Option<AnyEl
669 .gap(px(8.))
797 .gap(px(8.))
670 .child(
798 .child(
671 Button::new("options-cancel")
799 Button::new("options-cancel")
672 .label("Cancel")
800 .label(tr("common.cancel"))
673 .ghost()
801 .ghost()
674 .on_click(move |_, _, cx| {
802 .on_click(move |_, _, cx| {
675 cancel_app.update(cx, |state, cx| state.close_meeting_options(cx))
803 cancel_app
804 .update(cx, |state, cx| state.close_meeting_options(cx))
676 }),
805 }),
677 )
806 )
678 .child(save),
807 .child(save),
crates/app/src/views/call_record.rs +2 −1
@@ -10,6 +10,7 @@ use gpui_kit::*;
10 10 use super::call_extras::confirm_record_action;
11 11 use super::call_transcript::TranscriptPanel;
12 12 use super::widgets::icon;
13 use crate::i18n::tr;
13 14 use crate::app_state::AppState;
14 15 use crate::call::{
15 16 CallModel, CaptionPosition, CaptionSize, RecordBlock, RecordFeature, record_actions,
@@ -236,7 +237,7 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
236 237 DialogFooter::new().child(
237 238 Button::new("captions-settings-done")
238 239 .primary()
239 .label("Done")
240 .label(tr("common.done"))
240 241 .on_click(|_, window, cx| window.close_dialog(cx)),
241 242 ),
242 243 )
@@ -10,6 +10,7 @@ use gpui_kit::*;
10use super::call_extras::confirm_record_action;
10use super::call_extras::confirm_record_action;
11use super::call_transcript::TranscriptPanel;
11use super::call_transcript::TranscriptPanel;
12use super::widgets::icon;
12use super::widgets::icon;
13use crate::i18n::tr;
13use crate::app_state::AppState;
14use crate::app_state::AppState;
14use crate::call::{
15use crate::call::{
15 CallModel, CaptionPosition, CaptionSize, RecordBlock, RecordFeature, record_actions,
16 CallModel, CaptionPosition, CaptionSize, RecordBlock, RecordFeature, record_actions,
@@ -236,7 +237,7 @@ pub fn open_captions_settings(app: &Entity<AppState>, window: &mut Window, cx: &
236 DialogFooter::new().child(
237 DialogFooter::new().child(
237 Button::new("captions-settings-done")
238 Button::new("captions-settings-done")
238 .primary()
239 .primary()
239 .label("Done")
240 .label(tr("common.done"))
240 .on_click(|_, window, cx| window.close_dialog(cx)),
241 .on_click(|_, window, cx| window.close_dialog(cx)),
241 ),
242 ),
242 )
243 )
crates/app/src/views/call_view.rs +483 −308
@@ -1,7 +1,7 @@
1 1 use std::sync::Arc;
2 2 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
3 3
4 use calling::{DeviceEntry, MicSettings, NoiseSuppression, Reaction, VideoKey};
4 use calling::{DeviceEntry, MicSettings, NoiseSuppression, Reaction, ShareKind, VideoKey};
5 5 use gpui_kit::assets::IconName;
6 6 use gpui_kit::component::{
7 7 button::{Button, ButtonVariants as _},
@@ -16,32 +16,33 @@ use gpui_kit::prelude::FluentBuilder as _;
16 16 use gpui_kit::*;
17 17
18 18 use super::avatar::person_avatar;
19 use super::call_control_fold::{Foldable, FoldedControls, fixed_controls_width, folded_for_width, in_more_menu};
20 use super::call_toolbar::{
21 GROUP_GAP, LEAVE_HEIGHT, group_divider, SPLIT_CHEVRON_WIDTH, TOOL_GAP, tool_face, tool_trigger, split_chevron,
19 use super::call_control_fold::{
20 fixed_controls_width, folded_for_width, Foldable, FoldedControls, CONTROLS_PADDING, CONTROL_GAP,
22 21 };
23 22 use super::call_extras::{
24 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
25 room_chip, whiteboard_stage,
23 consent_overlay, consult_banner, hold_panel, recording_chip, return_button, room_chip,
24 whiteboard_stage, CameraMenu,
26 25 };
27 26 use super::call_health::{health_banner, health_indicator};
28 27 use super::call_layouts::stage_region;
29 use crate::call::measured_stage;
30 28 use super::call_organizer::{
31 camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner,
29 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
32 30 more_button, pin_chip, spotlight_chip, with_tile_menu,
33 31 };
34 32 use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
35 use super::call_stage::{POP_OUT_TOOLTIP, StageMode, popped_placeholder, render_stage};
33 use super::call_stage::{popped_placeholder, render_stage, StageMode, WAITING_TEXT};
36 34 use super::call_view_menu::view_button;
37 use app_ui_kit::layout::ISLAND_GAP;
38 use super::widgets::{Corner, corner_badge, count_badge, icon};
35 use super::widgets::{corner_badge, count_badge, icon, Corner};
39 36 use crate::app_state::AppState;
40 use crate::call::REACTION_SHOWN;
37 use crate::i18n::{tr, tr_args};
38 use crate::call::measured_stage;
39 use crate::call::model::ShareMenuEntry;
41 40 use crate::call::TileSize;
41 use crate::call::REACTION_SHOWN;
42 42 use crate::call::{ActiveCall, CallKind, CallModel, Tile, TileState};
43 43 use crate::rows::reaction_glyph as chat_reaction_glyph;
44 44 use crate::theme;
45 use app_ui_kit::layout::ISLAND_GAP;
45 46
46 47 const HEADER_HEIGHT: f32 = 60.;
47 48 const RING_WIDTH: f32 = 3.;
@@ -58,40 +59,30 @@ const TILE_RADIUS: f32 = 12.;
58 59 const NAME_PLATE_BACKGROUND: f32 = 0.6;
59 60 const COMPACT_PLATE_BELOW: f32 = 200.;
60 61 pub const CHAT_PANEL_TAG: &str = "shell/islands/main/call-chat-panel";
61 pub const NO_MICROPHONE_HINT: &str = "No microphone found";
62 const AUDIO_OFF_HINT: &str = "Audio is off for this meeting";
63 pub const NO_CAMERA_HINT: &str = "No camera found";
64 pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";
65 pub const NO_WINDOWS_HINT: &str = "No windows found";
66 62 pub(super) const BANNER_HEIGHT: f32 = 40.;
67 const MAX_WINDOW_ITEMS: usize = 12;
68 63 pub const SHARE_THUMBNAIL_TAG: &str = "call/share-menu/thumbnail";
69 64 const SCREEN_THUMBNAIL: (f32, f32) = (128., 72.);
70 65 const WINDOW_THUMBNAIL: (f32, f32) = (96., 54.);
71 66 const THUMBNAIL_RADIUS: f32 = 6.;
72 67 const THUMBNAIL_ICON: f32 = 22.;
73 pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
74 68 pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
75 69 pub(super) const OVERLAY_BELOW: f32 = 720.;
76 const HEADER_END_PADDING: f32 = 8.;
77 const LEAVE_RADIUS: f32 = 6.;
70 const CONTROLS_HEIGHT: f32 = 2. * 16. + CONTROL_SIZE;
78 71 const CHAT_HEADER_HEIGHT: f32 = 48.;
79 72 const REACTION_RISE: f32 = 24.;
80 73 const REACTION_FADE_FROM: f32 = 0.75;
81 74 const REACTION_CELL: f32 = 40.;
82 const SHARE_SOUND_LABEL: &str = "Include computer sound";
83 const SHARE_MOTION_LABEL: &str = "Optimize for motion";
84 const SHARE_STANDOUT_LABEL: &str = "Show me over my content";
85 const SHARE_STANDOUT_NEEDS_CAMERA: &str = "Turn your camera on first";
86 const NOISE_SUPPRESSION_LABEL: &str = "Noise suppression";
87 const MUSIC_MODE_LABEL: &str = "Music mode";
88 const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";
89 75 const PUSH_TO_TALK_TOP: f32 = 12.;
90 76
91 77 pub fn reaction_glyph(reaction: &Reaction) -> String {
92 78 match reaction {
79 Reaction::Like => "\u{1F44D}".to_owned(),
80 // Keep VS16 so the heart stays emoji-style, not a text outline.
81 Reaction::Heart => "\u{2764}\u{FE0F}".to_owned(),
93 82 Reaction::Applause => "\u{1F44F}".to_owned(),
94 other => chat_reaction_glyph(other.name()),
83 Reaction::Laugh => "\u{1F606}".to_owned(),
84 Reaction::Surprised => "\u{1F62E}".to_owned(),
85 Reaction::Other(name) => chat_reaction_glyph(name),
95 86 }
96 87 }
97 88
@@ -121,9 +112,11 @@ fn hand_badge(position: usize, own: bool) -> Div {
121 112 .text_size(px(12.))
122 113 .font_weight(FontWeight::SEMIBOLD)
123 114 .child(if own {
124 "Hand raised".to_owned()
115 tr("calls.chrome.hand_raised")
125 116 } else {
126 format!("Hand {position}")
117 let mut args = std::collections::HashMap::new();
118 args.insert("position".to_owned(), position.to_string());
119 tr_args("calls.chrome.hand_position", &args)
127 120 })
128 121 }
129 122
@@ -143,6 +136,7 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
143 136 .rounded_full()
144 137 .bg(theme::popup())
145 138 .text_size(px(if emoji { 20. } else { 13. }))
139 .when(emoji, |chip| chip.font_family(theme::EMOJI_FONT_FAMILY))
146 140 .child(glyph)
147 141 .with_animation(
148 142 ("call-reaction", serial as usize),
@@ -177,11 +171,11 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
177 171
178 172 pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
179 173 if model.lobby {
180 (LOBBY_TEXT.to_owned(), theme::amber())
174 (tr("calls.chrome.lobby_waiting"), theme::amber())
181 175 } else if model.is_connecting() {
182 176 (model.connecting_text().to_owned(), theme::text_muted())
183 177 } else if model.is_reconnecting() {
184 ("Reconnecting...".to_owned(), theme::amber())
178 (tr("calls.chrome.reconnecting"), theme::amber())
185 179 } else if model.view.hide_timer {
186 180 (String::new(), theme::text_muted())
187 181 } else {
@@ -251,9 +245,23 @@ struct NamePlate {
251 245
252 246 fn name_plate_metrics(size: TileSize) -> NamePlate {
253 247 if size.height < COMPACT_PLATE_BELOW {
254 NamePlate { inset: 4., padding_x: 6., padding_y: 2., radius: 4., text_size: 11., max_width_share: 0.6 }
248 NamePlate {
249 inset: 4.,
250 padding_x: 6.,
251 padding_y: 2.,
252 radius: 4.,
253 text_size: 11.,
254 max_width_share: 0.6,
255 }
255 256 } else {
256 NamePlate { inset: 8., padding_x: 8., padding_y: 4., radius: 6., text_size: 12., max_width_share: 1. }
257 NamePlate {
258 inset: 8.,
259 padding_x: 8.,
260 padding_y: 4.,
261 radius: 6.,
262 text_size: 12.,
263 max_width_share: 1.,
264 }
257 265 }
258 266 }
259 267
@@ -263,7 +271,9 @@ fn name_plate(size: TileSize, name: &str) -> Div {
263 271 .absolute()
264 272 .left(px(plate.inset))
265 273 .bottom(px(plate.inset))
266 .max_w(px(((size.width - 3. * plate.inset) * plate.max_width_share).max(0.)))
274 .max_w(px(((size.width - 3. * plate.inset)
275 * plate.max_width_share)
276 .max(0.)))
267 277 .truncate()
268 278 .px(px(plate.padding_x))
269 279 .py(px(plate.padding_y))
@@ -385,29 +395,17 @@ pub fn mute_button(
385 395 } else {
386 396 (IconName::Mic, theme::surface_raised(), theme::text())
387 397 };
388 mic_action(round_control(id, glyph, background, foreground).size(px(size)), app, model)
389 }
390
391 fn toolbar_mic(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
392 let glyph = if model.muted {
393 IconName::MicOff
394 } else {
395 IconName::Mic
396 };
397 mic_action(tool_face("call-mute", glyph, "Mic", false), app, model)
398 }
399
400 fn mic_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
398 let button = round_control(id, glyph, background, foreground).size(px(size));
401 399 if !model.can_unmute() {
402 400 let hint = if model.audio_off {
403 AUDIO_OFF_HINT
401 tr("calls.chrome.audio_off_meeting")
404 402 } else {
405 NO_MICROPHONE_HINT
403 tr("calls.chrome.no_microphone")
406 404 };
407 405 return button
408 406 .opacity(DISABLED_OPACITY)
409 407 .cursor_default()
410 .tooltip(move |window, cx| Tooltip::new(hint).build(window, cx));
408 .tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx));
411 409 }
412 410 let app = app.clone();
413 411 button.on_click(move |_, _, cx| {
@@ -423,15 +421,15 @@ pub fn leave_button(
423 421 compact: bool,
424 422 ) -> Stateful<Div> {
425 423 let label = if model.is_connecting() {
426 "Cancel"
424 tr("common.cancel")
427 425 } else {
428 "Leave"
426 tr("common.leave")
429 427 };
430 428 let app = app.clone();
431 429 h_flex()
432 430 .id(id)
433 .h(px(if compact { 28. } else { LEAVE_HEIGHT }))
434 .px(px(if compact { 10. } else { 14. }))
431 .h(px(if compact { 28. } else { CONTROL_SIZE }))
432 .px(px(if compact { 10. } else { 20. }))
435 433 .gap(px(8.))
436 434 .flex_none()
437 435 .items_center()
@@ -439,13 +437,13 @@ pub fn leave_button(
439 437 .rounded_full()
440 438 .bg(theme::red())
441 439 .text_color(theme::white())
442 .text_size(px(if compact { 12. } else { 13. }))
440 .text_size(px(if compact { 12. } else { 14. }))
443 441 .font_weight(FontWeight::SEMIBOLD)
444 442 .cursor_pointer()
445 443 .hover(|button| button.opacity(0.85))
446 444 .child(icon(
447 445 IconName::PhoneOff,
448 if compact { 14. } else { 16. },
446 if compact { 14. } else { 18. },
449 447 theme::white(),
450 448 ))
451 449 .child(label)
@@ -455,7 +453,11 @@ pub fn leave_button(
455 453 })
456 454 }
457 455
458 fn share_stage_element(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
456 fn share_stage_element(
457 app: &Entity<AppState>,
458 state: &AppState,
459 call: &ActiveCall,
460 ) -> Option<AnyElement> {
459 461 if call.share_stage.popped && call.model.screen_sharer.is_some() {
460 462 return Some(popped_placeholder(app));
461 463 }
@@ -468,24 +470,14 @@ pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Statef
468 470 } else {
469 471 (IconName::VideoOff, theme::surface_raised(), theme::text())
470 472 };
471 camera_action(round_control("call-camera", glyph, background, foreground), app, model)
472 }
473
474 fn toolbar_camera(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
475 let glyph = if model.camera_on {
476 IconName::Video
477 } else {
478 IconName::VideoOff
479 };
480 camera_action(tool_face("call-camera", glyph, "Camera", false), app, model)
481 }
482
483 fn camera_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
473 let button = round_control("call-camera", glyph, background, foreground);
484 474 if !model.can_use_camera() {
485 475 return button
486 476 .opacity(DISABLED_OPACITY)
487 477 .cursor_default()
488 .tooltip(|window, cx| Tooltip::new(NO_CAMERA_HINT).build(window, cx));
478 .tooltip(|window, cx| {
479 Tooltip::new(tr("calls.chrome.no_camera")).build(window, cx)
480 });
489 481 }
490 482 let app = app.clone();
491 483 button.on_click(move |_, _, cx| {
@@ -503,7 +495,7 @@ fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
503 495 .gap(px(16.))
504 496 .items_center()
505 497 .justify_between()
506 .child(SHARE_SOUND_LABEL)
498 .child(tr("calls.chrome.include_computer_sound"))
507 499 .child(Switch::new("call-share-sound").checked(sound))
508 500 })
509 501 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
@@ -518,7 +510,7 @@ fn motion_switch_item(app: &Entity<AppState>, motion: bool) -> PopupMenuItem {
518 510 .gap(px(16.))
519 511 .items_center()
520 512 .justify_between()
521 .child(SHARE_MOTION_LABEL)
513 .child(tr("calls.chrome.optimize_motion"))
522 514 .child(Switch::new("call-share-motion").checked(motion))
523 515 })
524 516 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_motion(!motion, cx)))
@@ -537,7 +529,7 @@ fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool)
537 529 .gap(px(16.))
538 530 .items_center()
539 531 .justify_between()
540 .child(SHARE_STANDOUT_LABEL)
532 .child(tr("calls.chrome.show_me_over_content"))
541 533 .child(Switch::new("call-share-standout").checked(standout && camera_on)),
542 534 )
543 535 .when(!camera_on, |row| {
@@ -545,12 +537,14 @@ fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool)
545 537 div()
546 538 .text_size(px(11.))
547 539 .text_color(theme::text_muted())
548 .child(SHARE_STANDOUT_NEEDS_CAMERA),
540 .child(tr("calls.chrome.camera_on_first")),
549 541 )
550 542 })
551 543 })
552 544 .disabled(!camera_on)
553 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx)))
545 .on_click(move |_, _, cx| {
546 app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx))
547 })
554 548 }
555 549
556 550 fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
@@ -562,7 +556,7 @@ fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
562 556 .gap(px(16.))
563 557 .items_center()
564 558 .justify_between()
565 .child(MUSIC_MODE_LABEL)
559 .child(tr("calls.chrome.music_mode"))
566 560 .child(Switch::new("call-music-mode").checked(mic.music_mode))
567 561 })
568 562 .on_click(move |_, _, cx| {
@@ -595,7 +589,7 @@ fn push_to_talk_chip(call: &ActiveCall) -> Option<AnyElement> {
595 589 .bg(hsla(0., 0., 0., NAME_PLATE_BACKGROUND))
596 590 .text_color(theme::white())
597 591 .text_size(px(13.))
598 .child(PUSH_TO_TALK_HINT),
592 .child(tr("calls.chrome.push_to_talk")),
599 593 )
600 594 .into_any_element()
601 595 })
@@ -624,46 +618,75 @@ fn share_items(
624 618 model: &CallModel,
625 619 options: ShareOptions,
626 620 ) -> PopupMenu {
627 let screens = model.screens();
628 let single_screen = screens.len() == 1;
629 let mut popup = popup
630 .min_w(px(SHARE_MENU_WIDTH))
631 .item(sound_switch_item(app, options.sound))
632 .item(motion_switch_item(app, options.motion))
633 .item(standout_switch_item(app, options.standout, model.camera_on))
634 .separator();
635 for (index, source) in screens.into_iter().enumerate() {
636 let label = if single_screen {
637 "Share entire screen".to_owned()
638 } else {
639 format!("Share screen {}", index + 1)
621 let single_screen = model.screens().len() == 1;
622 let mut screen_index = 0usize;
623 let mut separated = false;
624 let mut popup = popup.min_w(px(SHARE_MENU_WIDTH));
625 for entry in model.share_menu_entries() {
626 popup = match entry {
627 ShareMenuEntry::Sound => popup.item(sound_switch_item(app, options.sound)),
628 ShareMenuEntry::Motion => popup.item(motion_switch_item(app, options.motion)),
629 ShareMenuEntry::Standout => {
630 popup.item(standout_switch_item(app, options.standout, model.camera_on))
631 }
632 ShareMenuEntry::Portal(kind) => {
633 if !separated {
634 popup = popup.separator();
635 separated = true;
636 }
637 let label = match kind {
638 ShareKind::Screen => tr("calls.chrome.share_entire_screen"),
639 ShareKind::Window => tr("calls.chrome.share_window"),
640 };
641 let app = app.clone();
642 popup.item(PopupMenuItem::new(label).on_click(move |_, _, cx| {
643 app.update(cx, |state, cx| state.start_portal_share(kind, cx))
644 }))
645 }
646 ShareMenuEntry::Source(source) => {
647 if !separated {
648 popup = popup.separator();
649 separated = true;
650 }
651 let (label, thumbnail, icon, size) = if source.kind == ShareKind::Screen {
652 screen_index += 1;
653 let label = if single_screen {
654 tr("calls.chrome.share_entire_screen")
655 } else {
656 {
657 let mut args = std::collections::HashMap::new();
658 args.insert("n".to_owned(), screen_index.to_string());
659 tr_args("calls.chrome.share_screen_n", &args)
660 }
661 };
662 (
663 label,
664 model.share_thumbnail(&source),
665 IconName::Monitor,
666 SCREEN_THUMBNAIL,
667 )
668 } else {
669 (
670 source.label(),
671 model.share_thumbnail(&source),
672 IconName::AppWindow,
673 WINDOW_THUMBNAIL,
674 )
675 };
676 let app = app.clone();
677 popup.item(share_source_item(label, thumbnail, icon, size).on_click(
678 move |_, _, cx| {
679 app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
680 },
681 ))
682 }
683 ShareMenuEntry::WindowHeader => popup
684 .separator()
685 .item(PopupMenuItem::label(tr("calls.chrome.share_window_ellipsis"))),
686 ShareMenuEntry::NoWindows => {
687 popup.item(PopupMenuItem::new(tr("calls.chrome.no_windows")).disabled(true))
688 }
640 689 };
641 let thumbnail = model.share_thumbnail(source);
642 let source = source.clone();
643 let app = app.clone();
644 popup = popup.item(
645 share_source_item(label, thumbnail, IconName::Monitor, SCREEN_THUMBNAIL).on_click(
646 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
647 ),
648 );
649 }
650 popup = popup
651 .separator()
652 .item(PopupMenuItem::label("Share a window..."));
653 let windows = model.windows();
654 if windows.is_empty() {
655 return popup.item(PopupMenuItem::new(NO_WINDOWS_HINT).disabled(true));
656 }
657 for source in windows.into_iter().take(MAX_WINDOW_ITEMS) {
658 let label = source.label();
659 let thumbnail = model.share_thumbnail(source);
660 let source = source.clone();
661 let app = app.clone();
662 popup = popup.item(
663 share_source_item(label, thumbnail, IconName::AppWindow, WINDOW_THUMBNAIL).on_click(
664 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
665 ),
666 );
667 690 }
668 691 popup
669 692 }
@@ -716,27 +739,44 @@ fn share_button(
716 739 ) -> AnyElement {
717 740 if model.local_share.is_some() {
718 741 let app = app.clone();
719 return tool_face("call-share-stop", IconName::ScreenShareOff, "Stop", true)
720 .tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
742 return round_control(
743 "call-share-stop",
744 IconName::ScreenShareOff,
745 theme::accent(),
746 theme::on_accent(),
747 )
748 .tooltip(|window, cx| Tooltip::new(tr("calls.chrome.stop_sharing")).build(window, cx))
721 749 .on_click(move |_, _, cx| {
722 750 cx.stop_propagation();
723 751 app.update(cx, |state, cx| state.stop_call_share(cx));
724 752 })
725 753 .into_any_element();
726 754 }
727 let face = tool_face("call-share-face", IconName::ScreenShare, "Share", false);
755 let face = round_control(
756 "call-share-face",
757 IconName::ScreenShare,
758 theme::surface_raised(),
759 theme::text(),
760 );
728 761 if !model.can_share() {
729 762 return face
730 763 .opacity(DISABLED_OPACITY)
731 764 .cursor_default()
732 .tooltip(|window, cx| Tooltip::new(NO_SHARE_HINT).build(window, cx))
765 .tooltip(|window, cx| {
766 Tooltip::new(tr("calls.chrome.sharing_when_connected")).build(window, cx)
767 })
733 768 .into_any_element();
734 769 }
735 770 let app = app.clone();
736 771 let open_app = app.clone();
737 772 let model = model.clone();
738 tool_trigger("call-share", face)
739 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
773 Button::new("call-share")
774 .ghost()
775 .p_0()
776 .size(px(CONTROL_SIZE))
777 .rounded_full()
778 .child(face)
779 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
740 780 share_items(popup, &app, &model, options)
741 781 })
742 782 .open(menu_open)
@@ -765,7 +805,11 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
765 805 .text_size(px(13.))
766 806 .font_weight(FontWeight::SEMIBOLD)
767 807 .child(icon(IconName::ScreenShare, 16., theme::on_accent()))
768 .child(format!("You are sharing: {label}"))
808 .child({
809 let mut args = std::collections::HashMap::new();
810 args.insert("label".to_owned(), label.clone());
811 tr_args("calls.chrome.sharing_label", &args)
812 })
769 813 .child(
770 814 div()
771 815 .id("call-sharing-sound")
@@ -778,9 +822,9 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
778 822 .cursor_pointer()
779 823 .hover(|button| button.opacity(0.9))
780 824 .child(if sound {
781 "Computer sound on"
825 tr("calls.chrome.computer_sound_on")
782 826 } else {
783 "Computer sound off"
827 tr("calls.chrome.computer_sound_off")
784 828 })
785 829 .on_click(move |_, _, cx| {
786 830 sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))
@@ -798,7 +842,7 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
798 842 .text_color(theme::accent())
799 843 .cursor_pointer()
800 844 .hover(|button| button.opacity(0.9))
801 .child("Stop sharing")
845 .child(tr("calls.chrome.stop_sharing"))
802 846 .on_click(move |_, _, cx| {
803 847 app.update(cx, |state, cx| state.stop_call_share(cx))
804 848 }),
@@ -809,13 +853,18 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
809 853
810 854 fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
811 855 let app = app.clone();
812 tool_face("call-chat", IconName::MessageCircle, "Chat", open)
856 let (background, foreground) = if open {
857 (theme::accent(), theme::on_accent())
858 } else {
859 (theme::surface_raised(), theme::text())
860 };
861 round_control("call-chat", IconName::MessageCircle, background, foreground)
813 862 .relative()
814 863 .tooltip(move |window, cx| {
815 864 Tooltip::new(if open {
816 "Close the chat"
865 tr("calls.chrome.close_chat")
817 866 } else {
818 "Open the chat"
867 tr("calls.chrome.open_chat")
819 868 })
820 869 .build(window, cx)
821 870 })
@@ -825,9 +874,45 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>
825 874 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
826 875 }
827 876
828 fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
877 fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
829 878 let raised = model.own_hand.is_some();
830 let face = tool_face("call-reactions-face", IconName::FaceSlightlySmiling, "React", raised);
879 let background = if raised {
880 theme::accent()
881 } else {
882 theme::surface_raised()
883 };
884 let foreground = if raised {
885 theme::on_accent()
886 } else {
887 theme::text()
888 };
889 let button = control_shell("call-hand", background).child(icon(
890 IconName::Hand,
891 CONTROL_ICON,
892 foreground,
893 ));
894 let tooltip = if raised {
895 tr("calls.chrome.lower_hand")
896 } else {
897 tr("calls.chrome.raise_hand")
898 };
899 let button = button.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx));
900 if !model.can_react() {
901 return button.opacity(DISABLED_OPACITY).cursor_default();
902 }
903 let app = app.clone();
904 button.on_click(move |_, _, cx| {
905 cx.stop_propagation();
906 app.update(cx, |state, cx| state.toggle_call_hand(cx));
907 })
908 }
909
910 fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
911 let face = control_shell("call-reactions-face", theme::surface_raised()).child(icon(
912 IconName::FaceSlightlySmiling,
913 CONTROL_ICON,
914 theme::text(),
915 ));
831 916 if !model.can_react() {
832 917 return face
833 918 .opacity(DISABLED_OPACITY)
@@ -836,14 +921,19 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
836 921 }
837 922 let app = app.clone();
838 923 Popover::new("call-reactions-popover")
839 .anchor(Anchor::TopRight)
840 .offset(px(6.))
841 .trigger(tool_trigger("call-reactions", face))
924 .anchor(Anchor::BottomLeft)
925 .offset(px(10.))
926 .trigger(
927 Button::new("call-reactions")
928 .ghost()
929 .p_0()
930 .size(px(CONTROL_SIZE))
931 .rounded_full()
932 .child(face),
933 )
842 934 .content(move |_, _, cx| {
843 935 let popover = cx.entity().downgrade();
844 let hand_app = app.clone();
845 let hand_popover = popover.clone();
846 let reactions = h_flex()
936 h_flex()
847 937 .id("call-reactions-row")
848 938 .gap(px(4.))
849 939 .children(Reaction::ALL.into_iter().map(|reaction| {
@@ -857,68 +947,23 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
857 947 .justify_center()
858 948 .rounded(px(8.))
859 949 .text_size(px(24.))
950 .font_family(theme::EMOJI_FONT_FAMILY)
860 951 .cursor_pointer()
861 952 .hover(|cell| cell.bg(theme::border_strong()))
862 953 .child(reaction_glyph(&reaction))
863 954 .on_click(move |_, window, cx| {
864 app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx));
955 app.update(cx, |state, cx| {
956 state.send_call_reaction(reaction.clone(), cx)
957 });
865 958 popover
866 959 .update(cx, |state, cx| state.dismiss(window, cx))
867 960 .ok();
868 961 })
869 }));
870 v_flex()
871 .gap(px(6.))
872 .child(reactions)
873 .child(
874 h_flex()
875 .id("call-hand")
876 .h(px(36.))
877 .px(px(10.))
878 .gap(px(8.))
879 .items_center()
880 .rounded(px(8.))
881 .cursor_pointer()
882 .when(raised, |row| row.bg(theme::accent_soft()))
883 .hover(|row| row.bg(theme::border_strong()))
884 .child(icon(IconName::Hand, 18., if raised { theme::accent_text() } else { theme::text() }))
885 .child(div().text_size(px(13.)).child(if raised { "Lower hand" } else { "Raise hand" }))
886 .on_click(move |_, window, cx| {
887 hand_app.update(cx, |state, cx| state.toggle_call_hand(cx));
888 hand_popover
889 .update(cx, |state, cx| state.dismiss(window, cx))
890 .ok();
891 }),
892 )
962 }))
893 963 })
894 964 .into_any_element()
895 965 }
896 966
897 fn pop_out_tool(app: &Entity<AppState>) -> Stateful<Div> {
898 let app = app.clone();
899 tool_face("call-pop-out", IconName::ExternalLink, POP_OUT_TOOLTIP, false)
900 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.pop_out_stage(cx)))
901 }
902
903 fn shows_pop_out(call: &ActiveCall) -> bool {
904 call.model.screen_sharer.is_some() && !call.share_stage.popped
905 }
906
907 fn leave_group(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
908 let leave = leave_button(app, model, "call-leave", false)
909 .rounded(px(LEAVE_RADIUS))
910 .debug_selector(|| "shell/islands/main/call-header/leave".into());
911 if !has_leave_menu(model) {
912 return leave.into_any_element();
913 }
914 h_flex()
915 .flex_none()
916 .gap(px(1.))
917 .child(leave.rounded_r(px(0.)))
918 .child(leave_menu(app, model))
919 .into_any_element()
920 }
921
922 967 fn has_leave_menu(model: &CallModel) -> bool {
923 968 model.kind == CallKind::Meeting
924 969 && (model.can_end_meeting || (model.can_lower_hands() && model.any_hand_raised()))
@@ -932,29 +977,21 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
932 977 Button::new("call-leave-menu")
933 978 .ghost()
934 979 .p_0()
935 .w(px(SPLIT_CHEVRON_WIDTH + 4.))
936 .h(px(LEAVE_HEIGHT))
937 .rounded_r(px(LEAVE_RADIUS))
938 .child(
939 div()
940 .id("call-leave-menu-face")
941 .size_full()
942 .flex()
943 .items_center()
944 .justify_center()
945 .rounded_r(px(LEAVE_RADIUS))
946 .bg(theme::red())
947 .cursor_pointer()
948 .hover(|face| face.opacity(0.85))
949 .child(icon(IconName::ChevronDown, 12., theme::white())),
950 )
951 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
980 .size(px(CONTROL_SIZE))
981 .rounded_full()
982 .child(round_control(
983 "call-leave-menu-face",
984 IconName::ChevronUp,
985 theme::surface_raised(),
986 theme::text(),
987 ))
988 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
952 989 let end_app = end_app.clone();
953 990 let lower_app = lower_app.clone();
954 991 let popup = popup.min_w(px(MENU_WIDTH));
955 992 let popup = if can_lower_all {
956 993 popup.item(
957 PopupMenuItem::new("Lower all hands").on_click(move |_, _, cx| {
994 PopupMenuItem::new(tr("calls.chrome.lower_all_hands")).on_click(move |_, _, cx| {
958 995 lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))
959 996 }),
960 997 )
@@ -963,7 +1000,7 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
963 1000 };
964 1001 if can_end {
965 1002 popup.item(
966 PopupMenuItem::new("End meeting for everyone")
1003 PopupMenuItem::new(tr("calls.chrome.end_meeting_for_all"))
967 1004 .icon(IconName::PhoneOff)
968 1005 .on_click(move |_, _, cx| {
969 1006 end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))
@@ -999,7 +1036,8 @@ fn devices_menu(
999 1036 mic: MicSettings,
1000 1037 ) -> PopupMenu {
1001 1038 if model.audio_off {
1002 return popup.item(PopupMenuItem::new(AUDIO_OFF_HINT).disabled(true));
1039 return popup
1040 .item(PopupMenuItem::new(tr("calls.chrome.audio_off_meeting")).disabled(true));
1003 1041 }
1004 1042 let input_app = app.clone();
1005 1043 let output_app = app.clone();
@@ -1019,9 +1057,9 @@ fn devices_menu(
1019 1057 );
1020 1058 let mut popup = popup
1021 1059 .min_w(px(MENU_WIDTH))
1022 .item(PopupMenuItem::label("Microphone"));
1060 .item(PopupMenuItem::label(tr("calls.chrome.microphone")));
1023 1061 if model.listen_only {
1024 popup = popup.item(PopupMenuItem::new(NO_MICROPHONE_HINT).disabled(true));
1062 popup = popup.item(PopupMenuItem::new(tr("calls.chrome.no_microphone")).disabled(true));
1025 1063 } else {
1026 1064 for item in inputs {
1027 1065 popup = popup.item(item);
@@ -1029,7 +1067,7 @@ fn devices_menu(
1029 1067 }
1030 1068 popup = popup
1031 1069 .separator()
1032 .item(PopupMenuItem::label(NOISE_SUPPRESSION_LABEL));
1070 .item(PopupMenuItem::label(tr("calls.chrome.noise_suppression")));
1033 1071 for level in NoiseSuppression::ALL {
1034 1072 let level_app = app.clone();
1035 1073 popup = popup.item(
@@ -1050,18 +1088,22 @@ fn devices_menu(
1050 1088 popup = popup
1051 1089 .item(music_mode_item(app, mic))
1052 1090 .separator()
1053 .item(PopupMenuItem::label("Speaker"));
1091 .item(PopupMenuItem::label(tr("calls.chrome.speaker")));
1054 1092 for item in outputs {
1055 1093 popup = popup.item(item);
1056 1094 }
1057 1095 popup
1058 1096 }
1059 1097
1060 fn mic_menu_button(app: &Entity<AppState>, model: &CallModel, mic: MicSettings) -> impl IntoElement {
1098 fn mic_menu_button(
1099 app: &Entity<AppState>,
1100 model: &CallModel,
1101 mic: MicSettings,
1102 ) -> impl IntoElement {
1061 1103 let app = app.clone();
1062 1104 let model = model.clone();
1063 split_chevron("call-mic-menu", "call-mic-menu-face")
1064 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
1105 chevron_button("call-mic-menu", "call-mic-menu-face")
1106 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
1065 1107 devices_menu(popup, &app, &model, mic)
1066 1108 })
1067 1109 }
@@ -1167,7 +1209,7 @@ pub(super) fn own_tile(
1167 1209 if own_mri.is_empty() {
1168 1210 return element;
1169 1211 }
1170 with_tile_menu(app, model, &own_mri, "You", true, element)
1212 with_tile_menu(app, model, &own_mri, &tr("common.you"), true, element)
1171 1213 }
1172 1214
1173 1215 pub(super) fn plain_own_tile(
@@ -1180,7 +1222,9 @@ pub(super) fn plain_own_tile(
1180 1222 let extras = TileExtras {
1181 1223 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1182 1224 own: true,
1183 reaction: model.own_chip(now).map(|chip| (chip.reaction.clone(), chip.serial)),
1225 reaction: model
1226 .own_chip(now)
1227 .map(|chip| (chip.reaction.clone(), chip.serial)),
1184 1228 spotlight: model.own_spotlight.is_some(),
1185 1229 pinned: model.is_pinned(own_mri),
1186 1230 fitted: false,
@@ -1200,11 +1244,12 @@ fn own_tile_body(
1200 1244 .call
1201 1245 .as_ref()
1202 1246 .and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
1247 let you = tr("common.you");
1203 1248 if let Some(image) = self_view {
1204 1249 return video_tile(
1205 1250 size,
1206 1251 image,
1207 "You",
1252 &you,
1208 1253 model.local_speaking,
1209 1254 model.muted,
1210 1255 extras,
@@ -1214,13 +1259,13 @@ fn own_tile_body(
1214 1259 let avatar = person_avatar(
1215 1260 &state.directory,
1216 1261 me.map(|person| person.user_id.as_str()),
1217 me.map_or("You", |person| person.display_name.as_str()),
1262 me.map_or(you.as_str(), |person| person.display_name.as_str()),
1218 1263 size.avatar,
1219 1264 );
1220 1265 tile(
1221 1266 size,
1222 1267 avatar,
1223 "You",
1268 &you,
1224 1269 model.local_speaking,
1225 1270 model.muted,
1226 1271 None,
@@ -1235,9 +1280,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1235 1280 if !has_more {
1236 1281 return FoldedControls::default();
1237 1282 }
1238 let mut present = Vec::new();
1283 let mut present = vec![Foldable::View];
1239 1284 if model.has_reaction_controls() {
1240 present.push(Foldable::Reactions);
1285 present.extend([Foldable::Reactions, Foldable::RaiseHand]);
1241 1286 }
1242 1287 if model.kind != CallKind::Test {
1243 1288 present.push(Foldable::People);
@@ -1245,14 +1290,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1245 1290 if call.chat_thread().is_some() {
1246 1291 present.push(Foldable::Chat);
1247 1292 }
1248 let fixed = fixed_controls_width(
1249 model.can_use_camera(),
1250 has_more,
1251 has_leave_menu(model),
1252 shows_pop_out(call),
1253 );
1293 let fixed = fixed_controls_width(model.can_use_camera(), has_more, has_leave_menu(model));
1254 1294 FoldedControls {
1255 items: in_more_menu(folded_for_width(measured_stage(call).0, fixed, &present)),
1295 items: folded_for_width(measured_stage(call).0, fixed, &present),
1256 1296 fullscreen,
1257 1297 people_open: call.people_open,
1258 1298 chat_open: call.chat_open,
@@ -1275,14 +1315,7 @@ pub fn render_call_view(
1275 1315 .w_full()
1276 1316 .h(px(HEADER_HEIGHT))
1277 1317 .flex_none()
1278 .pl(px(20.))
1279 .pr(px(HEADER_END_PADDING))
1280 .gap(px(12.))
1281 .items_center();
1282 let title_group = h_flex()
1283 .flex_1()
1284 .flex_basis(px(0.))
1285 .min_w_0()
1318 .px(px(20.))
1286 1319 .gap(px(12.))
1287 1320 .items_center()
1288 1321 .child(icon(IconName::Phone, 18., theme::accent_text()))
@@ -1304,59 +1337,40 @@ pub fn render_call_view(
1304 1337 .children(health_indicator(model))
1305 1338 .children(recording_chip(model))
1306 1339 .children(lock_chip(model))
1307 .children(room_chip(model));
1308 let end_group = h_flex()
1309 .flex_1()
1310 .flex_basis(px(0.))
1311 .min_w_0()
1312 .justify_end()
1313 .gap(px(GROUP_GAP))
1314 .items_center()
1315 .children(return_button(app, model))
1316 .child(leave_group(app, model));
1340 .children(room_chip(model))
1341 .child(div().flex_1())
1342 .children(return_button(app, model));
1317 1343
1318 1344 let hold = hold_panel(app, model);
1319 1345 let share_stage = share_stage_element(app, state, call);
1320 1346 let region = stage_region(app, state, call, now, hold, share_stage);
1321 1347
1322 1348 let folded = folded_controls(state, call, fullscreen);
1323 let panels_and_reactions = h_flex()
1324 .gap(px(TOOL_GAP))
1325 .items_center()
1326 .when(
1327 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1328 |row| row.child(reactions_button(app, model)),
1329 )
1330 .when(
1331 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1332 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1333 )
1334 .when(
1335 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1336 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1337 );
1338 let stage_and_more = h_flex()
1339 .gap(px(TOOL_GAP))
1340 .items_center()
1341 .when(shows_pop_out(call), |row| row.child(pop_out_tool(app)))
1342 .when(!folded.folds(Foldable::View), |row| {
1343 row.child(view_button(app, model, fullscreen))
1344 })
1345 .children(more_button(app, model, &folded));
1346 let devices = h_flex()
1347 .gap(px(TOOL_GAP))
1349 let controls = h_flex()
1350 .w_full()
1351 .flex_none()
1352 .py(px(16.))
1353 .px(px(CONTROLS_PADDING))
1354 .gap(px(CONTROL_GAP))
1348 1355 .items_center()
1356 .justify_center()
1349 1357 .child(
1350 1358 h_flex()
1351 .debug_selector(|| "shell/islands/main/call-header/controls/mic".into())
1359 .debug_selector(|| "shell/islands/main/call-controls/mic".into())
1360 .h(px(CONTROL_SIZE))
1352 1361 .items_center()
1353 .child(toolbar_mic(app, model))
1362 .rounded_full()
1363 .bg(theme::surface_raised())
1364 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
1354 1365 .child(mic_menu_button(app, model, state.call_mic)),
1355 1366 )
1356 1367 .child(
1357 1368 h_flex()
1369 .h(px(CONTROL_SIZE))
1358 1370 .items_center()
1359 .child(toolbar_camera(app, model))
1371 .rounded_full()
1372 .bg(theme::surface_raised())
1373 .child(camera_button(app, model))
1360 1374 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1361 1375 )
1362 1376 .child(share_button(
@@ -1364,18 +1378,34 @@ pub fn render_call_view(
1364 1378 model,
1365 1379 ShareOptions::of(state),
1366 1380 call.share_menu_open,
1367 ));
1368 let controls = h_flex()
1369 .debug_selector(|| "shell/islands/main/call-header/controls".into())
1370 .flex_none()
1371 .gap(px(GROUP_GAP))
1372 .items_center()
1373 .child(devices)
1374 .child(group_divider())
1375 .child(panels_and_reactions)
1376 .child(group_divider())
1377 .child(stage_and_more);
1378 let header = header.child(title_group).child(controls).child(end_group);
1381 ))
1382 .when(
1383 model.has_reaction_controls() && !folded.folds(Foldable::RaiseHand),
1384 |row| row.child(hand_button(app, model)),
1385 )
1386 .when(
1387 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1388 |row| row.child(reactions_button(app, model)),
1389 )
1390 .when(!folded.folds(Foldable::View), |row| {
1391 row.child(view_button(app, model, fullscreen))
1392 })
1393 .children(more_button(app, model, &folded))
1394 .when(
1395 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1396 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1397 )
1398 .when(
1399 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1400 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1401 )
1402 .child(
1403 leave_button(app, model, "call-leave", false)
1404 .debug_selector(|| "shell/islands/main/call-controls/leave".into()),
1405 )
1406 .when(has_leave_menu(model), |row| {
1407 row.child(leave_menu(app, model))
1408 });
1379 1409
1380 1410 let top = v_flex()
1381 1411 .w_full()
@@ -1406,19 +1436,28 @@ pub fn render_call_view(
1406 1436 column.child(fullscreen_chrome("call-chrome-top", app, top))
1407 1437 })
1408 1438 .child(region)
1439 .when(chrome_visible, |column| {
1440 column.child(fullscreen_chrome("call-chrome-bottom", app, controls))
1441 })
1409 1442 } else {
1410 1443 base.rounded(px(10.))
1411 1444 .child(top.debug_selector(|| "shell/islands/main/call-header".into()))
1412 1445 .child(region)
1446 .child(controls.debug_selector(|| "shell/islands/main/call-controls".into()))
1413 1447 }
1414 1448 .children(captions_overlay(model, now))
1415 1449 .children(captions_hint_chip(model))
1416 1450 .children(push_to_talk_chip(call))
1417 1451 .children(state.transfer_picker.clone())
1418 1452 .children(options_dialog(app, call))
1419 .children(consent_overlay(app, model));
1453 .children(consent_overlay(app, model))
1454 .children(local_share_float(app, state));
1455 let share_in_chat = call
1456 .chat_open
1457 .then(|| local_share_window(app, state, CHAT_PANEL_WIDTH))
1458 .flatten();
1420 1459 let panels: Vec<AnyElement> = chat
1421 .map(|chat| chat_panel(app, chat))
1460 .map(|chat| chat_panel(app, share_in_chat, chat))
1422 1461 .into_iter()
1423 1462 .chain(
1424 1463 call.transcript_open
@@ -1452,17 +1491,15 @@ fn side_panels(panels: Vec<AnyElement>, island_width: f32) -> Vec<AnyElement> {
1452 1491 if island_width - panels_width >= OVERLAY_BELOW {
1453 1492 return panels;
1454 1493 }
1455 vec![
1456 h_flex()
1457 .absolute()
1458 .top(px(HEADER_HEIGHT))
1459 .right_0()
1460 .bottom_0()
1461 .gap(px(ISLAND_GAP))
1462 .w(px(panels_width.min(island_width)))
1463 .children(panels)
1464 .into_any_element(),
1465 ]
1494 vec![h_flex()
1495 .absolute()
1496 .top_0()
1497 .right_0()
1498 .bottom(px(CONTROLS_HEIGHT))
1499 .gap(px(ISLAND_GAP))
1500 .w(px(panels_width.min(island_width)))
1501 .children(panels)
1502 .into_any_element()]
1466 1503 }
1467 1504
1468 1505 fn fullscreen_chrome(id: &'static str, app: &Entity<AppState>, content: Div) -> Stateful<Div> {
@@ -1477,19 +1514,146 @@ fn fullscreen_chrome(id: &'static str, app: &Entity<AppState>, content: Div) ->
1477 1514 .child(content)
1478 1515 }
1479 1516
1480 fn chat_panel(app: &Entity<AppState>, chat: AnyView) -> AnyElement {
1517 fn chat_panel(app: &Entity<AppState>, share: Option<AnyElement>, chat: AnyView) -> AnyElement {
1481 1518 let app = app.clone();
1519 let body = v_flex()
1520 .w_full()
1521 .flex_1()
1522 .min_h_0()
1523 .children(share)
1524 .child(div().flex_1().min_h_0().overflow_hidden().child(chat));
1482 1525 side_panel(
1483 1526 "call-chat-panel",
1484 1527 "Chat",
1485 1528 "Close the chat",
1486 1529 move |cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)),
1487 chat,
1530 body,
1488 1531 )
1489 1532 .debug_selector(|| CHAT_PANEL_TAG.into())
1490 1533 .into_any_element()
1491 1534 }
1492 1535
1536 const SHARE_WINDOW_INSET: f32 = 12.;
1537 const SHARE_WINDOW_RATIO: f32 = 9. / 16.;
1538 const SHARE_FLOAT_WIDTH: f32 = 320.;
1539
1540 /// The live local share, pinned in the meeting chat or floating on the call
1541 /// when the chat is closed.
1542 fn local_share_window(app: &Entity<AppState>, state: &AppState, width: f32) -> Option<AnyElement> {
1543 let call = state.call.as_ref()?;
1544 let label = call.model.local_share.clone()?;
1545 let image = call.pictures.live(&VideoKey::LocalScreen, Instant::now());
1546 Some(share_window(app, &label, image, width))
1547 }
1548
1549 fn local_share_float(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
1550 let call = state.call.as_ref()?;
1551 if call.chat_open {
1552 return None;
1553 }
1554 let window = local_share_window(app, state, SHARE_FLOAT_WIDTH)?;
1555 Some(
1556 div()
1557 .absolute()
1558 .right(px(16.))
1559 .bottom(px(CONTROLS_HEIGHT + 12.))
1560 .w(px(SHARE_FLOAT_WIDTH))
1561 .rounded(px(10.))
1562 .overflow_hidden()
1563 .bg(theme::surface())
1564 .shadow(theme::flyout_shadow())
1565 .child(window)
1566 .into_any_element(),
1567 )
1568 }
1569
1570 fn share_window(
1571 app: &Entity<AppState>,
1572 label: &str,
1573 image: Option<Arc<RenderImage>>,
1574 width: f32,
1575 ) -> AnyElement {
1576 let picture_width = (width - 2. * SHARE_WINDOW_INSET).max(0.);
1577 let picture_height = picture_width * SHARE_WINDOW_RATIO;
1578 let stop = app.clone();
1579 v_flex()
1580 .w_full()
1581 .flex_none()
1582 .p(px(SHARE_WINDOW_INSET))
1583 .child(
1584 div()
1585 .id("call-share-window")
1586 .relative()
1587 .w(px(picture_width))
1588 .h(px(picture_height))
1589 .rounded(px(8.))
1590 .overflow_hidden()
1591 .bg(hsla(0., 0., 0.04, 1.))
1592 .child(share_picture(image))
1593 .child(
1594 div()
1595 .absolute()
1596 .top(px(8.))
1597 .left(px(8.))
1598 .max_w(px(picture_width * 0.62))
1599 .h(px(22.))
1600 .px(px(8.))
1601 .flex()
1602 .items_center()
1603 .rounded_full()
1604 .bg(hsla(0., 0., 0., 0.6))
1605 .text_size(px(11.))
1606 .text_color(theme::white())
1607 .child(div().truncate().child(label.to_owned())),
1608 )
1609 .child(share_stop(stop)),
1610 )
1611 .into_any_element()
1612 }
1613
1614 fn share_picture(image: Option<Arc<RenderImage>>) -> AnyElement {
1615 let Some(image) = image else {
1616 return div()
1617 .size_full()
1618 .flex()
1619 .items_center()
1620 .justify_center()
1621 .px(px(12.))
1622 .text_size(px(12.))
1623 .text_color(theme::text_muted())
1624 .child(WAITING_TEXT)
1625 .into_any_element();
1626 };
1627 img(ImageSource::Render(image))
1628 .size_full()
1629 .object_fit(ObjectFit::Contain)
1630 .into_any_element()
1631 }
1632
1633 fn share_stop(app: Entity<AppState>) -> Stateful<Div> {
1634 div()
1635 .id("call-share-window-stop")
1636 .absolute()
1637 .top(px(8.))
1638 .right(px(8.))
1639 .h(px(22.))
1640 .px(px(8.))
1641 .flex()
1642 .items_center()
1643 .rounded_full()
1644 .bg(theme::red())
1645 .text_color(theme::white())
1646 .text_size(px(11.))
1647 .font_weight(FontWeight::SEMIBOLD)
1648 .cursor_pointer()
1649 .hover(|button| button.opacity(0.85))
1650 .child("Stop")
1651 .on_click(move |_, _, cx| {
1652 cx.stop_propagation();
1653 app.update(cx, |state, cx| state.stop_call_share(cx));
1654 })
1655 }
1656
1493 1657 pub fn side_panel(
1494 1658 panel_id: &'static str,
1495 1659 title: &'static str,
@@ -1541,14 +1705,25 @@ pub fn side_panel(
1541 1705
1542 1706 #[cfg(test)]
1543 1707 mod tests {
1544 use super::{TileSize, name_plate_metrics};
1708 use super::{name_plate_metrics, TileSize};
1545 1709
1546 1710 #[test]
1547 1711 fn small_strip_tiles_get_a_compact_name_plate() {
1548 let strip = name_plate_metrics(TileSize { width: 216., height: 121.5, avatar: 48. });
1549 assert_eq!((strip.text_size, strip.inset, strip.padding_y), (11., 4., 2.));
1712 let strip = name_plate_metrics(TileSize {
1713 width: 216.,
1714 height: 121.5,
1715 avatar: 48.,
1716 });
1717 assert_eq!(
1718 (strip.text_size, strip.inset, strip.padding_y),
1719 (11., 4., 2.)
1720 );
1550 1721 assert!(strip.max_width_share < 1.);
1551 let stage = name_plate_metrics(TileSize { width: 640., height: 360., avatar: 96. });
1722 let stage = name_plate_metrics(TileSize {
1723 width: 640.,
1724 height: 360.,
1725 avatar: 96.,
1726 });
1552 1727 assert_eq!((stage.text_size, stage.inset), (12., 8.));
1553 1728 }
1554 1729 }
@@ -1,7 +1,7 @@
1use std::sync::Arc;
1use std::sync::Arc;
2use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
2use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
3
3
4use calling::{DeviceEntry, MicSettings, NoiseSuppression, Reaction, VideoKey};
4use calling::{DeviceEntry, MicSettings, NoiseSuppression, Reaction, ShareKind, VideoKey};
5use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
6use gpui_kit::component::{
6use gpui_kit::component::{
7 button::{Button, ButtonVariants as _},
7 button::{Button, ButtonVariants as _},
@@ -16,32 +16,33 @@ use gpui_kit::prelude::FluentBuilder as _;
16use gpui_kit::*;
16use gpui_kit::*;
17
17
18use super::avatar::person_avatar;
18use super::avatar::person_avatar;
19use super::call_control_fold::{Foldable, FoldedControls, fixed_controls_width, folded_for_width, in_more_menu};
19use super::call_control_fold::{
20use super::call_toolbar::{
20 fixed_controls_width, folded_for_width, Foldable, FoldedControls, CONTROLS_PADDING, CONTROL_GAP,
21 GROUP_GAP, LEAVE_HEIGHT, group_divider, SPLIT_CHEVRON_WIDTH, TOOL_GAP, tool_face, tool_trigger, split_chevron,
22};
21};
23use super::call_extras::{
22use super::call_extras::{
24 CameraMenu, consent_overlay, consult_banner, hold_panel, recording_chip, return_button,
23 consent_overlay, consult_banner, hold_panel, recording_chip, return_button, room_chip,
25 room_chip, whiteboard_stage,
24 whiteboard_stage, CameraMenu,
26};
25};
27use super::call_health::{health_banner, health_indicator};
26use super::call_health::{health_banner, health_indicator};
28use super::call_layouts::stage_region;
27use super::call_layouts::stage_region;
29use crate::call::measured_stage;
30use super::call_organizer::{
28use super::call_organizer::{
31 camera_menu_button, captions_hint_chip, captions_overlay, lobby_banner,
29 camera_menu_button, captions_hint_chip, captions_overlay, chevron_button, lobby_banner,
32 more_button, pin_chip, spotlight_chip, with_tile_menu,
30 more_button, pin_chip, spotlight_chip, with_tile_menu,
33};
31};
34use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
32use super::call_people::{lock_banner, lock_chip, options_dialog, people_button, people_panel};
35use super::call_stage::{POP_OUT_TOOLTIP, StageMode, popped_placeholder, render_stage};
33use super::call_stage::{popped_placeholder, render_stage, StageMode, WAITING_TEXT};
36use super::call_view_menu::view_button;
34use super::call_view_menu::view_button;
37use app_ui_kit::layout::ISLAND_GAP;
35use super::widgets::{corner_badge, count_badge, icon, Corner};
38use super::widgets::{Corner, corner_badge, count_badge, icon};
39use crate::app_state::AppState;
36use crate::app_state::AppState;
40use crate::call::REACTION_SHOWN;
37use crate::i18n::{tr, tr_args};
38use crate::call::measured_stage;
39use crate::call::model::ShareMenuEntry;
41use crate::call::TileSize;
40use crate::call::TileSize;
41use crate::call::REACTION_SHOWN;
42use crate::call::{ActiveCall, CallKind, CallModel, Tile, TileState};
42use crate::call::{ActiveCall, CallKind, CallModel, Tile, TileState};
43use crate::rows::reaction_glyph as chat_reaction_glyph;
43use crate::rows::reaction_glyph as chat_reaction_glyph;
44use crate::theme;
44use crate::theme;
45use app_ui_kit::layout::ISLAND_GAP;
45
46
46const HEADER_HEIGHT: f32 = 60.;
47const HEADER_HEIGHT: f32 = 60.;
47const RING_WIDTH: f32 = 3.;
48const RING_WIDTH: f32 = 3.;
@@ -58,40 +59,30 @@ const TILE_RADIUS: f32 = 12.;
58const NAME_PLATE_BACKGROUND: f32 = 0.6;
59const NAME_PLATE_BACKGROUND: f32 = 0.6;
59const COMPACT_PLATE_BELOW: f32 = 200.;
60const COMPACT_PLATE_BELOW: f32 = 200.;
60pub const CHAT_PANEL_TAG: &str = "shell/islands/main/call-chat-panel";
61pub const CHAT_PANEL_TAG: &str = "shell/islands/main/call-chat-panel";
61pub const NO_MICROPHONE_HINT: &str = "No microphone found";
62const AUDIO_OFF_HINT: &str = "Audio is off for this meeting";
63pub const NO_CAMERA_HINT: &str = "No camera found";
64pub const NO_SHARE_HINT: &str = "Sharing starts once the call is connected";
65pub const NO_WINDOWS_HINT: &str = "No windows found";
66pub(super) const BANNER_HEIGHT: f32 = 40.;
62pub(super) const BANNER_HEIGHT: f32 = 40.;
67const MAX_WINDOW_ITEMS: usize = 12;
68pub const SHARE_THUMBNAIL_TAG: &str = "call/share-menu/thumbnail";
63pub const SHARE_THUMBNAIL_TAG: &str = "call/share-menu/thumbnail";
69const SCREEN_THUMBNAIL: (f32, f32) = (128., 72.);
64const SCREEN_THUMBNAIL: (f32, f32) = (128., 72.);
70const WINDOW_THUMBNAIL: (f32, f32) = (96., 54.);
65const WINDOW_THUMBNAIL: (f32, f32) = (96., 54.);
71const THUMBNAIL_RADIUS: f32 = 6.;
66const THUMBNAIL_RADIUS: f32 = 6.;
72const THUMBNAIL_ICON: f32 = 22.;
67const THUMBNAIL_ICON: f32 = 22.;
73pub const LOBBY_TEXT: &str = "Waiting in the lobby...";
74pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
68pub(super) const CHAT_PANEL_WIDTH: f32 = 320.;
75pub(super) const OVERLAY_BELOW: f32 = 720.;
69pub(super) const OVERLAY_BELOW: f32 = 720.;
76const HEADER_END_PADDING: f32 = 8.;
70const CONTROLS_HEIGHT: f32 = 2. * 16. + CONTROL_SIZE;
77const LEAVE_RADIUS: f32 = 6.;
78const CHAT_HEADER_HEIGHT: f32 = 48.;
71const CHAT_HEADER_HEIGHT: f32 = 48.;
79const REACTION_RISE: f32 = 24.;
72const REACTION_RISE: f32 = 24.;
80const REACTION_FADE_FROM: f32 = 0.75;
73const REACTION_FADE_FROM: f32 = 0.75;
81const REACTION_CELL: f32 = 40.;
74const REACTION_CELL: f32 = 40.;
82const SHARE_SOUND_LABEL: &str = "Include computer sound";
83const SHARE_MOTION_LABEL: &str = "Optimize for motion";
84const SHARE_STANDOUT_LABEL: &str = "Show me over my content";
85const SHARE_STANDOUT_NEEDS_CAMERA: &str = "Turn your camera on first";
86const NOISE_SUPPRESSION_LABEL: &str = "Noise suppression";
87const MUSIC_MODE_LABEL: &str = "Music mode";
88const PUSH_TO_TALK_HINT: &str = "Unmuted - release Ctrl+Space to mute";
89const PUSH_TO_TALK_TOP: f32 = 12.;
75const PUSH_TO_TALK_TOP: f32 = 12.;
90
76
91pub fn reaction_glyph(reaction: &Reaction) -> String {
77pub fn reaction_glyph(reaction: &Reaction) -> String {
92 match reaction {
78 match reaction {
79 Reaction::Like => "\u{1F44D}".to_owned(),
80 // Keep VS16 so the heart stays emoji-style, not a text outline.
81 Reaction::Heart => "\u{2764}\u{FE0F}".to_owned(),
93 Reaction::Applause => "\u{1F44F}".to_owned(),
82 Reaction::Applause => "\u{1F44F}".to_owned(),
94 other => chat_reaction_glyph(other.name()),
83 Reaction::Laugh => "\u{1F606}".to_owned(),
84 Reaction::Surprised => "\u{1F62E}".to_owned(),
85 Reaction::Other(name) => chat_reaction_glyph(name),
95 }
86 }
96}
87}
97
88
@@ -121,9 +112,11 @@ fn hand_badge(position: usize, own: bool) -> Div {
121 .text_size(px(12.))
112 .text_size(px(12.))
122 .font_weight(FontWeight::SEMIBOLD)
113 .font_weight(FontWeight::SEMIBOLD)
123 .child(if own {
114 .child(if own {
124 "Hand raised".to_owned()
115 tr("calls.chrome.hand_raised")
125 } else {
116 } else {
126 format!("Hand {position}")
117 let mut args = std::collections::HashMap::new();
118 args.insert("position".to_owned(), position.to_string());
119 tr_args("calls.chrome.hand_position", &args)
127 })
120 })
128}
121}
129
122
@@ -143,6 +136,7 @@ fn reaction_chip(reaction: Reaction, serial: u64) -> AnyElement {
143 .rounded_full()
136 .rounded_full()
144 .bg(theme::popup())
137 .bg(theme::popup())
145 .text_size(px(if emoji { 20. } else { 13. }))
138 .text_size(px(if emoji { 20. } else { 13. }))
139 .when(emoji, |chip| chip.font_family(theme::EMOJI_FONT_FAMILY))
146 .child(glyph)
140 .child(glyph)
147 .with_animation(
141 .with_animation(
148 ("call-reaction", serial as usize),
142 ("call-reaction", serial as usize),
@@ -177,11 +171,11 @@ fn tile_overlays(extras: &TileExtras) -> Vec<AnyElement> {
177
171
178pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
172pub fn status_line(model: &CallModel, now: Instant) -> (String, Hsla) {
179 if model.lobby {
173 if model.lobby {
180 (LOBBY_TEXT.to_owned(), theme::amber())
174 (tr("calls.chrome.lobby_waiting"), theme::amber())
181 } else if model.is_connecting() {
175 } else if model.is_connecting() {
182 (model.connecting_text().to_owned(), theme::text_muted())
176 (model.connecting_text().to_owned(), theme::text_muted())
183 } else if model.is_reconnecting() {
177 } else if model.is_reconnecting() {
184 ("Reconnecting...".to_owned(), theme::amber())
178 (tr("calls.chrome.reconnecting"), theme::amber())
185 } else if model.view.hide_timer {
179 } else if model.view.hide_timer {
186 (String::new(), theme::text_muted())
180 (String::new(), theme::text_muted())
187 } else {
181 } else {
@@ -251,9 +245,23 @@ struct NamePlate {
251
245
252fn name_plate_metrics(size: TileSize) -> NamePlate {
246fn name_plate_metrics(size: TileSize) -> NamePlate {
253 if size.height < COMPACT_PLATE_BELOW {
247 if size.height < COMPACT_PLATE_BELOW {
254 NamePlate { inset: 4., padding_x: 6., padding_y: 2., radius: 4., text_size: 11., max_width_share: 0.6 }
248 NamePlate {
249 inset: 4.,
250 padding_x: 6.,
251 padding_y: 2.,
252 radius: 4.,
253 text_size: 11.,
254 max_width_share: 0.6,
255 }
255 } else {
256 } else {
256 NamePlate { inset: 8., padding_x: 8., padding_y: 4., radius: 6., text_size: 12., max_width_share: 1. }
257 NamePlate {
258 inset: 8.,
259 padding_x: 8.,
260 padding_y: 4.,
261 radius: 6.,
262 text_size: 12.,
263 max_width_share: 1.,
264 }
257 }
265 }
258}
266}
259
267
@@ -263,7 +271,9 @@ fn name_plate(size: TileSize, name: &str) -> Div {
263 .absolute()
271 .absolute()
264 .left(px(plate.inset))
272 .left(px(plate.inset))
265 .bottom(px(plate.inset))
273 .bottom(px(plate.inset))
266 .max_w(px(((size.width - 3. * plate.inset) * plate.max_width_share).max(0.)))
274 .max_w(px(((size.width - 3. * plate.inset)
275 * plate.max_width_share)
276 .max(0.)))
267 .truncate()
277 .truncate()
268 .px(px(plate.padding_x))
278 .px(px(plate.padding_x))
269 .py(px(plate.padding_y))
279 .py(px(plate.padding_y))
@@ -385,29 +395,17 @@ pub fn mute_button(
385 } else {
395 } else {
386 (IconName::Mic, theme::surface_raised(), theme::text())
396 (IconName::Mic, theme::surface_raised(), theme::text())
387 };
397 };
388 mic_action(round_control(id, glyph, background, foreground).size(px(size)), app, model)
398 let button = round_control(id, glyph, background, foreground).size(px(size));
389}
390
391fn toolbar_mic(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
392 let glyph = if model.muted {
393 IconName::MicOff
394 } else {
395 IconName::Mic
396 };
397 mic_action(tool_face("call-mute", glyph, "Mic", false), app, model)
398}
399
400fn mic_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
401 if !model.can_unmute() {
399 if !model.can_unmute() {
402 let hint = if model.audio_off {
400 let hint = if model.audio_off {
403 AUDIO_OFF_HINT
401 tr("calls.chrome.audio_off_meeting")
404 } else {
402 } else {
405 NO_MICROPHONE_HINT
403 tr("calls.chrome.no_microphone")
406 };
404 };
407 return button
405 return button
408 .opacity(DISABLED_OPACITY)
406 .opacity(DISABLED_OPACITY)
409 .cursor_default()
407 .cursor_default()
410 .tooltip(move |window, cx| Tooltip::new(hint).build(window, cx));
408 .tooltip(move |window, cx| Tooltip::new(hint.clone()).build(window, cx));
411 }
409 }
412 let app = app.clone();
410 let app = app.clone();
413 button.on_click(move |_, _, cx| {
411 button.on_click(move |_, _, cx| {
@@ -423,15 +421,15 @@ pub fn leave_button(
423 compact: bool,
421 compact: bool,
424) -> Stateful<Div> {
422) -> Stateful<Div> {
425 let label = if model.is_connecting() {
423 let label = if model.is_connecting() {
426 "Cancel"
424 tr("common.cancel")
427 } else {
425 } else {
428 "Leave"
426 tr("common.leave")
429 };
427 };
430 let app = app.clone();
428 let app = app.clone();
431 h_flex()
429 h_flex()
432 .id(id)
430 .id(id)
433 .h(px(if compact { 28. } else { LEAVE_HEIGHT }))
431 .h(px(if compact { 28. } else { CONTROL_SIZE }))
434 .px(px(if compact { 10. } else { 14. }))
432 .px(px(if compact { 10. } else { 20. }))
435 .gap(px(8.))
433 .gap(px(8.))
436 .flex_none()
434 .flex_none()
437 .items_center()
435 .items_center()
@@ -439,13 +437,13 @@ pub fn leave_button(
439 .rounded_full()
437 .rounded_full()
440 .bg(theme::red())
438 .bg(theme::red())
441 .text_color(theme::white())
439 .text_color(theme::white())
442 .text_size(px(if compact { 12. } else { 13. }))
440 .text_size(px(if compact { 12. } else { 14. }))
443 .font_weight(FontWeight::SEMIBOLD)
441 .font_weight(FontWeight::SEMIBOLD)
444 .cursor_pointer()
442 .cursor_pointer()
445 .hover(|button| button.opacity(0.85))
443 .hover(|button| button.opacity(0.85))
446 .child(icon(
444 .child(icon(
447 IconName::PhoneOff,
445 IconName::PhoneOff,
448 if compact { 14. } else { 16. },
446 if compact { 14. } else { 18. },
449 theme::white(),
447 theme::white(),
450 ))
448 ))
451 .child(label)
449 .child(label)
@@ -455,7 +453,11 @@ pub fn leave_button(
455 })
453 })
456}
454}
457
455
458fn share_stage_element(app: &Entity<AppState>, state: &AppState, call: &ActiveCall) -> Option<AnyElement> {
456fn share_stage_element(
457 app: &Entity<AppState>,
458 state: &AppState,
459 call: &ActiveCall,
460) -> Option<AnyElement> {
459 if call.share_stage.popped && call.model.screen_sharer.is_some() {
461 if call.share_stage.popped && call.model.screen_sharer.is_some() {
460 return Some(popped_placeholder(app));
462 return Some(popped_placeholder(app));
461 }
463 }
@@ -468,24 +470,14 @@ pub(super) fn camera_button(app: &Entity<AppState>, model: &CallModel) -> Statef
468 } else {
470 } else {
469 (IconName::VideoOff, theme::surface_raised(), theme::text())
471 (IconName::VideoOff, theme::surface_raised(), theme::text())
470 };
472 };
471 camera_action(round_control("call-camera", glyph, background, foreground), app, model)
473 let button = round_control("call-camera", glyph, background, foreground);
472}
473
474fn toolbar_camera(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
475 let glyph = if model.camera_on {
476 IconName::Video
477 } else {
478 IconName::VideoOff
479 };
480 camera_action(tool_face("call-camera", glyph, "Camera", false), app, model)
481}
482
483fn camera_action(button: Stateful<Div>, app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
484 if !model.can_use_camera() {
474 if !model.can_use_camera() {
485 return button
475 return button
486 .opacity(DISABLED_OPACITY)
476 .opacity(DISABLED_OPACITY)
487 .cursor_default()
477 .cursor_default()
488 .tooltip(|window, cx| Tooltip::new(NO_CAMERA_HINT).build(window, cx));
478 .tooltip(|window, cx| {
479 Tooltip::new(tr("calls.chrome.no_camera")).build(window, cx)
480 });
489 }
481 }
490 let app = app.clone();
482 let app = app.clone();
491 button.on_click(move |_, _, cx| {
483 button.on_click(move |_, _, cx| {
@@ -503,7 +495,7 @@ fn sound_switch_item(app: &Entity<AppState>, sound: bool) -> PopupMenuItem {
503 .gap(px(16.))
495 .gap(px(16.))
504 .items_center()
496 .items_center()
505 .justify_between()
497 .justify_between()
506 .child(SHARE_SOUND_LABEL)
498 .child(tr("calls.chrome.include_computer_sound"))
507 .child(Switch::new("call-share-sound").checked(sound))
499 .child(Switch::new("call-share-sound").checked(sound))
508 })
500 })
509 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
501 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx)))
@@ -518,7 +510,7 @@ fn motion_switch_item(app: &Entity<AppState>, motion: bool) -> PopupMenuItem {
518 .gap(px(16.))
510 .gap(px(16.))
519 .items_center()
511 .items_center()
520 .justify_between()
512 .justify_between()
521 .child(SHARE_MOTION_LABEL)
513 .child(tr("calls.chrome.optimize_motion"))
522 .child(Switch::new("call-share-motion").checked(motion))
514 .child(Switch::new("call-share-motion").checked(motion))
523 })
515 })
524 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_motion(!motion, cx)))
516 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_motion(!motion, cx)))
@@ -537,7 +529,7 @@ fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool)
537 .gap(px(16.))
529 .gap(px(16.))
538 .items_center()
530 .items_center()
539 .justify_between()
531 .justify_between()
540 .child(SHARE_STANDOUT_LABEL)
532 .child(tr("calls.chrome.show_me_over_content"))
541 .child(Switch::new("call-share-standout").checked(standout && camera_on)),
533 .child(Switch::new("call-share-standout").checked(standout && camera_on)),
542 )
534 )
543 .when(!camera_on, |row| {
535 .when(!camera_on, |row| {
@@ -545,12 +537,14 @@ fn standout_switch_item(app: &Entity<AppState>, standout: bool, camera_on: bool)
545 div()
537 div()
546 .text_size(px(11.))
538 .text_size(px(11.))
547 .text_color(theme::text_muted())
539 .text_color(theme::text_muted())
548 .child(SHARE_STANDOUT_NEEDS_CAMERA),
540 .child(tr("calls.chrome.camera_on_first")),
549 )
541 )
550 })
542 })
551 })
543 })
552 .disabled(!camera_on)
544 .disabled(!camera_on)
553 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx)))
545 .on_click(move |_, _, cx| {
546 app.update(cx, |state, cx| state.set_call_share_standout(!standout, cx))
547 })
554}
548}
555
549
556fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
550fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
@@ -562,7 +556,7 @@ fn music_mode_item(app: &Entity<AppState>, mic: MicSettings) -> PopupMenuItem {
562 .gap(px(16.))
556 .gap(px(16.))
563 .items_center()
557 .items_center()
564 .justify_between()
558 .justify_between()
565 .child(MUSIC_MODE_LABEL)
559 .child(tr("calls.chrome.music_mode"))
566 .child(Switch::new("call-music-mode").checked(mic.music_mode))
560 .child(Switch::new("call-music-mode").checked(mic.music_mode))
567 })
561 })
568 .on_click(move |_, _, cx| {
562 .on_click(move |_, _, cx| {
@@ -595,7 +589,7 @@ fn push_to_talk_chip(call: &ActiveCall) -> Option<AnyElement> {
595 .bg(hsla(0., 0., 0., NAME_PLATE_BACKGROUND))
589 .bg(hsla(0., 0., 0., NAME_PLATE_BACKGROUND))
596 .text_color(theme::white())
590 .text_color(theme::white())
597 .text_size(px(13.))
591 .text_size(px(13.))
598 .child(PUSH_TO_TALK_HINT),
592 .child(tr("calls.chrome.push_to_talk")),
599 )
593 )
600 .into_any_element()
594 .into_any_element()
601 })
595 })
@@ -624,46 +618,75 @@ fn share_items(
624 model: &CallModel,
618 model: &CallModel,
625 options: ShareOptions,
619 options: ShareOptions,
626) -> PopupMenu {
620) -> PopupMenu {
627 let screens = model.screens();
621 let single_screen = model.screens().len() == 1;
628 let single_screen = screens.len() == 1;
622 let mut screen_index = 0usize;
629 let mut popup = popup
623 let mut separated = false;
630 .min_w(px(SHARE_MENU_WIDTH))
624 let mut popup = popup.min_w(px(SHARE_MENU_WIDTH));
631 .item(sound_switch_item(app, options.sound))
625 for entry in model.share_menu_entries() {
632 .item(motion_switch_item(app, options.motion))
626 popup = match entry {
633 .item(standout_switch_item(app, options.standout, model.camera_on))
627 ShareMenuEntry::Sound => popup.item(sound_switch_item(app, options.sound)),
634 .separator();
628 ShareMenuEntry::Motion => popup.item(motion_switch_item(app, options.motion)),
635 for (index, source) in screens.into_iter().enumerate() {
629 ShareMenuEntry::Standout => {
636 let label = if single_screen {
630 popup.item(standout_switch_item(app, options.standout, model.camera_on))
637 "Share entire screen".to_owned()
631 }
638 } else {
632 ShareMenuEntry::Portal(kind) => {
639 format!("Share screen {}", index + 1)
633 if !separated {
634 popup = popup.separator();
635 separated = true;
636 }
637 let label = match kind {
638 ShareKind::Screen => tr("calls.chrome.share_entire_screen"),
639 ShareKind::Window => tr("calls.chrome.share_window"),
640 };
641 let app = app.clone();
642 popup.item(PopupMenuItem::new(label).on_click(move |_, _, cx| {
643 app.update(cx, |state, cx| state.start_portal_share(kind, cx))
644 }))
645 }
646 ShareMenuEntry::Source(source) => {
647 if !separated {
648 popup = popup.separator();
649 separated = true;
650 }
651 let (label, thumbnail, icon, size) = if source.kind == ShareKind::Screen {
652 screen_index += 1;
653 let label = if single_screen {
654 tr("calls.chrome.share_entire_screen")
655 } else {
656 {
657 let mut args = std::collections::HashMap::new();
658 args.insert("n".to_owned(), screen_index.to_string());
659 tr_args("calls.chrome.share_screen_n", &args)
660 }
661 };
662 (
663 label,
664 model.share_thumbnail(&source),
665 IconName::Monitor,
666 SCREEN_THUMBNAIL,
667 )
668 } else {
669 (
670 source.label(),
671 model.share_thumbnail(&source),
672 IconName::AppWindow,
673 WINDOW_THUMBNAIL,
674 )
675 };
676 let app = app.clone();
677 popup.item(share_source_item(label, thumbnail, icon, size).on_click(
678 move |_, _, cx| {
679 app.update(cx, |state, cx| state.start_call_share(source.clone(), cx))
680 },
681 ))
682 }
683 ShareMenuEntry::WindowHeader => popup
684 .separator()
685 .item(PopupMenuItem::label(tr("calls.chrome.share_window_ellipsis"))),
686 ShareMenuEntry::NoWindows => {
687 popup.item(PopupMenuItem::new(tr("calls.chrome.no_windows")).disabled(true))
688 }
640 };
689 };
641 let thumbnail = model.share_thumbnail(source);
642 let source = source.clone();
643 let app = app.clone();
644 popup = popup.item(
645 share_source_item(label, thumbnail, IconName::Monitor, SCREEN_THUMBNAIL).on_click(
646 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
647 ),
648 );
649 }
650 popup = popup
651 .separator()
652 .item(PopupMenuItem::label("Share a window..."));
653 let windows = model.windows();
654 if windows.is_empty() {
655 return popup.item(PopupMenuItem::new(NO_WINDOWS_HINT).disabled(true));
656 }
657 for source in windows.into_iter().take(MAX_WINDOW_ITEMS) {
658 let label = source.label();
659 let thumbnail = model.share_thumbnail(source);
660 let source = source.clone();
661 let app = app.clone();
662 popup = popup.item(
663 share_source_item(label, thumbnail, IconName::AppWindow, WINDOW_THUMBNAIL).on_click(
664 move |_, _, cx| app.update(cx, |state, cx| state.start_call_share(source.clone(), cx)),
665 ),
666 );
667 }
690 }
668 popup
691 popup
669}
692}
@@ -716,27 +739,44 @@ fn share_button(
716) -> AnyElement {
739) -> AnyElement {
717 if model.local_share.is_some() {
740 if model.local_share.is_some() {
718 let app = app.clone();
741 let app = app.clone();
719 return tool_face("call-share-stop", IconName::ScreenShareOff, "Stop", true)
742 return round_control(
720 .tooltip(|window, cx| Tooltip::new("Stop sharing").build(window, cx))
743 "call-share-stop",
744 IconName::ScreenShareOff,
745 theme::accent(),
746 theme::on_accent(),
747 )
748 .tooltip(|window, cx| Tooltip::new(tr("calls.chrome.stop_sharing")).build(window, cx))
721 .on_click(move |_, _, cx| {
749 .on_click(move |_, _, cx| {
722 cx.stop_propagation();
750 cx.stop_propagation();
723 app.update(cx, |state, cx| state.stop_call_share(cx));
751 app.update(cx, |state, cx| state.stop_call_share(cx));
724 })
752 })
725 .into_any_element();
753 .into_any_element();
726 }
754 }
727 let face = tool_face("call-share-face", IconName::ScreenShare, "Share", false);
755 let face = round_control(
756 "call-share-face",
757 IconName::ScreenShare,
758 theme::surface_raised(),
759 theme::text(),
760 );
728 if !model.can_share() {
761 if !model.can_share() {
729 return face
762 return face
730 .opacity(DISABLED_OPACITY)
763 .opacity(DISABLED_OPACITY)
731 .cursor_default()
764 .cursor_default()
732 .tooltip(|window, cx| Tooltip::new(NO_SHARE_HINT).build(window, cx))
765 .tooltip(|window, cx| {
766 Tooltip::new(tr("calls.chrome.sharing_when_connected")).build(window, cx)
767 })
733 .into_any_element();
768 .into_any_element();
734 }
769 }
735 let app = app.clone();
770 let app = app.clone();
736 let open_app = app.clone();
771 let open_app = app.clone();
737 let model = model.clone();
772 let model = model.clone();
738 tool_trigger("call-share", face)
773 Button::new("call-share")
739 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
774 .ghost()
775 .p_0()
776 .size(px(CONTROL_SIZE))
777 .rounded_full()
778 .child(face)
779 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
740 share_items(popup, &app, &model, options)
780 share_items(popup, &app, &model, options)
741 })
781 })
742 .open(menu_open)
782 .open(menu_open)
@@ -765,7 +805,11 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
765 .text_size(px(13.))
805 .text_size(px(13.))
766 .font_weight(FontWeight::SEMIBOLD)
806 .font_weight(FontWeight::SEMIBOLD)
767 .child(icon(IconName::ScreenShare, 16., theme::on_accent()))
807 .child(icon(IconName::ScreenShare, 16., theme::on_accent()))
768 .child(format!("You are sharing: {label}"))
808 .child({
809 let mut args = std::collections::HashMap::new();
810 args.insert("label".to_owned(), label.clone());
811 tr_args("calls.chrome.sharing_label", &args)
812 })
769 .child(
813 .child(
770 div()
814 div()
771 .id("call-sharing-sound")
815 .id("call-sharing-sound")
@@ -778,9 +822,9 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
778 .cursor_pointer()
822 .cursor_pointer()
779 .hover(|button| button.opacity(0.9))
823 .hover(|button| button.opacity(0.9))
780 .child(if sound {
824 .child(if sound {
781 "Computer sound on"
825 tr("calls.chrome.computer_sound_on")
782 } else {
826 } else {
783 "Computer sound off"
827 tr("calls.chrome.computer_sound_off")
784 })
828 })
785 .on_click(move |_, _, cx| {
829 .on_click(move |_, _, cx| {
786 sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))
830 sound_app.update(cx, |state, cx| state.set_call_share_sound(!sound, cx))
@@ -798,7 +842,7 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
798 .text_color(theme::accent())
842 .text_color(theme::accent())
799 .cursor_pointer()
843 .cursor_pointer()
800 .hover(|button| button.opacity(0.9))
844 .hover(|button| button.opacity(0.9))
801 .child("Stop sharing")
845 .child(tr("calls.chrome.stop_sharing"))
802 .on_click(move |_, _, cx| {
846 .on_click(move |_, _, cx| {
803 app.update(cx, |state, cx| state.stop_call_share(cx))
847 app.update(cx, |state, cx| state.stop_call_share(cx))
804 }),
848 }),
@@ -809,13 +853,18 @@ fn sharing_banner(app: &Entity<AppState>, model: &CallModel, sound: bool) -> Opt
809
853
810fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
854fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div> {
811 let app = app.clone();
855 let app = app.clone();
812 tool_face("call-chat", IconName::MessageCircle, "Chat", open)
856 let (background, foreground) = if open {
857 (theme::accent(), theme::on_accent())
858 } else {
859 (theme::surface_raised(), theme::text())
860 };
861 round_control("call-chat", IconName::MessageCircle, background, foreground)
813 .relative()
862 .relative()
814 .tooltip(move |window, cx| {
863 .tooltip(move |window, cx| {
815 Tooltip::new(if open {
864 Tooltip::new(if open {
816 "Close the chat"
865 tr("calls.chrome.close_chat")
817 } else {
866 } else {
818 "Open the chat"
867 tr("calls.chrome.open_chat")
819 })
868 })
820 .build(window, cx)
869 .build(window, cx)
821 })
870 })
@@ -825,9 +874,45 @@ fn chat_button(app: &Entity<AppState>, open: bool, unread: u32) -> Stateful<Div>
825 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
874 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)))
826}
875}
827
876
828fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
877fn hand_button(app: &Entity<AppState>, model: &CallModel) -> Stateful<Div> {
829 let raised = model.own_hand.is_some();
878 let raised = model.own_hand.is_some();
830 let face = tool_face("call-reactions-face", IconName::FaceSlightlySmiling, "React", raised);
879 let background = if raised {
880 theme::accent()
881 } else {
882 theme::surface_raised()
883 };
884 let foreground = if raised {
885 theme::on_accent()
886 } else {
887 theme::text()
888 };
889 let button = control_shell("call-hand", background).child(icon(
890 IconName::Hand,
891 CONTROL_ICON,
892 foreground,
893 ));
894 let tooltip = if raised {
895 tr("calls.chrome.lower_hand")
896 } else {
897 tr("calls.chrome.raise_hand")
898 };
899 let button = button.tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx));
900 if !model.can_react() {
901 return button.opacity(DISABLED_OPACITY).cursor_default();
902 }
903 let app = app.clone();
904 button.on_click(move |_, _, cx| {
905 cx.stop_propagation();
906 app.update(cx, |state, cx| state.toggle_call_hand(cx));
907 })
908}
909
910fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
911 let face = control_shell("call-reactions-face", theme::surface_raised()).child(icon(
912 IconName::FaceSlightlySmiling,
913 CONTROL_ICON,
914 theme::text(),
915 ));
831 if !model.can_react() {
916 if !model.can_react() {
832 return face
917 return face
833 .opacity(DISABLED_OPACITY)
918 .opacity(DISABLED_OPACITY)
@@ -836,14 +921,19 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
836 }
921 }
837 let app = app.clone();
922 let app = app.clone();
838 Popover::new("call-reactions-popover")
923 Popover::new("call-reactions-popover")
839 .anchor(Anchor::TopRight)
924 .anchor(Anchor::BottomLeft)
840 .offset(px(6.))
925 .offset(px(10.))
841 .trigger(tool_trigger("call-reactions", face))
926 .trigger(
927 Button::new("call-reactions")
928 .ghost()
929 .p_0()
930 .size(px(CONTROL_SIZE))
931 .rounded_full()
932 .child(face),
933 )
842 .content(move |_, _, cx| {
934 .content(move |_, _, cx| {
843 let popover = cx.entity().downgrade();
935 let popover = cx.entity().downgrade();
844 let hand_app = app.clone();
936 h_flex()
845 let hand_popover = popover.clone();
846 let reactions = h_flex()
847 .id("call-reactions-row")
937 .id("call-reactions-row")
848 .gap(px(4.))
938 .gap(px(4.))
849 .children(Reaction::ALL.into_iter().map(|reaction| {
939 .children(Reaction::ALL.into_iter().map(|reaction| {
@@ -857,68 +947,23 @@ fn reactions_button(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
857 .justify_center()
947 .justify_center()
858 .rounded(px(8.))
948 .rounded(px(8.))
859 .text_size(px(24.))
949 .text_size(px(24.))
950 .font_family(theme::EMOJI_FONT_FAMILY)
860 .cursor_pointer()
951 .cursor_pointer()
861 .hover(|cell| cell.bg(theme::border_strong()))
952 .hover(|cell| cell.bg(theme::border_strong()))
862 .child(reaction_glyph(&reaction))
953 .child(reaction_glyph(&reaction))
863 .on_click(move |_, window, cx| {
954 .on_click(move |_, window, cx| {
864 app.update(cx, |state, cx| state.send_call_reaction(reaction.clone(), cx));
955 app.update(cx, |state, cx| {
956 state.send_call_reaction(reaction.clone(), cx)
957 });
865 popover
958 popover
866 .update(cx, |state, cx| state.dismiss(window, cx))
959 .update(cx, |state, cx| state.dismiss(window, cx))
867 .ok();
960 .ok();
868 })
961 })
869 }));
962 }))
870 v_flex()
871 .gap(px(6.))
872 .child(reactions)
873 .child(
874 h_flex()
875 .id("call-hand")
876 .h(px(36.))
877 .px(px(10.))
878 .gap(px(8.))
879 .items_center()
880 .rounded(px(8.))
881 .cursor_pointer()
882 .when(raised, |row| row.bg(theme::accent_soft()))
883 .hover(|row| row.bg(theme::border_strong()))
884 .child(icon(IconName::Hand, 18., if raised { theme::accent_text() } else { theme::text() }))
885 .child(div().text_size(px(13.)).child(if raised { "Lower hand" } else { "Raise hand" }))
886 .on_click(move |_, window, cx| {
887 hand_app.update(cx, |state, cx| state.toggle_call_hand(cx));
888 hand_popover
889 .update(cx, |state, cx| state.dismiss(window, cx))
890 .ok();
891 }),
892 )
893 })
963 })
894 .into_any_element()
964 .into_any_element()
895}
965}
896
966
897fn pop_out_tool(app: &Entity<AppState>) -> Stateful<Div> {
898 let app = app.clone();
899 tool_face("call-pop-out", IconName::ExternalLink, POP_OUT_TOOLTIP, false)
900 .on_click(move |_, _, cx| app.update(cx, |state, cx| state.pop_out_stage(cx)))
901}
902
903fn shows_pop_out(call: &ActiveCall) -> bool {
904 call.model.screen_sharer.is_some() && !call.share_stage.popped
905}
906
907fn leave_group(app: &Entity<AppState>, model: &CallModel) -> AnyElement {
908 let leave = leave_button(app, model, "call-leave", false)
909 .rounded(px(LEAVE_RADIUS))
910 .debug_selector(|| "shell/islands/main/call-header/leave".into());
911 if !has_leave_menu(model) {
912 return leave.into_any_element();
913 }
914 h_flex()
915 .flex_none()
916 .gap(px(1.))
917 .child(leave.rounded_r(px(0.)))
918 .child(leave_menu(app, model))
919 .into_any_element()
920}
921
922fn has_leave_menu(model: &CallModel) -> bool {
967fn has_leave_menu(model: &CallModel) -> bool {
923 model.kind == CallKind::Meeting
968 model.kind == CallKind::Meeting
924 && (model.can_end_meeting || (model.can_lower_hands() && model.any_hand_raised()))
969 && (model.can_end_meeting || (model.can_lower_hands() && model.any_hand_raised()))
@@ -932,29 +977,21 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
932 Button::new("call-leave-menu")
977 Button::new("call-leave-menu")
933 .ghost()
978 .ghost()
934 .p_0()
979 .p_0()
935 .w(px(SPLIT_CHEVRON_WIDTH + 4.))
980 .size(px(CONTROL_SIZE))
936 .h(px(LEAVE_HEIGHT))
981 .rounded_full()
937 .rounded_r(px(LEAVE_RADIUS))
982 .child(round_control(
938 .child(
983 "call-leave-menu-face",
939 div()
984 IconName::ChevronUp,
940 .id("call-leave-menu-face")
985 theme::surface_raised(),
941 .size_full()
986 theme::text(),
942 .flex()
987 ))
943 .items_center()
988 .dropdown_menu_with_anchor(Anchor::BottomRight, move |popup, _, _| {
944 .justify_center()
945 .rounded_r(px(LEAVE_RADIUS))
946 .bg(theme::red())
947 .cursor_pointer()
948 .hover(|face| face.opacity(0.85))
949 .child(icon(IconName::ChevronDown, 12., theme::white())),
950 )
951 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
952 let end_app = end_app.clone();
989 let end_app = end_app.clone();
953 let lower_app = lower_app.clone();
990 let lower_app = lower_app.clone();
954 let popup = popup.min_w(px(MENU_WIDTH));
991 let popup = popup.min_w(px(MENU_WIDTH));
955 let popup = if can_lower_all {
992 let popup = if can_lower_all {
956 popup.item(
993 popup.item(
957 PopupMenuItem::new("Lower all hands").on_click(move |_, _, cx| {
994 PopupMenuItem::new(tr("calls.chrome.lower_all_hands")).on_click(move |_, _, cx| {
958 lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))
995 lower_app.update(cx, |state, cx| state.lower_all_call_hands(cx))
959 }),
996 }),
960 )
997 )
@@ -963,7 +1000,7 @@ fn leave_menu(app: &Entity<AppState>, model: &CallModel) -> impl IntoElement {
963 };
1000 };
964 if can_end {
1001 if can_end {
965 popup.item(
1002 popup.item(
966 PopupMenuItem::new("End meeting for everyone")
1003 PopupMenuItem::new(tr("calls.chrome.end_meeting_for_all"))
967 .icon(IconName::PhoneOff)
1004 .icon(IconName::PhoneOff)
968 .on_click(move |_, _, cx| {
1005 .on_click(move |_, _, cx| {
969 end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))
1006 end_app.update(cx, |state, cx| state.end_meeting_for_all(cx))
@@ -999,7 +1036,8 @@ fn devices_menu(
999 mic: MicSettings,
1036 mic: MicSettings,
1000) -> PopupMenu {
1037) -> PopupMenu {
1001 if model.audio_off {
1038 if model.audio_off {
1002 return popup.item(PopupMenuItem::new(AUDIO_OFF_HINT).disabled(true));
1039 return popup
1040 .item(PopupMenuItem::new(tr("calls.chrome.audio_off_meeting")).disabled(true));
1003 }
1041 }
1004 let input_app = app.clone();
1042 let input_app = app.clone();
1005 let output_app = app.clone();
1043 let output_app = app.clone();
@@ -1019,9 +1057,9 @@ fn devices_menu(
1019 );
1057 );
1020 let mut popup = popup
1058 let mut popup = popup
1021 .min_w(px(MENU_WIDTH))
1059 .min_w(px(MENU_WIDTH))
1022 .item(PopupMenuItem::label("Microphone"));
1060 .item(PopupMenuItem::label(tr("calls.chrome.microphone")));
1023 if model.listen_only {
1061 if model.listen_only {
1024 popup = popup.item(PopupMenuItem::new(NO_MICROPHONE_HINT).disabled(true));
1062 popup = popup.item(PopupMenuItem::new(tr("calls.chrome.no_microphone")).disabled(true));
1025 } else {
1063 } else {
1026 for item in inputs {
1064 for item in inputs {
1027 popup = popup.item(item);
1065 popup = popup.item(item);
@@ -1029,7 +1067,7 @@ fn devices_menu(
1029 }
1067 }
1030 popup = popup
1068 popup = popup
1031 .separator()
1069 .separator()
1032 .item(PopupMenuItem::label(NOISE_SUPPRESSION_LABEL));
1070 .item(PopupMenuItem::label(tr("calls.chrome.noise_suppression")));
1033 for level in NoiseSuppression::ALL {
1071 for level in NoiseSuppression::ALL {
1034 let level_app = app.clone();
1072 let level_app = app.clone();
1035 popup = popup.item(
1073 popup = popup.item(
@@ -1050,18 +1088,22 @@ fn devices_menu(
1050 popup = popup
1088 popup = popup
1051 .item(music_mode_item(app, mic))
1089 .item(music_mode_item(app, mic))
1052 .separator()
1090 .separator()
1053 .item(PopupMenuItem::label("Speaker"));
1091 .item(PopupMenuItem::label(tr("calls.chrome.speaker")));
1054 for item in outputs {
1092 for item in outputs {
1055 popup = popup.item(item);
1093 popup = popup.item(item);
1056 }
1094 }
1057 popup
1095 popup
1058}
1096}
1059
1097
1060fn mic_menu_button(app: &Entity<AppState>, model: &CallModel, mic: MicSettings) -> impl IntoElement {
1098fn mic_menu_button(
1099 app: &Entity<AppState>,
1100 model: &CallModel,
1101 mic: MicSettings,
1102) -> impl IntoElement {
1061 let app = app.clone();
1103 let app = app.clone();
1062 let model = model.clone();
1104 let model = model.clone();
1063 split_chevron("call-mic-menu", "call-mic-menu-face")
1105 chevron_button("call-mic-menu", "call-mic-menu-face")
1064 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
1106 .dropdown_menu_with_anchor(Anchor::BottomLeft, move |popup, _, _| {
1065 devices_menu(popup, &app, &model, mic)
1107 devices_menu(popup, &app, &model, mic)
1066 })
1108 })
1067}
1109}
@@ -1167,7 +1209,7 @@ pub(super) fn own_tile(
1167 if own_mri.is_empty() {
1209 if own_mri.is_empty() {
1168 return element;
1210 return element;
1169 }
1211 }
1170 with_tile_menu(app, model, &own_mri, "You", true, element)
1212 with_tile_menu(app, model, &own_mri, &tr("common.you"), true, element)
1171}
1213}
1172
1214
1173pub(super) fn plain_own_tile(
1215pub(super) fn plain_own_tile(
@@ -1180,7 +1222,9 @@ pub(super) fn plain_own_tile(
1180 let extras = TileExtras {
1222 let extras = TileExtras {
1181 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1223 hand: model.own_hand.map(|rank| model.hand_position(rank)),
1182 own: true,
1224 own: true,
1183 reaction: model.own_chip(now).map(|chip| (chip.reaction.clone(), chip.serial)),
1225 reaction: model
1226 .own_chip(now)
1227 .map(|chip| (chip.reaction.clone(), chip.serial)),
1184 spotlight: model.own_spotlight.is_some(),
1228 spotlight: model.own_spotlight.is_some(),
1185 pinned: model.is_pinned(own_mri),
1229 pinned: model.is_pinned(own_mri),
1186 fitted: false,
1230 fitted: false,
@@ -1200,11 +1244,12 @@ fn own_tile_body(
1200 .call
1244 .call
1201 .as_ref()
1245 .as_ref()
1202 .and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
1246 .and_then(|call| call.pictures.live(&VideoKey::LocalCamera, now));
1247 let you = tr("common.you");
1203 if let Some(image) = self_view {
1248 if let Some(image) = self_view {
1204 return video_tile(
1249 return video_tile(
1205 size,
1250 size,
1206 image,
1251 image,
1207 "You",
1252 &you,
1208 model.local_speaking,
1253 model.local_speaking,
1209 model.muted,
1254 model.muted,
1210 extras,
1255 extras,
@@ -1214,13 +1259,13 @@ fn own_tile_body(
1214 let avatar = person_avatar(
1259 let avatar = person_avatar(
1215 &state.directory,
1260 &state.directory,
1216 me.map(|person| person.user_id.as_str()),
1261 me.map(|person| person.user_id.as_str()),
1217 me.map_or("You", |person| person.display_name.as_str()),
1262 me.map_or(you.as_str(), |person| person.display_name.as_str()),
1218 size.avatar,
1263 size.avatar,
1219 );
1264 );
1220 tile(
1265 tile(
1221 size,
1266 size,
1222 avatar,
1267 avatar,
1223 "You",
1268 &you,
1224 model.local_speaking,
1269 model.local_speaking,
1225 model.muted,
1270 model.muted,
1226 None,
1271 None,
@@ -1235,9 +1280,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1235 if !has_more {
1280 if !has_more {
1236 return FoldedControls::default();
1281 return FoldedControls::default();
1237 }
1282 }
1238 let mut present = Vec::new();
1283 let mut present = vec![Foldable::View];
1239 if model.has_reaction_controls() {
1284 if model.has_reaction_controls() {
1240 present.push(Foldable::Reactions);
1285 present.extend([Foldable::Reactions, Foldable::RaiseHand]);
1241 }
1286 }
1242 if model.kind != CallKind::Test {
1287 if model.kind != CallKind::Test {
1243 present.push(Foldable::People);
1288 present.push(Foldable::People);
@@ -1245,14 +1290,9 @@ fn folded_controls(state: &AppState, call: &ActiveCall, fullscreen: bool) -> Fol
1245 if call.chat_thread().is_some() {
1290 if call.chat_thread().is_some() {
1246 present.push(Foldable::Chat);
1291 present.push(Foldable::Chat);
1247 }
1292 }
1248 let fixed = fixed_controls_width(
1293 let fixed = fixed_controls_width(model.can_use_camera(), has_more, has_leave_menu(model));
1249 model.can_use_camera(),
1250 has_more,
1251 has_leave_menu(model),
1252 shows_pop_out(call),
1253 );
1254 FoldedControls {
1294 FoldedControls {
1255 items: in_more_menu(folded_for_width(measured_stage(call).0, fixed, &present)),
1295 items: folded_for_width(measured_stage(call).0, fixed, &present),
1256 fullscreen,
1296 fullscreen,
1257 people_open: call.people_open,
1297 people_open: call.people_open,
1258 chat_open: call.chat_open,
1298 chat_open: call.chat_open,
@@ -1275,14 +1315,7 @@ pub fn render_call_view(
1275 .w_full()
1315 .w_full()
1276 .h(px(HEADER_HEIGHT))
1316 .h(px(HEADER_HEIGHT))
1277 .flex_none()
1317 .flex_none()
1278 .pl(px(20.))
1318 .px(px(20.))
1279 .pr(px(HEADER_END_PADDING))
1280 .gap(px(12.))
1281 .items_center();
1282 let title_group = h_flex()
1283 .flex_1()
1284 .flex_basis(px(0.))
1285 .min_w_0()
1286 .gap(px(12.))
1319 .gap(px(12.))
1287 .items_center()
1320 .items_center()
1288 .child(icon(IconName::Phone, 18., theme::accent_text()))
1321 .child(icon(IconName::Phone, 18., theme::accent_text()))
@@ -1304,59 +1337,40 @@ pub fn render_call_view(
1304 .children(health_indicator(model))
1337 .children(health_indicator(model))
1305 .children(recording_chip(model))
1338 .children(recording_chip(model))
1306 .children(lock_chip(model))
1339 .children(lock_chip(model))
1307 .children(room_chip(model));
1340 .children(room_chip(model))
1308 let end_group = h_flex()
1341 .child(div().flex_1())
1309 .flex_1()
1342 .children(return_button(app, model));
1310 .flex_basis(px(0.))
1311 .min_w_0()
1312 .justify_end()
1313 .gap(px(GROUP_GAP))
1314 .items_center()
1315 .children(return_button(app, model))
1316 .child(leave_group(app, model));
1317
1343
1318 let hold = hold_panel(app, model);
1344 let hold = hold_panel(app, model);
1319 let share_stage = share_stage_element(app, state, call);
1345 let share_stage = share_stage_element(app, state, call);
1320 let region = stage_region(app, state, call, now, hold, share_stage);
1346 let region = stage_region(app, state, call, now, hold, share_stage);
1321
1347
1322 let folded = folded_controls(state, call, fullscreen);
1348 let folded = folded_controls(state, call, fullscreen);
1323 let panels_and_reactions = h_flex()
1349 let controls = h_flex()
1324 .gap(px(TOOL_GAP))
1350 .w_full()
1325 .items_center()
1351 .flex_none()
1326 .when(
1352 .py(px(16.))
1327 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1353 .px(px(CONTROLS_PADDING))
1328 |row| row.child(reactions_button(app, model)),
1354 .gap(px(CONTROL_GAP))
1329 )
1330 .when(
1331 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1332 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1333 )
1334 .when(
1335 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1336 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1337 );
1338 let stage_and_more = h_flex()
1339 .gap(px(TOOL_GAP))
1340 .items_center()
1341 .when(shows_pop_out(call), |row| row.child(pop_out_tool(app)))
1342 .when(!folded.folds(Foldable::View), |row| {
1343 row.child(view_button(app, model, fullscreen))
1344 })
1345 .children(more_button(app, model, &folded));
1346 let devices = h_flex()
1347 .gap(px(TOOL_GAP))
1348 .items_center()
1355 .items_center()
1356 .justify_center()
1349 .child(
1357 .child(
1350 h_flex()
1358 h_flex()
1351 .debug_selector(|| "shell/islands/main/call-header/controls/mic".into())
1359 .debug_selector(|| "shell/islands/main/call-controls/mic".into())
1360 .h(px(CONTROL_SIZE))
1352 .items_center()
1361 .items_center()
1353 .child(toolbar_mic(app, model))
1362 .rounded_full()
1363 .bg(theme::surface_raised())
1364 .child(mute_button(app, model, "call-mute", CONTROL_SIZE))
1354 .child(mic_menu_button(app, model, state.call_mic)),
1365 .child(mic_menu_button(app, model, state.call_mic)),
1355 )
1366 )
1356 .child(
1367 .child(
1357 h_flex()
1368 h_flex()
1369 .h(px(CONTROL_SIZE))
1358 .items_center()
1370 .items_center()
1359 .child(toolbar_camera(app, model))
1371 .rounded_full()
1372 .bg(theme::surface_raised())
1373 .child(camera_button(app, model))
1360 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1374 .children(camera_menu_button(app, model, CameraMenu::of(state))),
1361 )
1375 )
1362 .child(share_button(
1376 .child(share_button(
@@ -1364,18 +1378,34 @@ pub fn render_call_view(
1364 model,
1378 model,
1365 ShareOptions::of(state),
1379 ShareOptions::of(state),
1366 call.share_menu_open,
1380 call.share_menu_open,
1367 ));
1381 ))
1368 let controls = h_flex()
1382 .when(
1369 .debug_selector(|| "shell/islands/main/call-header/controls".into())
1383 model.has_reaction_controls() && !folded.folds(Foldable::RaiseHand),
1370 .flex_none()
1384 |row| row.child(hand_button(app, model)),
1371 .gap(px(GROUP_GAP))
1385 )
1372 .items_center()
1386 .when(
1373 .child(devices)
1387 model.has_reaction_controls() && !folded.folds(Foldable::Reactions),
1374 .child(group_divider())
1388 |row| row.child(reactions_button(app, model)),
1375 .child(panels_and_reactions)
1389 )
1376 .child(group_divider())
1390 .when(!folded.folds(Foldable::View), |row| {
1377 .child(stage_and_more);
1391 row.child(view_button(app, model, fullscreen))
1378 let header = header.child(title_group).child(controls).child(end_group);
1392 })
1393 .children(more_button(app, model, &folded))
1394 .when(
1395 model.kind != CallKind::Test && !folded.folds(Foldable::People),
1396 |row| row.child(people_button(app, call.people_open, model.raised_hands())),
1397 )
1398 .when(
1399 call.chat_thread().is_some() && !folded.folds(Foldable::Chat),
1400 |row| row.child(chat_button(app, call.chat_open, state.call_chat_unread())),
1401 )
1402 .child(
1403 leave_button(app, model, "call-leave", false)
1404 .debug_selector(|| "shell/islands/main/call-controls/leave".into()),
1405 )
1406 .when(has_leave_menu(model), |row| {
1407 row.child(leave_menu(app, model))
1408 });
1379
1409
1380 let top = v_flex()
1410 let top = v_flex()
1381 .w_full()
1411 .w_full()
@@ -1406,19 +1436,28 @@ pub fn render_call_view(
1406 column.child(fullscreen_chrome("call-chrome-top", app, top))
1436 column.child(fullscreen_chrome("call-chrome-top", app, top))
1407 })
1437 })
1408 .child(region)
1438 .child(region)
1439 .when(chrome_visible, |column| {
1440 column.child(fullscreen_chrome("call-chrome-bottom", app, controls))
1441 })
1409 } else {
1442 } else {
1410 base.rounded(px(10.))
1443 base.rounded(px(10.))
1411 .child(top.debug_selector(|| "shell/islands/main/call-header".into()))
1444 .child(top.debug_selector(|| "shell/islands/main/call-header".into()))
1412 .child(region)
1445 .child(region)
1446 .child(controls.debug_selector(|| "shell/islands/main/call-controls".into()))
1413 }
1447 }
1414 .children(captions_overlay(model, now))
1448 .children(captions_overlay(model, now))
1415 .children(captions_hint_chip(model))
1449 .children(captions_hint_chip(model))
1416 .children(push_to_talk_chip(call))
1450 .children(push_to_talk_chip(call))
1417 .children(state.transfer_picker.clone())
1451 .children(state.transfer_picker.clone())
1418 .children(options_dialog(app, call))
1452 .children(options_dialog(app, call))
1419 .children(consent_overlay(app, model));
1453 .children(consent_overlay(app, model))
1454 .children(local_share_float(app, state));
1455 let share_in_chat = call
1456 .chat_open
1457 .then(|| local_share_window(app, state, CHAT_PANEL_WIDTH))
1458 .flatten();
1420 let panels: Vec<AnyElement> = chat
1459 let panels: Vec<AnyElement> = chat
1421 .map(|chat| chat_panel(app, chat))
1460 .map(|chat| chat_panel(app, share_in_chat, chat))
1422 .into_iter()
1461 .into_iter()
1423 .chain(
1462 .chain(
1424 call.transcript_open
1463 call.transcript_open
@@ -1452,17 +1491,15 @@ fn side_panels(panels: Vec<AnyElement>, island_width: f32) -> Vec<AnyElement> {
1452 if island_width - panels_width >= OVERLAY_BELOW {
1491 if island_width - panels_width >= OVERLAY_BELOW {
1453 return panels;
1492 return panels;
1454 }
1493 }
1455 vec![
1494 vec![h_flex()
1456 h_flex()
1495 .absolute()
1457 .absolute()
1496 .top_0()
1458 .top(px(HEADER_HEIGHT))
1497 .right_0()
1459 .right_0()
1498 .bottom(px(CONTROLS_HEIGHT))
1460 .bottom_0()
1499 .gap(px(ISLAND_GAP))
1461 .gap(px(ISLAND_GAP))
1500 .w(px(panels_width.min(island_width)))
1462 .w(px(panels_width.min(island_width)))
1501 .children(panels)
1463 .children(panels)
1502 .into_any_element()]
1464 .into_any_element(),
1465 ]
1466}
1503}
1467
1504
1468fn fullscreen_chrome(id: &'static str, app: &Entity<AppState>, content: Div) -> Stateful<Div> {
1505fn fullscreen_chrome(id: &'static str, app: &Entity<AppState>, content: Div) -> Stateful<Div> {
@@ -1477,19 +1514,146 @@ fn fullscreen_chrome(id: &'static str, app: &Entity<AppState>, content: Div) ->
1477 .child(content)
1514 .child(content)
1478}
1515}
1479
1516
1480fn chat_panel(app: &Entity<AppState>, chat: AnyView) -> AnyElement {
1517fn chat_panel(app: &Entity<AppState>, share: Option<AnyElement>, chat: AnyView) -> AnyElement {
1481 let app = app.clone();
1518 let app = app.clone();
1519 let body = v_flex()
1520 .w_full()
1521 .flex_1()
1522 .min_h_0()
1523 .children(share)
1524 .child(div().flex_1().min_h_0().overflow_hidden().child(chat));
1482 side_panel(
1525 side_panel(
1483 "call-chat-panel",
1526 "call-chat-panel",
1484 "Chat",
1527 "Chat",
1485 "Close the chat",
1528 "Close the chat",
1486 move |cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)),
1529 move |cx| app.update(cx, |state, cx| state.toggle_call_chat(cx)),
1487 chat,
1530 body,
1488 )
1531 )
1489 .debug_selector(|| CHAT_PANEL_TAG.into())
1532 .debug_selector(|| CHAT_PANEL_TAG.into())
1490 .into_any_element()
1533 .into_any_element()
1491}
1534}
1492
1535
1536const SHARE_WINDOW_INSET: f32 = 12.;
1537const SHARE_WINDOW_RATIO: f32 = 9. / 16.;
1538const SHARE_FLOAT_WIDTH: f32 = 320.;
1539
1540/// The live local share, pinned in the meeting chat or floating on the call
1541/// when the chat is closed.
1542fn local_share_window(app: &Entity<AppState>, state: &AppState, width: f32) -> Option<AnyElement> {
1543 let call = state.call.as_ref()?;
1544 let label = call.model.local_share.clone()?;
1545 let image = call.pictures.live(&VideoKey::LocalScreen, Instant::now());
1546 Some(share_window(app, &label, image, width))
1547}
1548
1549fn local_share_float(app: &Entity<AppState>, state: &AppState) -> Option<AnyElement> {
1550 let call = state.call.as_ref()?;
1551 if call.chat_open {
1552 return None;
1553 }
1554 let window = local_share_window(app, state, SHARE_FLOAT_WIDTH)?;
1555 Some(
1556 div()
1557 .absolute()
1558 .right(px(16.))
1559 .bottom(px(CONTROLS_HEIGHT + 12.))
1560 .w(px(SHARE_FLOAT_WIDTH))
1561 .rounded(px(10.))
1562 .overflow_hidden()
1563 .bg(theme::surface())
1564 .shadow(theme::flyout_shadow())
1565 .child(window)
1566 .into_any_element(),
1567 )
1568}
1569
1570fn share_window(
1571 app: &Entity<AppState>,
1572 label: &str,
1573 image: Option<Arc<RenderImage>>,
1574 width: f32,
1575) -> AnyElement {
1576 let picture_width = (width - 2. * SHARE_WINDOW_INSET).max(0.);
1577 let picture_height = picture_width * SHARE_WINDOW_RATIO;
1578 let stop = app.clone();
1579 v_flex()
1580 .w_full()
1581 .flex_none()
1582 .p(px(SHARE_WINDOW_INSET))
1583 .child(
1584 div()
1585 .id("call-share-window")
1586 .relative()
1587 .w(px(picture_width))
1588 .h(px(picture_height))
1589 .rounded(px(8.))
1590 .overflow_hidden()
1591 .bg(hsla(0., 0., 0.04, 1.))
1592 .child(share_picture(image))
1593 .child(
1594 div()
1595 .absolute()
1596 .top(px(8.))
1597 .left(px(8.))
1598 .max_w(px(picture_width * 0.62))
1599 .h(px(22.))
1600 .px(px(8.))
1601 .flex()
1602 .items_center()
1603 .rounded_full()
1604 .bg(hsla(0., 0., 0., 0.6))
1605 .text_size(px(11.))
1606 .text_color(theme::white())
1607 .child(div().truncate().child(label.to_owned())),
1608 )
1609 .child(share_stop(stop)),
1610 )
1611 .into_any_element()
1612}
1613
1614fn share_picture(image: Option<Arc<RenderImage>>) -> AnyElement {
1615 let Some(image) = image else {
1616 return div()
1617 .size_full()
1618 .flex()
1619 .items_center()
1620 .justify_center()
1621 .px(px(12.))
1622 .text_size(px(12.))
1623 .text_color(theme::text_muted())
1624 .child(WAITING_TEXT)
1625 .into_any_element();
1626 };
1627 img(ImageSource::Render(image))
1628 .size_full()
1629 .object_fit(ObjectFit::Contain)
1630 .into_any_element()
1631}
1632
1633fn share_stop(app: Entity<AppState>) -> Stateful<Div> {
1634 div()
1635 .id("call-share-window-stop")
1636 .absolute()
1637 .top(px(8.))
1638 .right(px(8.))
1639 .h(px(22.))
1640 .px(px(8.))
1641 .flex()
1642 .items_center()
1643 .rounded_full()
1644 .bg(theme::red())
1645 .text_color(theme::white())
1646 .text_size(px(11.))
1647 .font_weight(FontWeight::SEMIBOLD)
1648 .cursor_pointer()
1649 .hover(|button| button.opacity(0.85))
1650 .child("Stop")
1651 .on_click(move |_, _, cx| {
1652 cx.stop_propagation();
1653 app.update(cx, |state, cx| state.stop_call_share(cx));
1654 })
1655}
1656
1493pub fn side_panel(
1657pub fn side_panel(
1494 panel_id: &'static str,
1658 panel_id: &'static str,
1495 title: &'static str,
1659 title: &'static str,
@@ -1541,14 +1705,25 @@ pub fn side_panel(
1541
1705
1542#[cfg(test)]
1706#[cfg(test)]
1543mod tests {
1707mod tests {
1544 use super::{TileSize, name_plate_metrics};
1708 use super::{name_plate_metrics, TileSize};
1545
1709
1546 #[test]
1710 #[test]
1547 fn small_strip_tiles_get_a_compact_name_plate() {
1711 fn small_strip_tiles_get_a_compact_name_plate() {
1548 let strip = name_plate_metrics(TileSize { width: 216., height: 121.5, avatar: 48. });
1712 let strip = name_plate_metrics(TileSize {
1549 assert_eq!((strip.text_size, strip.inset, strip.padding_y), (11., 4., 2.));
1713 width: 216.,
1714 height: 121.5,
1715 avatar: 48.,
1716 });
1717 assert_eq!(
1718 (strip.text_size, strip.inset, strip.padding_y),
1719 (11., 4., 2.)
1720 );
1550 assert!(strip.max_width_share < 1.);
1721 assert!(strip.max_width_share < 1.);
1551 let stage = name_plate_metrics(TileSize { width: 640., height: 360., avatar: 96. });
1722 let stage = name_plate_metrics(TileSize {
1723 width: 640.,
1724 height: 360.,
1725 avatar: 96.,
1726 });
1552 assert_eq!((stage.text_size, stage.inset), (12., 8.));
1727 assert_eq!((stage.text_size, stage.inset), (12., 8.));
1553 }
1728 }
1554}
1729}
crates/app/src/views/calls_page.rs +25 −28
@@ -14,6 +14,7 @@ use super::new_chat::NewChatDraft;
14 14 use super::scroll_edge::{scroll_offset, with_top_edge};
15 15 use super::widgets::{icon, menu_icon, symbol};
16 16 use crate::app_state::AppState;
17 use crate::i18n::tr;
17 18 use crate::call::{
18 19 CALL_ROW_HEIGHT, CallRow, EMPTY_HEIGHT, HistoryFilter, ListEntry, SpeedDialEntry,
19 20 };
@@ -23,17 +24,8 @@ pub const CALLS_DIAL_TAG: &str = "shell/islands/main/calls-dial";
23 24 pub const CALLS_HISTORY_TAG: &str = "shell/islands/main/calls-history";
24 25 pub const CALLS_SPEED_DIAL_TAG: &str = "shell/islands/main/calls-speed-dial";
25 26 const CALLS_SCROLL_DIVIDER: &str = "shell/islands/main/calls-history/divider-scroll";
26 const CALLS_TITLE: &str = "Calls";
27 const HISTORY_TITLE: &str = "History";
28 const SPEED_DIAL_TITLE: &str = "Speed dial";
29 const SPEED_DIAL_EMPTY: &str = "Add people to speed dial for quick access.";
30 const SPEED_DIAL_ADD_TITLE: &str = "Add to speed dial";
31 const ADD_LABEL: &str = "Add";
32 const CANCEL_LABEL: &str = "Cancel";
33 27 const SPEED_DIAL_WIDTH: f32 = 340.;
34 28 const SPEED_DIAL_MIN_WINDOW_WIDTH: f32 = 1100.;
35 const CALL_LABEL: &str = "Call";
36 const CALL_ONE_PERSON_HINT: &str = "Pick one person to call";
37 29 const HEADER_HEIGHT: f32 = 60.;
38 30 const PAGE_PADDING: f32 = 20.;
39 31 const DIAL_WIDTH: f32 = 340.;
@@ -163,7 +155,7 @@ fn call_row(
163 155 })
164 156 .when(can_add_to_speed_dial, |popup| {
165 157 popup.item(
166 PopupMenuItem::new(SPEED_DIAL_ADD_TITLE)
158 PopupMenuItem::new(tr("calls.page.speed_dial_add"))
167 159 .icon(menu_icon(IconName::Star))
168 160 .on_click(move |_, _, cx| {
169 161 let Some(user_id) = dial_row.user_id.as_deref() else {
@@ -184,7 +176,10 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
184 176 let selected = filter == current;
185 177 let state = state.clone();
186 178 div()
187 .id(SharedString::from(format!("calls-filter-{}", filter.label())))
179 .id(SharedString::from(format!(
180 "calls-filter-{}",
181 filter.label()
182 )))
188 183 .h(px(24.))
189 184 .px(px(10.))
190 185 .flex()
@@ -206,7 +201,11 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
206 201 state.update(cx, |state, cx| state.set_call_history_filter(filter, cx))
207 202 })
208 203 });
209 h_flex().gap(px(6.)).items_center().children(pills).into_any_element()
204 h_flex()
205 .gap(px(6.))
206 .items_center()
207 .children(pills)
208 .into_any_element()
210 209 }
211 210
212 211 fn empty_row(text: &'static str) -> AnyElement {
@@ -377,14 +376,14 @@ impl CallsPage {
377 376 .justify_end()
378 377 .child(
379 378 Button::new("speed-dial-cancel")
380 .label(CANCEL_LABEL)
379 .label(tr("common.cancel"))
381 380 .on_click(cx.listener(|this, _, window, cx| {
382 381 this.close_speed_dial_add(window, cx)
383 382 })),
384 383 )
385 384 .child(
386 385 Button::new("speed-dial-confirm")
387 .label(ADD_LABEL)
386 .label(tr("common.add"))
388 387 .when(picked, |button| button.primary())
389 388 .disabled(!picked)
390 389 .on_click(cx.listener(|this, _, window, cx| {
@@ -404,14 +403,14 @@ impl CallsPage {
404 403 div()
405 404 .text_size(px(13.))
406 405 .text_color(theme::text_muted())
407 .child(SPEED_DIAL_EMPTY),
406 .child(tr("calls.page.speed_dial_empty")),
408 407 )
409 408 .child(
410 409 Button::new("speed-dial-empty-add")
411 .label(ADD_LABEL)
412 .on_click(cx.listener(|this, _, window, cx| {
413 this.open_speed_dial_add(window, cx)
414 })),
410 .label(tr("common.add"))
411 .on_click(
412 cx.listener(|this, _, window, cx| this.open_speed_dial_add(window, cx)),
413 ),
415 414 )
416 415 }
417 416
@@ -423,9 +422,7 @@ impl CallsPage {
423 422 .map(|entry| speed_dial_row(&self.app, entry, &state.directory))
424 423 .collect::<Vec<_>>();
425 424 let body = if self.adding_speed_dial {
426 div()
427 .p(px(PAGE_PADDING))
428 .child(self.speed_dial_adder(cx))
425 div().p(px(PAGE_PADDING)).child(self.speed_dial_adder(cx))
429 426 } else if rows.is_empty() {
430 427 self.speed_dial_empty(cx)
431 428 } else {
@@ -460,7 +457,7 @@ impl CallsPage {
460 457 .text_size(px(14.))
461 458 .font_weight(FontWeight::SEMIBOLD)
462 459 .text_color(theme::text())
463 .child(SPEED_DIAL_TITLE),
460 .child(tr("calls.page.speed_dial")),
464 461 )
465 462 .child(
466 463 div()
@@ -473,7 +470,7 @@ impl CallsPage {
473 470 .cursor_pointer()
474 471 .hover(|button| button.bg(theme::row_hover()))
475 472 .tooltip(|window, cx| {
476 gpui_kit::component::tooltip::Tooltip::new(SPEED_DIAL_ADD_TITLE)
473 gpui_kit::component::tooltip::Tooltip::new(tr("calls.page.speed_dial_add"))
477 474 .build(window, cx)
478 475 })
479 476 .child(symbol("person_add", 18., theme::text_soft()))
@@ -501,10 +498,10 @@ impl CallsPage {
501 498 .w_full()
502 499 .h(px(CALL_BUTTON_HEIGHT))
503 500 .icon(IconName::Phone)
504 .label(CALL_LABEL)
501 .label(tr("common.call"))
505 502 .when(callable, |button| button.primary())
506 503 .disabled(!callable)
507 .when(picked > 1, |button| button.tooltip(CALL_ONE_PERSON_HINT))
504 .when(picked > 1, |button| button.tooltip(tr("calls.page.pick_one")))
508 505 .on_click(cx.listener(|this, _, window, cx| this.call_picked(window, cx))),
509 506 )
510 507 }
@@ -570,7 +567,7 @@ impl CallsPage {
570 567 .text_size(px(14.))
571 568 .font_weight(FontWeight::SEMIBOLD)
572 569 .text_color(theme::text())
573 .child(HISTORY_TITLE),
570 .child(tr("calls.page.history")),
574 571 )
575 572 .child(history_filters(&self.app, filter)),
576 573 )
@@ -612,7 +609,7 @@ impl Render for CallsPage {
612 609 .text_size(px(16.))
613 610 .font_weight(FontWeight::BOLD)
614 611 .text_color(theme::text())
615 .child(CALLS_TITLE),
612 .child(tr("calls.page.title")),
616 613 ),
617 614 )
618 615 .child(div().w_full().h(px(1.)).flex_none().bg(theme::border()))
@@ -14,6 +14,7 @@ use super::new_chat::NewChatDraft;
14use super::scroll_edge::{scroll_offset, with_top_edge};
14use super::scroll_edge::{scroll_offset, with_top_edge};
15use super::widgets::{icon, menu_icon, symbol};
15use super::widgets::{icon, menu_icon, symbol};
16use crate::app_state::AppState;
16use crate::app_state::AppState;
17use crate::i18n::tr;
17use crate::call::{
18use crate::call::{
18 CALL_ROW_HEIGHT, CallRow, EMPTY_HEIGHT, HistoryFilter, ListEntry, SpeedDialEntry,
19 CALL_ROW_HEIGHT, CallRow, EMPTY_HEIGHT, HistoryFilter, ListEntry, SpeedDialEntry,
19};
20};
@@ -23,17 +24,8 @@ pub const CALLS_DIAL_TAG: &str = "shell/islands/main/calls-dial";
23pub const CALLS_HISTORY_TAG: &str = "shell/islands/main/calls-history";
24pub const CALLS_HISTORY_TAG: &str = "shell/islands/main/calls-history";
24pub const CALLS_SPEED_DIAL_TAG: &str = "shell/islands/main/calls-speed-dial";
25pub const CALLS_SPEED_DIAL_TAG: &str = "shell/islands/main/calls-speed-dial";
25const CALLS_SCROLL_DIVIDER: &str = "shell/islands/main/calls-history/divider-scroll";
26const CALLS_SCROLL_DIVIDER: &str = "shell/islands/main/calls-history/divider-scroll";
26const CALLS_TITLE: &str = "Calls";
27const HISTORY_TITLE: &str = "History";
28const SPEED_DIAL_TITLE: &str = "Speed dial";
29const SPEED_DIAL_EMPTY: &str = "Add people to speed dial for quick access.";
30const SPEED_DIAL_ADD_TITLE: &str = "Add to speed dial";
31const ADD_LABEL: &str = "Add";
32const CANCEL_LABEL: &str = "Cancel";
33const SPEED_DIAL_WIDTH: f32 = 340.;
27const SPEED_DIAL_WIDTH: f32 = 340.;
34const SPEED_DIAL_MIN_WINDOW_WIDTH: f32 = 1100.;
28const SPEED_DIAL_MIN_WINDOW_WIDTH: f32 = 1100.;
35const CALL_LABEL: &str = "Call";
36const CALL_ONE_PERSON_HINT: &str = "Pick one person to call";
37const HEADER_HEIGHT: f32 = 60.;
29const HEADER_HEIGHT: f32 = 60.;
38const PAGE_PADDING: f32 = 20.;
30const PAGE_PADDING: f32 = 20.;
39const DIAL_WIDTH: f32 = 340.;
31const DIAL_WIDTH: f32 = 340.;
@@ -163,7 +155,7 @@ fn call_row(
163 })
155 })
164 .when(can_add_to_speed_dial, |popup| {
156 .when(can_add_to_speed_dial, |popup| {
165 popup.item(
157 popup.item(
166 PopupMenuItem::new(SPEED_DIAL_ADD_TITLE)
158 PopupMenuItem::new(tr("calls.page.speed_dial_add"))
167 .icon(menu_icon(IconName::Star))
159 .icon(menu_icon(IconName::Star))
168 .on_click(move |_, _, cx| {
160 .on_click(move |_, _, cx| {
169 let Some(user_id) = dial_row.user_id.as_deref() else {
161 let Some(user_id) = dial_row.user_id.as_deref() else {
@@ -184,7 +176,10 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
184 let selected = filter == current;
176 let selected = filter == current;
185 let state = state.clone();
177 let state = state.clone();
186 div()
178 div()
187 .id(SharedString::from(format!("calls-filter-{}", filter.label())))
179 .id(SharedString::from(format!(
180 "calls-filter-{}",
181 filter.label()
182 )))
188 .h(px(24.))
183 .h(px(24.))
189 .px(px(10.))
184 .px(px(10.))
190 .flex()
185 .flex()
@@ -206,7 +201,11 @@ fn history_filters(state: &Entity<AppState>, current: HistoryFilter) -> AnyEleme
206 state.update(cx, |state, cx| state.set_call_history_filter(filter, cx))
201 state.update(cx, |state, cx| state.set_call_history_filter(filter, cx))
207 })
202 })
208 });
203 });
209 h_flex().gap(px(6.)).items_center().children(pills).into_any_element()
204 h_flex()
205 .gap(px(6.))
206 .items_center()
207 .children(pills)
208 .into_any_element()
210}
209}
211
210
212fn empty_row(text: &'static str) -> AnyElement {
211fn empty_row(text: &'static str) -> AnyElement {
@@ -377,14 +376,14 @@ impl CallsPage {
377 .justify_end()
376 .justify_end()
378 .child(
377 .child(
379 Button::new("speed-dial-cancel")
378 Button::new("speed-dial-cancel")
380 .label(CANCEL_LABEL)
379 .label(tr("common.cancel"))
381 .on_click(cx.listener(|this, _, window, cx| {
380 .on_click(cx.listener(|this, _, window, cx| {
382 this.close_speed_dial_add(window, cx)
381 this.close_speed_dial_add(window, cx)
383 })),
382 })),
384 )
383 )
385 .child(
384 .child(
386 Button::new("speed-dial-confirm")
385 Button::new("speed-dial-confirm")
387 .label(ADD_LABEL)
386 .label(tr("common.add"))
388 .when(picked, |button| button.primary())
387 .when(picked, |button| button.primary())
389 .disabled(!picked)
388 .disabled(!picked)
390 .on_click(cx.listener(|this, _, window, cx| {
389 .on_click(cx.listener(|this, _, window, cx| {
@@ -404,14 +403,14 @@ impl CallsPage {
404 div()
403 div()
405 .text_size(px(13.))
404 .text_size(px(13.))
406 .text_color(theme::text_muted())
405 .text_color(theme::text_muted())
407 .child(SPEED_DIAL_EMPTY),
406 .child(tr("calls.page.speed_dial_empty")),
408 )
407 )
409 .child(
408 .child(
410 Button::new("speed-dial-empty-add")
409 Button::new("speed-dial-empty-add")
411 .label(ADD_LABEL)
410 .label(tr("common.add"))
412 .on_click(cx.listener(|this, _, window, cx| {
411 .on_click(
413 this.open_speed_dial_add(window, cx)
412 cx.listener(|this, _, window, cx| this.open_speed_dial_add(window, cx)),
414 })),
413 ),
415 )
414 )
416 }
415 }
417
416
@@ -423,9 +422,7 @@ impl CallsPage {
423 .map(|entry| speed_dial_row(&self.app, entry, &state.directory))
422 .map(|entry| speed_dial_row(&self.app, entry, &state.directory))
424 .collect::<Vec<_>>();
423 .collect::<Vec<_>>();
425 let body = if self.adding_speed_dial {
424 let body = if self.adding_speed_dial {
426 div()
425 div().p(px(PAGE_PADDING)).child(self.speed_dial_adder(cx))
427 .p(px(PAGE_PADDING))
428 .child(self.speed_dial_adder(cx))
429 } else if rows.is_empty() {
426 } else if rows.is_empty() {
430 self.speed_dial_empty(cx)
427 self.speed_dial_empty(cx)
431 } else {
428 } else {
@@ -460,7 +457,7 @@ impl CallsPage {
460 .text_size(px(14.))
457 .text_size(px(14.))
461 .font_weight(FontWeight::SEMIBOLD)
458 .font_weight(FontWeight::SEMIBOLD)
462 .text_color(theme::text())
459 .text_color(theme::text())
463 .child(SPEED_DIAL_TITLE),
460 .child(tr("calls.page.speed_dial")),
464 )
461 )
465 .child(
462 .child(
466 div()
463 div()
@@ -473,7 +470,7 @@ impl CallsPage {
473 .cursor_pointer()
470 .cursor_pointer()
474 .hover(|button| button.bg(theme::row_hover()))
471 .hover(|button| button.bg(theme::row_hover()))
475 .tooltip(|window, cx| {
472 .tooltip(|window, cx| {
476 gpui_kit::component::tooltip::Tooltip::new(SPEED_DIAL_ADD_TITLE)
473 gpui_kit::component::tooltip::Tooltip::new(tr("calls.page.speed_dial_add"))
477 .build(window, cx)
474 .build(window, cx)
478 })
475 })
479 .child(symbol("person_add", 18., theme::text_soft()))
476 .child(symbol("person_add", 18., theme::text_soft()))
@@ -501,10 +498,10 @@ impl CallsPage {
501 .w_full()
498 .w_full()
502 .h(px(CALL_BUTTON_HEIGHT))
499 .h(px(CALL_BUTTON_HEIGHT))
503 .icon(IconName::Phone)
500 .icon(IconName::Phone)
504 .label(CALL_LABEL)
501 .label(tr("common.call"))
505 .when(callable, |button| button.primary())
502 .when(callable, |button| button.primary())
506 .disabled(!callable)
503 .disabled(!callable)
507 .when(picked > 1, |button| button.tooltip(CALL_ONE_PERSON_HINT))
504 .when(picked > 1, |button| button.tooltip(tr("calls.page.pick_one")))
508 .on_click(cx.listener(|this, _, window, cx| this.call_picked(window, cx))),
505 .on_click(cx.listener(|this, _, window, cx| this.call_picked(window, cx))),
509 )
506 )
510 }
507 }
@@ -570,7 +567,7 @@ impl CallsPage {
570 .text_size(px(14.))
567 .text_size(px(14.))
571 .font_weight(FontWeight::SEMIBOLD)
568 .font_weight(FontWeight::SEMIBOLD)
572 .text_color(theme::text())
569 .text_color(theme::text())
573 .child(HISTORY_TITLE),
570 .child(tr("calls.page.history")),
574 )
571 )
575 .child(history_filters(&self.app, filter)),
572 .child(history_filters(&self.app, filter)),
576 )
573 )
@@ -612,7 +609,7 @@ impl Render for CallsPage {
612 .text_size(px(16.))
609 .text_size(px(16.))
613 .font_weight(FontWeight::BOLD)
610 .font_weight(FontWeight::BOLD)
614 .text_color(theme::text())
611 .text_color(theme::text())
615 .child(CALLS_TITLE),
612 .child(tr("calls.page.title")),
616 ),
613 ),
617 )
614 )
618 .child(div().w_full().h(px(1.)).flex_none().bg(theme::border()))
615 .child(div().w_full().h(px(1.)).flex_none().bg(theme::border()))
crates/app/src/views/channel_admin_dialogs.rs +5 −4
@@ -6,6 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;
6 6 use gpui_kit::*;
7 7
8 8 use super::new_meeting_dialog::labeled;
9 use crate::i18n::tr;
9 10 use crate::app_state::AppState;
10 11 use crate::team_admin::{can_create_channel, channel_name_problem};
11 12 use crate::theme;
@@ -156,13 +157,13 @@ pub fn open_edit_channel_dialog(
156 157 let footer = DialogFooter::new()
157 158 .child(
158 159 Button::new("edit-channel-cancel")
159 .label("Cancel")
160 .label(tr("common.cancel"))
160 161 .on_click(|_, window, cx| window.close_dialog(cx)),
161 162 )
162 163 .child(
163 164 Button::new("edit-channel-save")
164 165 .primary()
165 .label("Save")
166 .label(tr("common.save"))
166 167 .disabled(!can_save)
167 168 .on_click(move |_, window, cx| {
168 169 if submit_form.update(cx, |form, cx| form.submit(cx)) {
@@ -207,10 +208,10 @@ pub fn confirm_delete_channel(
207 208 window.open_alert_dialog(cx, move |alert, _, _| {
208 209 let (state, channel_id) = (state.clone(), channel_id.clone());
209 210 let cancel = Button::new("delete-channel-cancel")
210 .label("Cancel")
211 .label(tr("common.cancel"))
211 212 .on_click(|_, window, cx| window.close_dialog(cx));
212 213 let delete = Button::new("delete-channel-confirm")
213 .label("Delete")
214 .label(tr("common.delete"))
214 215 .danger()
215 216 .on_click(move |_, window, cx| {
216 217 state.update(cx, |state, cx| state.delete_channel(&channel_id, cx));
@@ -6,6 +6,7 @@ use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
6use gpui_kit::*;
7
7
8use super::new_meeting_dialog::labeled;
8use super::new_meeting_dialog::labeled;
9use crate::i18n::tr;
9use crate::app_state::AppState;
10use crate::app_state::AppState;
10use crate::team_admin::{can_create_channel, channel_name_problem};
11use crate::team_admin::{can_create_channel, channel_name_problem};
11use crate::theme;
12use crate::theme;
@@ -156,13 +157,13 @@ pub fn open_edit_channel_dialog(
156 let footer = DialogFooter::new()
157 let footer = DialogFooter::new()
157 .child(
158 .child(
158 Button::new("edit-channel-cancel")
159 Button::new("edit-channel-cancel")
159 .label("Cancel")
160 .label(tr("common.cancel"))
160 .on_click(|_, window, cx| window.close_dialog(cx)),
161 .on_click(|_, window, cx| window.close_dialog(cx)),
161 )
162 )
162 .child(
163 .child(
163 Button::new("edit-channel-save")
164 Button::new("edit-channel-save")
164 .primary()
165 .primary()
165 .label("Save")
166 .label(tr("common.save"))
166 .disabled(!can_save)
167 .disabled(!can_save)
167 .on_click(move |_, window, cx| {
168 .on_click(move |_, window, cx| {
168 if submit_form.update(cx, |form, cx| form.submit(cx)) {
169 if submit_form.update(cx, |form, cx| form.submit(cx)) {
@@ -207,10 +208,10 @@ pub fn confirm_delete_channel(
207 window.open_alert_dialog(cx, move |alert, _, _| {
208 window.open_alert_dialog(cx, move |alert, _, _| {
208 let (state, channel_id) = (state.clone(), channel_id.clone());
209 let (state, channel_id) = (state.clone(), channel_id.clone());
209 let cancel = Button::new("delete-channel-cancel")
210 let cancel = Button::new("delete-channel-cancel")
210 .label("Cancel")
211 .label(tr("common.cancel"))
211 .on_click(|_, window, cx| window.close_dialog(cx));
212 .on_click(|_, window, cx| window.close_dialog(cx));
212 let delete = Button::new("delete-channel-confirm")
213 let delete = Button::new("delete-channel-confirm")
213 .label("Delete")
214 .label(tr("common.delete"))
214 .danger()
215 .danger()
215 .on_click(move |_, window, cx| {
216 .on_click(move |_, window, cx| {
216 state.update(cx, |state, cx| state.delete_channel(&channel_id, cx));
217 state.update(cx, |state, cx| state.delete_channel(&channel_id, cx));
crates/app/src/views/chat_members.rs +3 −2
@@ -16,6 +16,7 @@ use super::avatar::{person_avatar, with_presence};
16 16 use super::profile_card::opens_profile;
17 17 use super::chat_menu::confirm_leave;
18 18 use super::widgets::icon;
19 use crate::i18n::tr;
19 20 use crate::app_state::AppState;
20 21 use crate::chat_actions::TITLE_LIMIT;
21 22 use crate::chat_members::{MemberRow, can_leave, member_rows};
@@ -289,10 +290,10 @@ fn confirm_remove(
289 290 window.open_alert_dialog(cx, move |alert, _, _| {
290 291 let (app, chat_id, user_id) = (app.clone(), chat_id.clone(), user_id.clone());
291 292 let cancel = Button::new("remove-member-cancel")
292 .label("Cancel")
293 .label(tr("common.cancel"))
293 294 .on_click(|_, window, cx| window.close_dialog(cx));
294 295 let remove = Button::new("remove-member-confirm")
295 .label("Remove")
296 .label(tr("common.remove"))
296 297 .danger()
297 298 .on_click(move |_, window, cx| {
298 299 app.update(cx, |state, cx| {
@@ -16,6 +16,7 @@ use super::avatar::{person_avatar, with_presence};
16use super::profile_card::opens_profile;
16use super::profile_card::opens_profile;
17use super::chat_menu::confirm_leave;
17use super::chat_menu::confirm_leave;
18use super::widgets::icon;
18use super::widgets::icon;
19use crate::i18n::tr;
19use crate::app_state::AppState;
20use crate::app_state::AppState;
20use crate::chat_actions::TITLE_LIMIT;
21use crate::chat_actions::TITLE_LIMIT;
21use crate::chat_members::{MemberRow, can_leave, member_rows};
22use crate::chat_members::{MemberRow, can_leave, member_rows};
@@ -289,10 +290,10 @@ fn confirm_remove(
289 window.open_alert_dialog(cx, move |alert, _, _| {
290 window.open_alert_dialog(cx, move |alert, _, _| {
290 let (app, chat_id, user_id) = (app.clone(), chat_id.clone(), user_id.clone());
291 let (app, chat_id, user_id) = (app.clone(), chat_id.clone(), user_id.clone());
291 let cancel = Button::new("remove-member-cancel")
292 let cancel = Button::new("remove-member-cancel")
292 .label("Cancel")
293 .label(tr("common.cancel"))
293 .on_click(|_, window, cx| window.close_dialog(cx));
294 .on_click(|_, window, cx| window.close_dialog(cx));
294 let remove = Button::new("remove-member-confirm")
295 let remove = Button::new("remove-member-confirm")
295 .label("Remove")
296 .label(tr("common.remove"))
296 .danger()
297 .danger()
297 .on_click(move |_, window, cx| {
298 .on_click(move |_, window, cx| {
298 app.update(cx, |state, cx| {
299 app.update(cx, |state, cx| {
crates/app/src/views/chat_menu.rs +5 −4
@@ -8,6 +8,7 @@ use teams_core::{ChatNotificationMode, DesktopNotifications, chat_link, is_notes
8 8
9 9 use super::chat_pop_out;
10 10 use super::widgets::menu_icon;
11 use crate::i18n::tr;
11 12 use crate::app_state::{AppState, chat_title};
12 13 use crate::chat_actions::TITLE_LIMIT;
13 14 use crate::notice::truncated;
@@ -332,10 +333,10 @@ fn confirm_remove_history(
332 333 let state = state.clone();
333 334 let chat_id = chat_id.clone();
334 335 let cancel = Button::new("remove-history-cancel")
335 .label("Cancel")
336 .label(tr("common.cancel"))
336 337 .on_click(|_, window, cx| window.close_dialog(cx));
337 338 let remove = Button::new("remove-history-confirm")
338 .label("Remove")
339 .label(tr("common.remove"))
339 340 .primary()
340 341 .on_click(move |_, window, cx| {
341 342 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
@@ -365,10 +366,10 @@ pub(crate) fn confirm_leave(
365 366 let state = state.clone();
366 367 let chat_id = chat_id.clone();
367 368 let cancel = Button::new("leave-cancel")
368 .label("Cancel")
369 .label(tr("common.cancel"))
369 370 .on_click(|_, window, cx| window.close_dialog(cx));
370 371 let leave = Button::new("leave-confirm")
371 .label("Leave")
372 .label(tr("common.leave"))
372 373 .danger()
373 374 .on_click(move |_, window, cx| {
374 375 state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));
@@ -8,6 +8,7 @@ use teams_core::{ChatNotificationMode, DesktopNotifications, chat_link, is_notes
8
8
9use super::chat_pop_out;
9use super::chat_pop_out;
10use super::widgets::menu_icon;
10use super::widgets::menu_icon;
11use crate::i18n::tr;
11use crate::app_state::{AppState, chat_title};
12use crate::app_state::{AppState, chat_title};
12use crate::chat_actions::TITLE_LIMIT;
13use crate::chat_actions::TITLE_LIMIT;
13use crate::notice::truncated;
14use crate::notice::truncated;
@@ -332,10 +333,10 @@ fn confirm_remove_history(
332 let state = state.clone();
333 let state = state.clone();
333 let chat_id = chat_id.clone();
334 let chat_id = chat_id.clone();
334 let cancel = Button::new("remove-history-cancel")
335 let cancel = Button::new("remove-history-cancel")
335 .label("Cancel")
336 .label(tr("common.cancel"))
336 .on_click(|_, window, cx| window.close_dialog(cx));
337 .on_click(|_, window, cx| window.close_dialog(cx));
337 let remove = Button::new("remove-history-confirm")
338 let remove = Button::new("remove-history-confirm")
338 .label("Remove")
339 .label(tr("common.remove"))
339 .primary()
340 .primary()
340 .on_click(move |_, window, cx| {
341 .on_click(move |_, window, cx| {
341 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
342 state.update(cx, |state, cx| state.remove_chat_history(&chat_id, cx));
@@ -365,10 +366,10 @@ pub(crate) fn confirm_leave(
365 let state = state.clone();
366 let state = state.clone();
366 let chat_id = chat_id.clone();
367 let chat_id = chat_id.clone();
367 let cancel = Button::new("leave-cancel")
368 let cancel = Button::new("leave-cancel")
368 .label("Cancel")
369 .label(tr("common.cancel"))
369 .on_click(|_, window, cx| window.close_dialog(cx));
370 .on_click(|_, window, cx| window.close_dialog(cx));
370 let leave = Button::new("leave-confirm")
371 let leave = Button::new("leave-confirm")
371 .label("Leave")
372 .label(tr("common.leave"))
372 .danger()
373 .danger()
373 .on_click(move |_, window, cx| {
374 .on_click(move |_, window, cx| {
374 state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));
375 state.update(cx, |state, cx| state.leave_chat(&chat_id, cx));
crates/app/src/views/composer/cloud_picker.rs +195 −49
@@ -7,6 +7,7 @@ use gpui_kit::prelude::FluentBuilder as _;
7 7 use gpui_kit::*;
8 8 use teams_core::{CloudFile, DriveEntry, DriveFolder, QuickSite};
9 9
10 use crate::i18n::tr;
10 11 use crate::app_state::AppState;
11 12 use crate::runtime;
12 13 use crate::theme::{self, ElevatedSurface as _};
@@ -103,7 +104,7 @@ fn demo_rows() -> Vec<DriveEntry> {
103 104 drive_id: "demo-drive".into(),
104 105 id: format!("demo-{index}"),
105 106 name: (*name).into(),
106 web_url: format!("https://example.com/demo/{index}"),
107 web_url: format!("https://contoso.sharepoint.com/demo/{index}"),
107 108 size: 20_000,
108 109 modified_at: Some(now - chrono::Duration::hours(3 * index as i64 + 1)),
109 110 modified_by: Some("Megan Bowen".into()),
@@ -165,7 +166,11 @@ impl CloudPicker {
165 166 self.rows = Rows::Loading;
166 167 cx.notify();
167 168 if self.app.read(cx).mode.demo {
168 self.rows = Rows::Ready(if place == Place::Home { demo_rows() } else { Vec::new() });
169 self.rows = Rows::Ready(if place == Place::Home {
170 demo_rows()
171 } else {
172 Vec::new()
173 });
169 174 return;
170 175 }
171 176 let Some(engine) = self.app.read(cx).engine.clone() else {
@@ -178,7 +183,15 @@ impl CloudPicker {
178 183 };
179 184 let receiver = runtime::spawn(async move {
180 185 match place {
181 Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),
186 Place::Home => Ok((
187 None,
188 engine
189 .picker_recent()
190 .await?
191 .into_iter()
192 .filter_map(recent_row)
193 .collect(),
194 )),
182 195 Place::Shared => Ok((None, engine.picker_shared().await?)),
183 196 Place::MyFiles | Place::Site(_) => {
184 197 let root = engine.picker_root(site.as_deref()).await?;
@@ -188,7 +201,8 @@ impl CloudPicker {
188 201 }
189 202 });
190 203 cx.spawn(async move |this, cx| {
191 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();
204 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> =
205 receiver.await.ok();
192 206 this.update(cx, |this, cx| {
193 207 if this.generation != generation {
194 208 return;
@@ -196,7 +210,10 @@ impl CloudPicker {
196 210 match result {
197 211 Some(Ok((root, entries))) => {
198 212 if let Some(folder) = root {
199 this.crumbs.push(Crumb { name: this.root_name(), folder });
213 this.crumbs.push(Crumb {
214 name: this.root_name(),
215 folder,
216 });
200 217 }
201 218 this.rows = Rows::Ready(entries);
202 219 }
@@ -217,7 +234,10 @@ impl CloudPicker {
217 234 }
218 235
219 236 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
220 self.crumbs.push(Crumb { name, folder: folder.clone() });
237 self.crumbs.push(Crumb {
238 name,
239 folder: folder.clone(),
240 });
221 241 self.list_folder(folder, cx);
222 242 }
223 243
@@ -260,7 +280,11 @@ impl CloudPicker {
260 280 self.open_folder(entry.name.clone(), entry.folder(), cx);
261 281 return;
262 282 }
263 match self.selected.iter().position(|picked| picked.id == entry.id) {
283 match self
284 .selected
285 .iter()
286 .position(|picked| picked.id == entry.id)
287 {
264 288 Some(index) => {
265 289 self.selected.remove(index);
266 290 }
@@ -270,7 +294,11 @@ impl CloudPicker {
270 294 }
271 295
272 296 fn attach(&mut self, cx: &mut Context<Self>) {
273 let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();
297 let files = self
298 .selected
299 .iter()
300 .map(CloudFile::from)
301 .collect::<Vec<_>>();
274 302 if !files.is_empty() {
275 303 cx.emit(CloudPickerEvent::Attach(files));
276 304 }
@@ -280,11 +308,21 @@ impl CloudPicker {
280 308 match self.place {
281 309 Place::Home => "Home".into(),
282 310 Place::Shared => "Shared with you".into(),
283 Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
311 Place::MyFiles | Place::Site(_) => self
312 .crumbs
313 .last()
314 .map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
284 315 }
285 316 }
286 317
287 fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {
318 fn nav_row(
319 &self,
320 id: impl Into<ElementId>,
321 glyph: &'static str,
322 label: String,
323 place: Place,
324 cx: &mut Context<Self>,
325 ) -> Stateful<Div> {
288 326 let active = self.place == place;
289 327 h_flex()
290 328 .id(id)
@@ -296,10 +334,24 @@ impl CloudPicker {
296 334 .rounded(px(6.))
297 335 .cursor_pointer()
298 336 .text_size(px(13.))
299 .text_color(if active { theme::text_strong() } else { theme::text() })
300 .when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))
337 .text_color(if active {
338 theme::text_strong()
339 } else {
340 theme::text()
341 })
342 .when(active, |row| {
343 row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD)
344 })
301 345 .hover(|row| row.bg(theme::row_hover()))
302 .child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))
346 .child(symbol(
347 glyph,
348 18.,
349 if active {
350 theme::accent_text()
351 } else {
352 theme::text_soft()
353 },
354 ))
303 355 .child(div().flex_1().min_w_0().truncate().child(label))
304 356 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
305 357 }
@@ -317,7 +369,13 @@ impl CloudPicker {
317 369 };
318 370 let mut sites = Vec::with_capacity(self.sites.len());
319 371 for (index, site) in self.sites.iter().enumerate() {
320 sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));
372 sites.push(self.nav_row(
373 ("cloud-picker-site", index),
374 "domain",
375 site.name.clone(),
376 Place::Site(index),
377 cx,
378 ));
321 379 }
322 380 v_flex()
323 381 .w(px(NAV_WIDTH))
@@ -335,11 +393,29 @@ impl CloudPicker {
335 393 .child("OneDrive"),
336 394 )
337 395 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
338 .child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))
339 .child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))
396 .child(self.nav_row(
397 "cloud-picker-mine",
398 "folder",
399 "My files".into(),
400 Place::MyFiles,
401 cx,
402 ))
403 .child(self.nav_row(
404 "cloud-picker-shared",
405 "group",
406 "Shared".into(),
407 Place::Shared,
408 cx,
409 ))
340 410 .when(!self.sites.is_empty(), |nav| {
341 nav.child(section("Quick access"))
342 .child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))
411 nav.child(section("Quick access")).child(
412 v_flex()
413 .id("cloud-picker-sites")
414 .flex_1()
415 .min_h_0()
416 .overflow_y_scrollbar()
417 .children(sites),
418 )
343 419 })
344 420 }
345 421
@@ -356,10 +432,21 @@ impl CloudPicker {
356 432 .id(("cloud-picker-crumb", depth))
357 433 .truncate()
358 434 .text_size(px(if current { 20. } else { 14. }))
359 .font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
360 .text_color(if current { theme::text_strong() } else { theme::text_soft() })
435 .font_weight(if current {
436 FontWeight::SEMIBOLD
437 } else {
438 FontWeight::NORMAL
439 })
440 .text_color(if current {
441 theme::text_strong()
442 } else {
443 theme::text_soft()
444 })
361 445 .when(!current, |crumb| {
362 crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
446 crumb
447 .cursor_pointer()
448 .hover(|crumb| crumb.text_color(theme::text()))
449 .on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
363 450 })
364 451 .child(crumb.name.clone()),
365 452 );
@@ -376,12 +463,21 @@ impl CloudPicker {
376 463 self.breadcrumb(cx)
377 464 } else {
378 465 h_flex().child(
379 div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),
466 div()
467 .text_size(px(20.))
468 .font_weight(FontWeight::SEMIBOLD)
469 .text_color(theme::text_strong())
470 .child(self.title()),
380 471 )
381 472 };
382 473 v_flex()
383 474 .gap(px(2.))
384 .children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))
475 .children(site.map(|name| {
476 div()
477 .text_size(px(13.))
478 .text_color(theme::text_soft())
479 .child(name)
480 }))
385 481 .child(title)
386 482 }
387 483
@@ -406,12 +502,20 @@ impl CloudPicker {
406 502
407 503 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
408 504 match (self.place, entry.modified_at) {
409 (Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),
505 (Place::Home, Some(opened)) => {
506 opened_ago(opened, now).unwrap_or_else(|| modified_text(entry))
507 }
410 508 _ => modified_text(entry),
411 509 }
412 510 }
413 511
414 fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
512 fn row(
513 &self,
514 index: usize,
515 entry: &DriveEntry,
516 now: DateTime<Utc>,
517 cx: &mut Context<Self>,
518 ) -> Stateful<Div> {
415 519 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
416 520 let folder = entry.is_folder();
417 521 let clicked = entry.clone();
@@ -429,11 +533,9 @@ impl CloudPicker {
429 533 .text_color(theme::text_soft())
430 534 .when(picked, |row| row.bg(theme::selection()))
431 535 .hover(|row| row.bg(theme::row_hover()))
432 .child(
433 div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
434 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
435 }),
436 )
536 .child(div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
537 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
538 }))
437 539 .child(
438 540 h_flex()
439 541 .flex_1()
@@ -441,25 +543,49 @@ impl CloudPicker {
441 543 .gap(px(10.))
442 544 .items_center()
443 545 .child(entry_badge(entry))
444 .child(div().truncate().text_color(theme::text()).child(entry.name.clone())),
546 .child(
547 div()
548 .truncate()
549 .text_color(theme::text())
550 .child(entry.name.clone()),
551 ),
552 )
553 .child(
554 div()
555 .w(px(WHEN_WIDTH))
556 .flex_none()
557 .truncate()
558 .child(self.when_text(entry, now)),
559 )
560 .child(
561 div()
562 .w(px(WHO_WIDTH))
563 .flex_none()
564 .truncate()
565 .child(entry.modified_by.clone().unwrap_or_default()),
445 566 )
446 .child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))
447 .child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))
448 567 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
449 568 }
450 569
451 570 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
452 571 let note = |text: &'static str| {
453 div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()
572 div()
573 .p(px(16.))
574 .text_size(px(13.))
575 .text_color(theme::text_soft())
576 .child(text)
577 .into_any_element()
454 578 };
455 579 let now = Utc::now();
456 580 let body: Vec<AnyElement> = match &self.rows {
457 581 Rows::Loading => vec![note("Loading ...")],
458 582 Rows::Failed => vec![note("Couldn't load files.")],
459 583 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
460 Rows::Ready(entries) => {
461 entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()
462 }
584 Rows::Ready(entries) => entries
585 .iter()
586 .enumerate()
587 .map(|(index, entry)| self.row(index, entry, now, cx).into_any_element())
588 .collect(),
463 589 };
464 590 v_flex()
465 591 .flex_1()
@@ -468,7 +594,14 @@ impl CloudPicker {
468 594 .bg(theme::surface_raised())
469 595 .overflow_hidden()
470 596 .child(self.column_header())
471 .child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))
597 .child(
598 v_flex()
599 .id("cloud-picker-rows")
600 .flex_1()
601 .min_h_0()
602 .overflow_y_scrollbar()
603 .children(body),
604 )
472 605 .into_any_element()
473 606 }
474 607 }
@@ -506,15 +639,13 @@ impl Render for CloudPicker {
506 639 .child(
507 640 Button::new("cloud-picker-attach")
508 641 .primary()
509 .label("Attach")
642 .label(tr("common.attach"))
510 643 .disabled(!can_attach)
511 644 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
512 645 )
513 .child(
514 Button::new("cloud-picker-cancel")
515 .label("Cancel")
516 .on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),
517 ),
646 .child(Button::new("cloud-picker-cancel").label(tr("common.cancel")).on_click(
647 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
648 )),
518 649 ),
519 650 );
520 651 deferred(
@@ -534,7 +665,10 @@ impl Render for CloudPicker {
534 665 cx.emit(CloudPickerEvent::Close);
535 666 }
536 667 }))
537 .on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))
668 .on_mouse_down(
669 MouseButton::Left,
670 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
671 )
538 672 .child(panel),
539 673 ),
540 674 )
@@ -551,15 +685,27 @@ mod tests {
551 685 #[test]
552 686 fn home_shows_hours_ago_like_the_onedrive_picker() {
553 687 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
554 assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));
555 assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));
688 assert_eq!(
689 opened_ago(now - chrono::Duration::hours(9), now).as_deref(),
690 Some("9h ago")
691 );
692 assert_eq!(
693 opened_ago(now - chrono::Duration::minutes(5), now).as_deref(),
694 Some("5m ago")
695 );
556 696 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
557 697 }
558 698
559 699 #[test]
560 700 fn each_place_has_the_picker_columns() {
561 701 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
562 assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);
563 assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);
702 assert_eq!(
703 Place::Shared.columns(),
704 ["Name", "Date shared", "Shared by"]
705 );
706 assert_eq!(
707 Place::Site(0).columns(),
708 ["Name", "Modified", "Modified By"]
709 );
564 710 }
565 711 }
@@ -7,6 +7,7 @@ use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
7use gpui_kit::*;
8use teams_core::{CloudFile, DriveEntry, DriveFolder, QuickSite};
8use teams_core::{CloudFile, DriveEntry, DriveFolder, QuickSite};
9
9
10use crate::i18n::tr;
10use crate::app_state::AppState;
11use crate::app_state::AppState;
11use crate::runtime;
12use crate::runtime;
12use crate::theme::{self, ElevatedSurface as _};
13use crate::theme::{self, ElevatedSurface as _};
@@ -103,7 +104,7 @@ fn demo_rows() -> Vec<DriveEntry> {
103 drive_id: "demo-drive".into(),
104 drive_id: "demo-drive".into(),
104 id: format!("demo-{index}"),
105 id: format!("demo-{index}"),
105 name: (*name).into(),
106 name: (*name).into(),
106 web_url: format!("https://example.com/demo/{index}"),
107 web_url: format!("https://contoso.sharepoint.com/demo/{index}"),
107 size: 20_000,
108 size: 20_000,
108 modified_at: Some(now - chrono::Duration::hours(3 * index as i64 + 1)),
109 modified_at: Some(now - chrono::Duration::hours(3 * index as i64 + 1)),
109 modified_by: Some("Megan Bowen".into()),
110 modified_by: Some("Megan Bowen".into()),
@@ -165,7 +166,11 @@ impl CloudPicker {
165 self.rows = Rows::Loading;
166 self.rows = Rows::Loading;
166 cx.notify();
167 cx.notify();
167 if self.app.read(cx).mode.demo {
168 if self.app.read(cx).mode.demo {
168 self.rows = Rows::Ready(if place == Place::Home { demo_rows() } else { Vec::new() });
169 self.rows = Rows::Ready(if place == Place::Home {
170 demo_rows()
171 } else {
172 Vec::new()
173 });
169 return;
174 return;
170 }
175 }
171 let Some(engine) = self.app.read(cx).engine.clone() else {
176 let Some(engine) = self.app.read(cx).engine.clone() else {
@@ -178,7 +183,15 @@ impl CloudPicker {
178 };
183 };
179 let receiver = runtime::spawn(async move {
184 let receiver = runtime::spawn(async move {
180 match place {
185 match place {
181 Place::Home => Ok((None, engine.picker_recent().await?.into_iter().filter_map(recent_row).collect())),
186 Place::Home => Ok((
187 None,
188 engine
189 .picker_recent()
190 .await?
191 .into_iter()
192 .filter_map(recent_row)
193 .collect(),
194 )),
182 Place::Shared => Ok((None, engine.picker_shared().await?)),
195 Place::Shared => Ok((None, engine.picker_shared().await?)),
183 Place::MyFiles | Place::Site(_) => {
196 Place::MyFiles | Place::Site(_) => {
184 let root = engine.picker_root(site.as_deref()).await?;
197 let root = engine.picker_root(site.as_deref()).await?;
@@ -188,7 +201,8 @@ impl CloudPicker {
188 }
201 }
189 });
202 });
190 cx.spawn(async move |this, cx| {
203 cx.spawn(async move |this, cx| {
191 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> = receiver.await.ok();
204 let result: Option<teams_core::Result<(Option<DriveFolder>, Vec<DriveEntry>)>> =
205 receiver.await.ok();
192 this.update(cx, |this, cx| {
206 this.update(cx, |this, cx| {
193 if this.generation != generation {
207 if this.generation != generation {
194 return;
208 return;
@@ -196,7 +210,10 @@ impl CloudPicker {
196 match result {
210 match result {
197 Some(Ok((root, entries))) => {
211 Some(Ok((root, entries))) => {
198 if let Some(folder) = root {
212 if let Some(folder) = root {
199 this.crumbs.push(Crumb { name: this.root_name(), folder });
213 this.crumbs.push(Crumb {
214 name: this.root_name(),
215 folder,
216 });
200 }
217 }
201 this.rows = Rows::Ready(entries);
218 this.rows = Rows::Ready(entries);
202 }
219 }
@@ -217,7 +234,10 @@ impl CloudPicker {
217 }
234 }
218
235
219 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
236 fn open_folder(&mut self, name: String, folder: DriveFolder, cx: &mut Context<Self>) {
220 self.crumbs.push(Crumb { name, folder: folder.clone() });
237 self.crumbs.push(Crumb {
238 name,
239 folder: folder.clone(),
240 });
221 self.list_folder(folder, cx);
241 self.list_folder(folder, cx);
222 }
242 }
223
243
@@ -260,7 +280,11 @@ impl CloudPicker {
260 self.open_folder(entry.name.clone(), entry.folder(), cx);
280 self.open_folder(entry.name.clone(), entry.folder(), cx);
261 return;
281 return;
262 }
282 }
263 match self.selected.iter().position(|picked| picked.id == entry.id) {
283 match self
284 .selected
285 .iter()
286 .position(|picked| picked.id == entry.id)
287 {
264 Some(index) => {
288 Some(index) => {
265 self.selected.remove(index);
289 self.selected.remove(index);
266 }
290 }
@@ -270,7 +294,11 @@ impl CloudPicker {
270 }
294 }
271
295
272 fn attach(&mut self, cx: &mut Context<Self>) {
296 fn attach(&mut self, cx: &mut Context<Self>) {
273 let files = self.selected.iter().map(CloudFile::from).collect::<Vec<_>>();
297 let files = self
298 .selected
299 .iter()
300 .map(CloudFile::from)
301 .collect::<Vec<_>>();
274 if !files.is_empty() {
302 if !files.is_empty() {
275 cx.emit(CloudPickerEvent::Attach(files));
303 cx.emit(CloudPickerEvent::Attach(files));
276 }
304 }
@@ -280,11 +308,21 @@ impl CloudPicker {
280 match self.place {
308 match self.place {
281 Place::Home => "Home".into(),
309 Place::Home => "Home".into(),
282 Place::Shared => "Shared with you".into(),
310 Place::Shared => "Shared with you".into(),
283 Place::MyFiles | Place::Site(_) => self.crumbs.last().map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
311 Place::MyFiles | Place::Site(_) => self
312 .crumbs
313 .last()
314 .map_or_else(|| self.root_name(), |crumb| crumb.name.clone()),
284 }
315 }
285 }
316 }
286
317
287 fn nav_row(&self, id: impl Into<ElementId>, glyph: &'static str, label: String, place: Place, cx: &mut Context<Self>) -> Stateful<Div> {
318 fn nav_row(
319 &self,
320 id: impl Into<ElementId>,
321 glyph: &'static str,
322 label: String,
323 place: Place,
324 cx: &mut Context<Self>,
325 ) -> Stateful<Div> {
288 let active = self.place == place;
326 let active = self.place == place;
289 h_flex()
327 h_flex()
290 .id(id)
328 .id(id)
@@ -296,10 +334,24 @@ impl CloudPicker {
296 .rounded(px(6.))
334 .rounded(px(6.))
297 .cursor_pointer()
335 .cursor_pointer()
298 .text_size(px(13.))
336 .text_size(px(13.))
299 .text_color(if active { theme::text_strong() } else { theme::text() })
337 .text_color(if active {
300 .when(active, |row| row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD))
338 theme::text_strong()
339 } else {
340 theme::text()
341 })
342 .when(active, |row| {
343 row.bg(theme::selection()).font_weight(FontWeight::SEMIBOLD)
344 })
301 .hover(|row| row.bg(theme::row_hover()))
345 .hover(|row| row.bg(theme::row_hover()))
302 .child(symbol(glyph, 18., if active { theme::accent_text() } else { theme::text_soft() }))
346 .child(symbol(
347 glyph,
348 18.,
349 if active {
350 theme::accent_text()
351 } else {
352 theme::text_soft()
353 },
354 ))
303 .child(div().flex_1().min_w_0().truncate().child(label))
355 .child(div().flex_1().min_w_0().truncate().child(label))
304 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
356 .on_click(cx.listener(move |this, _, _, cx| this.open_place(place, cx)))
305 }
357 }
@@ -317,7 +369,13 @@ impl CloudPicker {
317 };
369 };
318 let mut sites = Vec::with_capacity(self.sites.len());
370 let mut sites = Vec::with_capacity(self.sites.len());
319 for (index, site) in self.sites.iter().enumerate() {
371 for (index, site) in self.sites.iter().enumerate() {
320 sites.push(self.nav_row(("cloud-picker-site", index), "domain", site.name.clone(), Place::Site(index), cx));
372 sites.push(self.nav_row(
373 ("cloud-picker-site", index),
374 "domain",
375 site.name.clone(),
376 Place::Site(index),
377 cx,
378 ));
321 }
379 }
322 v_flex()
380 v_flex()
323 .w(px(NAV_WIDTH))
381 .w(px(NAV_WIDTH))
@@ -335,11 +393,29 @@ impl CloudPicker {
335 .child("OneDrive"),
393 .child("OneDrive"),
336 )
394 )
337 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
395 .child(self.nav_row("cloud-picker-home", "home", "Home".into(), Place::Home, cx))
338 .child(self.nav_row("cloud-picker-mine", "folder", "My files".into(), Place::MyFiles, cx))
396 .child(self.nav_row(
339 .child(self.nav_row("cloud-picker-shared", "group", "Shared".into(), Place::Shared, cx))
397 "cloud-picker-mine",
398 "folder",
399 "My files".into(),
400 Place::MyFiles,
401 cx,
402 ))
403 .child(self.nav_row(
404 "cloud-picker-shared",
405 "group",
406 "Shared".into(),
407 Place::Shared,
408 cx,
409 ))
340 .when(!self.sites.is_empty(), |nav| {
410 .when(!self.sites.is_empty(), |nav| {
341 nav.child(section("Quick access"))
411 nav.child(section("Quick access")).child(
342 .child(v_flex().id("cloud-picker-sites").flex_1().min_h_0().overflow_y_scrollbar().children(sites))
412 v_flex()
413 .id("cloud-picker-sites")
414 .flex_1()
415 .min_h_0()
416 .overflow_y_scrollbar()
417 .children(sites),
418 )
343 })
419 })
344 }
420 }
345
421
@@ -356,10 +432,21 @@ impl CloudPicker {
356 .id(("cloud-picker-crumb", depth))
432 .id(("cloud-picker-crumb", depth))
357 .truncate()
433 .truncate()
358 .text_size(px(if current { 20. } else { 14. }))
434 .text_size(px(if current { 20. } else { 14. }))
359 .font_weight(if current { FontWeight::SEMIBOLD } else { FontWeight::NORMAL })
435 .font_weight(if current {
360 .text_color(if current { theme::text_strong() } else { theme::text_soft() })
436 FontWeight::SEMIBOLD
437 } else {
438 FontWeight::NORMAL
439 })
440 .text_color(if current {
441 theme::text_strong()
442 } else {
443 theme::text_soft()
444 })
361 .when(!current, |crumb| {
445 .when(!current, |crumb| {
362 crumb.cursor_pointer().hover(|crumb| crumb.text_color(theme::text())).on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
446 crumb
447 .cursor_pointer()
448 .hover(|crumb| crumb.text_color(theme::text()))
449 .on_click(cx.listener(move |this, _, _, cx| this.back_to(depth, cx)))
363 })
450 })
364 .child(crumb.name.clone()),
451 .child(crumb.name.clone()),
365 );
452 );
@@ -376,12 +463,21 @@ impl CloudPicker {
376 self.breadcrumb(cx)
463 self.breadcrumb(cx)
377 } else {
464 } else {
378 h_flex().child(
465 h_flex().child(
379 div().text_size(px(20.)).font_weight(FontWeight::SEMIBOLD).text_color(theme::text_strong()).child(self.title()),
466 div()
467 .text_size(px(20.))
468 .font_weight(FontWeight::SEMIBOLD)
469 .text_color(theme::text_strong())
470 .child(self.title()),
380 )
471 )
381 };
472 };
382 v_flex()
473 v_flex()
383 .gap(px(2.))
474 .gap(px(2.))
384 .children(site.map(|name| div().text_size(px(13.)).text_color(theme::text_soft()).child(name)))
475 .children(site.map(|name| {
476 div()
477 .text_size(px(13.))
478 .text_color(theme::text_soft())
479 .child(name)
480 }))
385 .child(title)
481 .child(title)
386 }
482 }
387
483
@@ -406,12 +502,20 @@ impl CloudPicker {
406
502
407 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
503 fn when_text(&self, entry: &DriveEntry, now: DateTime<Utc>) -> String {
408 match (self.place, entry.modified_at) {
504 match (self.place, entry.modified_at) {
409 (Place::Home, Some(opened)) => opened_ago(opened, now).unwrap_or_else(|| modified_text(entry)),
505 (Place::Home, Some(opened)) => {
506 opened_ago(opened, now).unwrap_or_else(|| modified_text(entry))
507 }
410 _ => modified_text(entry),
508 _ => modified_text(entry),
411 }
509 }
412 }
510 }
413
511
414 fn row(&self, index: usize, entry: &DriveEntry, now: DateTime<Utc>, cx: &mut Context<Self>) -> Stateful<Div> {
512 fn row(
513 &self,
514 index: usize,
515 entry: &DriveEntry,
516 now: DateTime<Utc>,
517 cx: &mut Context<Self>,
518 ) -> Stateful<Div> {
415 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
519 let picked = self.selected.iter().any(|selected| selected.id == entry.id);
416 let folder = entry.is_folder();
520 let folder = entry.is_folder();
417 let clicked = entry.clone();
521 let clicked = entry.clone();
@@ -429,11 +533,9 @@ impl CloudPicker {
429 .text_color(theme::text_soft())
533 .text_color(theme::text_soft())
430 .when(picked, |row| row.bg(theme::selection()))
534 .when(picked, |row| row.bg(theme::selection()))
431 .hover(|row| row.bg(theme::row_hover()))
535 .hover(|row| row.bg(theme::row_hover()))
432 .child(
536 .child(div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
433 div().w(px(CHECK_WIDTH)).flex_none().when(!folder, |cell| {
537 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
434 cell.child(Checkbox::new(("cloud-picker-check", index)).checked(picked))
538 }))
435 }),
436 )
437 .child(
539 .child(
438 h_flex()
540 h_flex()
439 .flex_1()
541 .flex_1()
@@ -441,25 +543,49 @@ impl CloudPicker {
441 .gap(px(10.))
543 .gap(px(10.))
442 .items_center()
544 .items_center()
443 .child(entry_badge(entry))
545 .child(entry_badge(entry))
444 .child(div().truncate().text_color(theme::text()).child(entry.name.clone())),
546 .child(
547 div()
548 .truncate()
549 .text_color(theme::text())
550 .child(entry.name.clone()),
551 ),
552 )
553 .child(
554 div()
555 .w(px(WHEN_WIDTH))
556 .flex_none()
557 .truncate()
558 .child(self.when_text(entry, now)),
559 )
560 .child(
561 div()
562 .w(px(WHO_WIDTH))
563 .flex_none()
564 .truncate()
565 .child(entry.modified_by.clone().unwrap_or_default()),
445 )
566 )
446 .child(div().w(px(WHEN_WIDTH)).flex_none().truncate().child(self.when_text(entry, now)))
447 .child(div().w(px(WHO_WIDTH)).flex_none().truncate().child(entry.modified_by.clone().unwrap_or_default()))
448 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
567 .on_click(cx.listener(move |this, _, _, cx| this.click_row(clicked.clone(), cx)))
449 }
568 }
450
569
451 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
570 fn table(&self, cx: &mut Context<Self>) -> AnyElement {
452 let note = |text: &'static str| {
571 let note = |text: &'static str| {
453 div().p(px(16.)).text_size(px(13.)).text_color(theme::text_soft()).child(text).into_any_element()
572 div()
573 .p(px(16.))
574 .text_size(px(13.))
575 .text_color(theme::text_soft())
576 .child(text)
577 .into_any_element()
454 };
578 };
455 let now = Utc::now();
579 let now = Utc::now();
456 let body: Vec<AnyElement> = match &self.rows {
580 let body: Vec<AnyElement> = match &self.rows {
457 Rows::Loading => vec![note("Loading ...")],
581 Rows::Loading => vec![note("Loading ...")],
458 Rows::Failed => vec![note("Couldn't load files.")],
582 Rows::Failed => vec![note("Couldn't load files.")],
459 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
583 Rows::Ready(entries) if entries.is_empty() => vec![note("This folder is empty.")],
460 Rows::Ready(entries) => {
584 Rows::Ready(entries) => entries
461 entries.iter().enumerate().map(|(index, entry)| self.row(index, entry, now, cx).into_any_element()).collect()
585 .iter()
462 }
586 .enumerate()
587 .map(|(index, entry)| self.row(index, entry, now, cx).into_any_element())
588 .collect(),
463 };
589 };
464 v_flex()
590 v_flex()
465 .flex_1()
591 .flex_1()
@@ -468,7 +594,14 @@ impl CloudPicker {
468 .bg(theme::surface_raised())
594 .bg(theme::surface_raised())
469 .overflow_hidden()
595 .overflow_hidden()
470 .child(self.column_header())
596 .child(self.column_header())
471 .child(v_flex().id("cloud-picker-rows").flex_1().min_h_0().overflow_y_scrollbar().children(body))
597 .child(
598 v_flex()
599 .id("cloud-picker-rows")
600 .flex_1()
601 .min_h_0()
602 .overflow_y_scrollbar()
603 .children(body),
604 )
472 .into_any_element()
605 .into_any_element()
473 }
606 }
474}
607}
@@ -506,15 +639,13 @@ impl Render for CloudPicker {
506 .child(
639 .child(
507 Button::new("cloud-picker-attach")
640 Button::new("cloud-picker-attach")
508 .primary()
641 .primary()
509 .label("Attach")
642 .label(tr("common.attach"))
510 .disabled(!can_attach)
643 .disabled(!can_attach)
511 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
644 .on_click(cx.listener(|this, _, _, cx| this.attach(cx))),
512 )
645 )
513 .child(
646 .child(Button::new("cloud-picker-cancel").label(tr("common.cancel")).on_click(
514 Button::new("cloud-picker-cancel")
647 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
515 .label("Cancel")
648 )),
516 .on_click(cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close))),
517 ),
518 ),
649 ),
519 );
650 );
520 deferred(
651 deferred(
@@ -534,7 +665,10 @@ impl Render for CloudPicker {
534 cx.emit(CloudPickerEvent::Close);
665 cx.emit(CloudPickerEvent::Close);
535 }
666 }
536 }))
667 }))
537 .on_mouse_down(MouseButton::Left, cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)))
668 .on_mouse_down(
669 MouseButton::Left,
670 cx.listener(|_, _, _, cx| cx.emit(CloudPickerEvent::Close)),
671 )
538 .child(panel),
672 .child(panel),
539 ),
673 ),
540 )
674 )
@@ -551,15 +685,27 @@ mod tests {
551 #[test]
685 #[test]
552 fn home_shows_hours_ago_like_the_onedrive_picker() {
686 fn home_shows_hours_ago_like_the_onedrive_picker() {
553 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
687 let now = Utc.with_ymd_and_hms(2026, 11, 10, 22, 0, 0).unwrap();
554 assert_eq!(opened_ago(now - chrono::Duration::hours(9), now).as_deref(), Some("9h ago"));
688 assert_eq!(
555 assert_eq!(opened_ago(now - chrono::Duration::minutes(5), now).as_deref(), Some("5m ago"));
689 opened_ago(now - chrono::Duration::hours(9), now).as_deref(),
690 Some("9h ago")
691 );
692 assert_eq!(
693 opened_ago(now - chrono::Duration::minutes(5), now).as_deref(),
694 Some("5m ago")
695 );
556 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
696 assert_eq!(opened_ago(now - chrono::Duration::days(3), now), None);
557 }
697 }
558
698
559 #[test]
699 #[test]
560 fn each_place_has_the_picker_columns() {
700 fn each_place_has_the_picker_columns() {
561 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
701 assert_eq!(Place::Home.columns(), ["Name", "Opened", "Owner"]);
562 assert_eq!(Place::Shared.columns(), ["Name", "Date shared", "Shared by"]);
702 assert_eq!(
563 assert_eq!(Place::Site(0).columns(), ["Name", "Modified", "Modified By"]);
703 Place::Shared.columns(),
704 ["Name", "Date shared", "Shared by"]
705 );
706 assert_eq!(
707 Place::Site(0).columns(),
708 ["Name", "Modified", "Modified By"]
709 );
564 }
710 }
565}
711}
crates/app/src/views/conversation.rs +3 −2
@@ -74,6 +74,7 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
74 74 use super::scroll_edge::edge_divider;
75 75 use super::toolbar_placement::{TimelineBounds, record_bounds};
76 76 use super::widgets::{icon, symbol};
77 use crate::i18n::tr;
77 78 use crate::agents::{AgentRun, StartRequest};
78 79 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
79 80 use crate::backend::Engine;
@@ -3686,7 +3687,7 @@ impl ConversationView {
3686 3687 Button::new("retry-new-chat")
3687 3688 .ghost()
3688 3689 .compact()
3689 .label("Retry")
3690 .label(tr("common.retry"))
3690 3691 .on_click(cx.listener(move |this, _, window, cx| {
3691 3692 this.retry(&failed_key, window, cx)
3692 3693 })),
@@ -4229,7 +4230,7 @@ impl Render for ConversationView {
4229 4230 Button::new("retry-fetch")
4230 4231 .ghost()
4231 4232 .compact()
4232 .label("Retry")
4233 .label(tr("common.retry"))
4233 4234 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
4234 4235 )
4235 4236 }),
@@ -74,6 +74,7 @@ use super::reaction_pills::{ReactionControls, ReactionPopover};
74use super::scroll_edge::edge_divider;
74use super::scroll_edge::edge_divider;
75use super::toolbar_placement::{TimelineBounds, record_bounds};
75use super::toolbar_placement::{TimelineBounds, record_bounds};
76use super::widgets::{icon, symbol};
76use super::widgets::{icon, symbol};
77use crate::i18n::tr;
77use crate::agents::{AgentRun, StartRequest};
78use crate::agents::{AgentRun, StartRequest};
78use crate::app_state::{AppEvent, AppState, Selection, selection_title};
79use crate::app_state::{AppEvent, AppState, Selection, selection_title};
79use crate::backend::Engine;
80use crate::backend::Engine;
@@ -3686,7 +3687,7 @@ impl ConversationView {
3686 Button::new("retry-new-chat")
3687 Button::new("retry-new-chat")
3687 .ghost()
3688 .ghost()
3688 .compact()
3689 .compact()
3689 .label("Retry")
3690 .label(tr("common.retry"))
3690 .on_click(cx.listener(move |this, _, window, cx| {
3691 .on_click(cx.listener(move |this, _, window, cx| {
3691 this.retry(&failed_key, window, cx)
3692 this.retry(&failed_key, window, cx)
3692 })),
3693 })),
@@ -4229,7 +4230,7 @@ impl Render for ConversationView {
4229 Button::new("retry-fetch")
4230 Button::new("retry-fetch")
4230 .ghost()
4231 .ghost()
4231 .compact()
4232 .compact()
4232 .label("Retry")
4233 .label(tr("common.retry"))
4233 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
4234 .on_click(cx.listener(|this, _, _, cx| this.retry_fetch(cx))),
4234 )
4235 )
4235 }),
4236 }),
crates/app/src/views/conversation/feed.rs +19 −19
@@ -11,6 +11,7 @@ use gpui_kit::component::{
11 11 use gpui_kit::*;
12 12
13 13 use super::{ConversationView, ViewMode};
14 use crate::i18n::tr;
14 15 use crate::notice::short_error;
15 16 use crate::rows::Row;
16 17 use crate::runtime;
@@ -18,7 +19,6 @@ use crate::views::channel_tabs::ChannelPane;
18 19 use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
19 20 use crate::views::post_card::{PostAction, post_in_channel_card};
20 21
21 const FEED_CARD_TOP: f32 = 12.;
22 22 const REPLY_PLACEHOLDER: &str = "Reply in thread";
23 23
24 24 pub(super) struct FeedStash {
@@ -31,7 +31,9 @@ pub(super) fn subject_input(
31 31 window: &mut Window,
32 32 cx: &mut Context<ConversationView>,
33 33 ) -> Entity<InputState> {
34 cx.new(|cx| InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER))
34 cx.new(|cx| {
35 InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER)
36 })
35 37 }
36 38
37 39 impl ConversationView {
@@ -161,7 +163,11 @@ impl ConversationView {
161 163 let view = cx.entity().downgrade();
162 164 window.on_next_frame(move |_, cx| {
163 165 view.update(cx, |this, cx| {
164 let index = this.rows.borrow().iter().position(|row| row.key() == root_id);
166 let index = this
167 .rows
168 .borrow()
169 .iter()
170 .position(|row| row.key() == root_id);
165 171 if let Some(index) = index {
166 172 this.scroller
167 173 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
@@ -280,14 +286,13 @@ impl ConversationView {
280 286 if !self.in_feed() || self.pane != ChannelPane::Posts {
281 287 return None;
282 288 }
283 let proposal_card = self
284 .render_proposal_card(cx)
285 .map(|card| div().w_full().pt(px(FEED_CARD_TOP)).child(card));
289 let proposal_card = self.render_proposal_card(cx);
286 290 if !self.new_post_open {
287 291 let view = cx.entity().downgrade();
288 292 let announce_view = view.clone();
289 293 let open: PostAction = Box::new(move |window, cx| {
290 view.update(cx, |this, cx| this.open_new_post(window, cx)).ok();
294 view.update(cx, |this, cx| this.open_new_post(window, cx))
295 .ok();
291 296 });
292 297 let announce: PostAction = Box::new(move |window, cx| {
293 298 announce_view
@@ -299,14 +304,9 @@ impl ConversationView {
299 304 .w_full()
300 305 .flex_none()
301 306 .children(proposal_card)
302 .child(
303 div()
304 .w_full()
305 .flex_none()
306 .px(px(20.))
307 .py(px(12.))
308 .child(post_in_channel_card(&self.app.read(cx).directory, open, announce)),
309 )
307 .child(div().w_full().flex_none().px(px(20.)).py(px(12.)).child(
308 post_in_channel_card(&self.app.read(cx).directory, open, announce),
309 ))
310 310 .into_any_element(),
311 311 );
312 312 }
@@ -321,10 +321,10 @@ impl ConversationView {
321 321 Button::new("cancel-new-post")
322 322 .ghost()
323 323 .compact()
324 .label("Cancel")
325 .on_click(cx.listener(|this, _, window, cx| {
326 this.cancel_new_post(window, cx)
327 })),
324 .label(tr("common.cancel"))
325 .on_click(
326 cx.listener(|this, _, window, cx| this.cancel_new_post(window, cx)),
327 ),
328 328 )
329 329 });
330 330 Some(
@@ -11,6 +11,7 @@ use gpui_kit::component::{
11use gpui_kit::*;
11use gpui_kit::*;
12
12
13use super::{ConversationView, ViewMode};
13use super::{ConversationView, ViewMode};
14use crate::i18n::tr;
14use crate::notice::short_error;
15use crate::notice::short_error;
15use crate::rows::Row;
16use crate::rows::Row;
16use crate::runtime;
17use crate::runtime;
@@ -18,7 +19,6 @@ use crate::views::channel_tabs::ChannelPane;
18use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
19use crate::views::composer::{Composer, ComposerEvent, ReplyPreview};
19use crate::views::post_card::{PostAction, post_in_channel_card};
20use crate::views::post_card::{PostAction, post_in_channel_card};
20
21
21const FEED_CARD_TOP: f32 = 12.;
22const REPLY_PLACEHOLDER: &str = "Reply in thread";
22const REPLY_PLACEHOLDER: &str = "Reply in thread";
23
23
24pub(super) struct FeedStash {
24pub(super) struct FeedStash {
@@ -31,7 +31,9 @@ pub(super) fn subject_input(
31 window: &mut Window,
31 window: &mut Window,
32 cx: &mut Context<ConversationView>,
32 cx: &mut Context<ConversationView>,
33) -> Entity<InputState> {
33) -> Entity<InputState> {
34 cx.new(|cx| InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER))
34 cx.new(|cx| {
35 InputState::new(window, cx).placeholder(crate::views::composer::SUBJECT_PLACEHOLDER)
36 })
35}
37}
36
38
37impl ConversationView {
39impl ConversationView {
@@ -161,7 +163,11 @@ impl ConversationView {
161 let view = cx.entity().downgrade();
163 let view = cx.entity().downgrade();
162 window.on_next_frame(move |_, cx| {
164 window.on_next_frame(move |_, cx| {
163 view.update(cx, |this, cx| {
165 view.update(cx, |this, cx| {
164 let index = this.rows.borrow().iter().position(|row| row.key() == root_id);
166 let index = this
167 .rows
168 .borrow()
169 .iter()
170 .position(|row| row.key() == root_id);
165 if let Some(index) = index {
171 if let Some(index) = index {
166 this.scroller
172 this.scroller
167 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
173 .update(cx, |scroller, cx| scroller.reveal_item_bottom(index, cx));
@@ -280,14 +286,13 @@ impl ConversationView {
280 if !self.in_feed() || self.pane != ChannelPane::Posts {
286 if !self.in_feed() || self.pane != ChannelPane::Posts {
281 return None;
287 return None;
282 }
288 }
283 let proposal_card = self
289 let proposal_card = self.render_proposal_card(cx);
284 .render_proposal_card(cx)
285 .map(|card| div().w_full().pt(px(FEED_CARD_TOP)).child(card));
286 if !self.new_post_open {
290 if !self.new_post_open {
287 let view = cx.entity().downgrade();
291 let view = cx.entity().downgrade();
288 let announce_view = view.clone();
292 let announce_view = view.clone();
289 let open: PostAction = Box::new(move |window, cx| {
293 let open: PostAction = Box::new(move |window, cx| {
290 view.update(cx, |this, cx| this.open_new_post(window, cx)).ok();
294 view.update(cx, |this, cx| this.open_new_post(window, cx))
295 .ok();
291 });
296 });
292 let announce: PostAction = Box::new(move |window, cx| {
297 let announce: PostAction = Box::new(move |window, cx| {
293 announce_view
298 announce_view
@@ -299,14 +304,9 @@ impl ConversationView {
299 .w_full()
304 .w_full()
300 .flex_none()
305 .flex_none()
301 .children(proposal_card)
306 .children(proposal_card)
302 .child(
307 .child(div().w_full().flex_none().px(px(20.)).py(px(12.)).child(
303 div()
308 post_in_channel_card(&self.app.read(cx).directory, open, announce),
304 .w_full()
309 ))
305 .flex_none()
306 .px(px(20.))
307 .py(px(12.))
308 .child(post_in_channel_card(&self.app.read(cx).directory, open, announce)),
309 )
310 .into_any_element(),
310 .into_any_element(),
311 );
311 );
312 }
312 }
@@ -321,10 +321,10 @@ impl ConversationView {
321 Button::new("cancel-new-post")
321 Button::new("cancel-new-post")
322 .ghost()
322 .ghost()
323 .compact()
323 .compact()
324 .label("Cancel")
324 .label(tr("common.cancel"))
325 .on_click(cx.listener(|this, _, window, cx| {
325 .on_click(
326 this.cancel_new_post(window, cx)
326 cx.listener(|this, _, window, cx| this.cancel_new_post(window, cx)),
327 })),
327 ),
328 )
328 )
329 });
329 });
330 Some(
330 Some(
crates/app/src/views/conversation/pins.rs +2 −1
@@ -9,6 +9,7 @@ use gpui_kit::component::WindowExt as _;
9 9 use gpui_kit::component::button::{Button, ButtonVariants as _};
10 10 use gpui_kit::component::dialog::DialogFooter;
11 11
12 use crate::i18n::tr;
12 13 use crate::app_state::{AppState, Selection, selection_title};
13 14 use crate::channel_menu::post_pin_dialog;
14 15 use crate::post_follow::post_followed;
@@ -46,7 +47,7 @@ fn confirm_post_pin(
46 47 let (state, channel_id, message_id) =
47 48 (state.clone(), channel_id.clone(), message_id.clone());
48 49 let cancel = Button::new("post-pin-cancel")
49 .label("Cancel")
50 .label(tr("common.cancel"))
50 51 .on_click(|_, window, cx| window.close_dialog(cx));
51 52 let confirm = Button::new("post-pin-confirm")
52 53 .label(dialog.confirm)
@@ -9,6 +9,7 @@ use gpui_kit::component::WindowExt as _;
9use gpui_kit::component::button::{Button, ButtonVariants as _};
9use gpui_kit::component::button::{Button, ButtonVariants as _};
10use gpui_kit::component::dialog::DialogFooter;
10use gpui_kit::component::dialog::DialogFooter;
11
11
12use crate::i18n::tr;
12use crate::app_state::{AppState, Selection, selection_title};
13use crate::app_state::{AppState, Selection, selection_title};
13use crate::channel_menu::post_pin_dialog;
14use crate::channel_menu::post_pin_dialog;
14use crate::post_follow::post_followed;
15use crate::post_follow::post_followed;
@@ -46,7 +47,7 @@ fn confirm_post_pin(
46 let (state, channel_id, message_id) =
47 let (state, channel_id, message_id) =
47 (state.clone(), channel_id.clone(), message_id.clone());
48 (state.clone(), channel_id.clone(), message_id.clone());
48 let cancel = Button::new("post-pin-cancel")
49 let cancel = Button::new("post-pin-cancel")
49 .label("Cancel")
50 .label(tr("common.cancel"))
50 .on_click(|_, window, cx| window.close_dialog(cx));
51 .on_click(|_, window, cx| window.close_dialog(cx));
51 let confirm = Button::new("post-pin-confirm")
52 let confirm = Button::new("post-pin-confirm")
52 .label(dialog.confirm)
53 .label(dialog.confirm)
crates/app/src/views/conversation/recap.rs +3 −2
@@ -15,6 +15,7 @@ use gpui_kit::component::WindowExt as _;
15 15 use gpui_kit::*;
16 16
17 17 use super::ConversationView;
18 use crate::i18n::tr;
18 19 use crate::app_state::{AppState, Selection};
19 20 use crate::rows::{MeetingInfo, MeetingSlot};
20 21 use crate::channel_files::SharedContent;
@@ -473,10 +474,10 @@ impl ConversationView {
473 474 window.open_alert_dialog(cx, move |alert, _, _| {
474 475 let view = view.clone();
475 476 let cancel = Button::new("recap-delete-cancel")
476 .label("Cancel")
477 .label(tr("common.cancel"))
477 478 .on_click(|_, window, cx| window.close_dialog(cx));
478 479 let delete = Button::new("recap-delete-confirm")
479 .label("Delete")
480 .label(tr("common.delete"))
480 481 .danger()
481 482 .on_click(move |_, window, cx| {
482 483 view.update(cx, |this, cx| this.delete_recording(cx)).ok();
@@ -15,6 +15,7 @@ use gpui_kit::component::WindowExt as _;
15use gpui_kit::*;
15use gpui_kit::*;
16
16
17use super::ConversationView;
17use super::ConversationView;
18use crate::i18n::tr;
18use crate::app_state::{AppState, Selection};
19use crate::app_state::{AppState, Selection};
19use crate::rows::{MeetingInfo, MeetingSlot};
20use crate::rows::{MeetingInfo, MeetingSlot};
20use crate::channel_files::SharedContent;
21use crate::channel_files::SharedContent;
@@ -473,10 +474,10 @@ impl ConversationView {
473 window.open_alert_dialog(cx, move |alert, _, _| {
474 window.open_alert_dialog(cx, move |alert, _, _| {
474 let view = view.clone();
475 let view = view.clone();
475 let cancel = Button::new("recap-delete-cancel")
476 let cancel = Button::new("recap-delete-cancel")
476 .label("Cancel")
477 .label(tr("common.cancel"))
477 .on_click(|_, window, cx| window.close_dialog(cx));
478 .on_click(|_, window, cx| window.close_dialog(cx));
478 let delete = Button::new("recap-delete-confirm")
479 let delete = Button::new("recap-delete-confirm")
479 .label("Delete")
480 .label(tr("common.delete"))
480 .danger()
481 .danger()
481 .on_click(move |_, window, cx| {
482 .on_click(move |_, window, cx| {
482 view.update(cx, |this, cx| this.delete_recording(cx)).ok();
483 view.update(cx, |this, cx| this.delete_recording(cx)).ok();
crates/app/src/views/create_channel_dialog.rs +3 −2
@@ -8,6 +8,7 @@ use gpui_kit::*;
8 8 use teams_core::ChannelPrivacy;
9 9
10 10 use super::new_meeting_dialog::labeled;
11 use crate::i18n::tr;
11 12 use crate::app_state::AppState;
12 13 use crate::team_admin::{can_create_channel, channel_name_problem};
13 14 use crate::theme;
@@ -166,13 +167,13 @@ pub fn open_create_channel_dialog(
166 167 let footer = DialogFooter::new()
167 168 .child(
168 169 Button::new("create-channel-cancel")
169 .label("Cancel")
170 .label(tr("common.cancel"))
170 171 .on_click(|_, window, cx| window.close_dialog(cx)),
171 172 )
172 173 .child(
173 174 Button::new("create-channel-confirm")
174 175 .primary()
175 .label("Create")
176 .label(tr("common.create"))
176 177 .disabled(!can_create)
177 178 .on_click(move |_, window, cx| {
178 179 if submit_form.update(cx, |form, cx| form.submit(cx)) {
@@ -8,6 +8,7 @@ use gpui_kit::*;
8use teams_core::ChannelPrivacy;
8use teams_core::ChannelPrivacy;
9
9
10use super::new_meeting_dialog::labeled;
10use super::new_meeting_dialog::labeled;
11use crate::i18n::tr;
11use crate::app_state::AppState;
12use crate::app_state::AppState;
12use crate::team_admin::{can_create_channel, channel_name_problem};
13use crate::team_admin::{can_create_channel, channel_name_problem};
13use crate::theme;
14use crate::theme;
@@ -166,13 +167,13 @@ pub fn open_create_channel_dialog(
166 let footer = DialogFooter::new()
167 let footer = DialogFooter::new()
167 .child(
168 .child(
168 Button::new("create-channel-cancel")
169 Button::new("create-channel-cancel")
169 .label("Cancel")
170 .label(tr("common.cancel"))
170 .on_click(|_, window, cx| window.close_dialog(cx)),
171 .on_click(|_, window, cx| window.close_dialog(cx)),
171 )
172 )
172 .child(
173 .child(
173 Button::new("create-channel-confirm")
174 Button::new("create-channel-confirm")
174 .primary()
175 .primary()
175 .label("Create")
176 .label(tr("common.create"))
176 .disabled(!can_create)
177 .disabled(!can_create)
177 .on_click(move |_, window, cx| {
178 .on_click(move |_, window, cx| {
178 if submit_form.update(cx, |form, cx| form.submit(cx)) {
179 if submit_form.update(cx, |form, cx| form.submit(cx)) {
crates/app/src/views/customize_reactions.rs +3 −2
@@ -12,6 +12,7 @@ use gpui_kit::*;
12 12
13 13 use super::reaction_picker::ReactionPicker;
14 14 use super::widgets::{Corner, corner_badge, icon};
15 use crate::i18n::tr;
15 16 use crate::app_state::AppState;
16 17 use crate::default_reactions::{
17 18 filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
@@ -248,13 +249,13 @@ pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx
248 249 let footer = DialogFooter::new()
249 250 .child(
250 251 Button::new("customize-reactions-cancel")
251 .label("Cancel")
252 .label(tr("common.cancel"))
252 253 .on_click(|_, window, cx| window.close_dialog(cx)),
253 254 )
254 255 .child(
255 256 Button::new("customize-reactions-save")
256 257 .primary()
257 .label("Save")
258 .label(tr("common.save"))
258 259 .disabled(unchanged)
259 260 .on_click(move |_, window, cx| {
260 261 submit_form.update(cx, |form, cx| form.save(window, cx));
@@ -12,6 +12,7 @@ use gpui_kit::*;
12
12
13use super::reaction_picker::ReactionPicker;
13use super::reaction_picker::ReactionPicker;
14use super::widgets::{Corner, corner_badge, icon};
14use super::widgets::{Corner, corner_badge, icon};
15use crate::i18n::tr;
15use crate::app_state::AppState;
16use crate::app_state::AppState;
16use crate::default_reactions::{
17use crate::default_reactions::{
17 filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
18 filled, place_in_slot, quick_reaction_glyphs, reaction_id_for_glyph, slots_for,
@@ -248,13 +249,13 @@ pub fn open_customize_reactions(state: Entity<AppState>, window: &mut Window, cx
248 let footer = DialogFooter::new()
249 let footer = DialogFooter::new()
249 .child(
250 .child(
250 Button::new("customize-reactions-cancel")
251 Button::new("customize-reactions-cancel")
251 .label("Cancel")
252 .label(tr("common.cancel"))
252 .on_click(|_, window, cx| window.close_dialog(cx)),
253 .on_click(|_, window, cx| window.close_dialog(cx)),
253 )
254 )
254 .child(
255 .child(
255 Button::new("customize-reactions-save")
256 Button::new("customize-reactions-save")
256 .primary()
257 .primary()
257 .label("Save")
258 .label(tr("common.save"))
258 .disabled(unchanged)
259 .disabled(unchanged)
259 .on_click(move |_, window, cx| {
260 .on_click(move |_, window, cx| {
260 submit_form.update(cx, |form, cx| form.save(window, cx));
261 submit_form.update(cx, |form, cx| form.save(window, cx));
crates/app/src/views/forward_dialog.rs +2 −1
@@ -11,6 +11,7 @@ use gpui_kit::*;
11 11
12 12 use super::switcher::{Candidate, candidate_avatar, clamp_highlight};
13 13 use super::widgets::{icon, symbol};
14 use crate::i18n::tr;
14 15 use crate::app_state::{AppState, Selection};
15 16 use crate::fuzzy;
16 17 use crate::message_actions::{ForwardItem, ForwardSource};
@@ -526,7 +527,7 @@ impl Render for ForwardDialog {
526 527 .child(
527 528 Button::new("forward-cancel")
528 529 .ghost()
529 .label("Cancel")
530 .label(tr("common.cancel"))
530 531 .on_click(cx.listener(|_, _, _, cx| {
531 532 cx.emit(ForwardDialogEvent::Close)
532 533 })),
@@ -11,6 +11,7 @@ use gpui_kit::*;
11
11
12use super::switcher::{Candidate, candidate_avatar, clamp_highlight};
12use super::switcher::{Candidate, candidate_avatar, clamp_highlight};
13use super::widgets::{icon, symbol};
13use super::widgets::{icon, symbol};
14use crate::i18n::tr;
14use crate::app_state::{AppState, Selection};
15use crate::app_state::{AppState, Selection};
15use crate::fuzzy;
16use crate::fuzzy;
16use crate::message_actions::{ForwardItem, ForwardSource};
17use crate::message_actions::{ForwardItem, ForwardSource};
@@ -526,7 +527,7 @@ impl Render for ForwardDialog {
526 .child(
527 .child(
527 Button::new("forward-cancel")
528 Button::new("forward-cancel")
528 .ghost()
529 .ghost()
529 .label("Cancel")
530 .label(tr("common.cancel"))
530 .on_click(cx.listener(|_, _, _, cx| {
531 .on_click(cx.listener(|_, _, _, cx| {
531 cx.emit(ForwardDialogEvent::Close)
532 cx.emit(ForwardDialogEvent::Close)
532 })),
533 })),
crates/app/src/views/group_name.rs +3 −2
@@ -12,6 +12,7 @@ use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
13 13
14 14 use super::widgets::icon;
15 use crate::i18n::tr;
15 16 use crate::app_state::AppState;
16 17 use crate::theme;
17 18
@@ -135,13 +136,13 @@ impl Render for GroupNameForm {
135 136 .gap(px(FORM_GAP))
136 137 .child(
137 138 Button::new("group-name-cancel")
138 .label("Cancel")
139 .label(tr("common.cancel"))
139 140 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
140 141 )
141 142 .child(
142 143 Button::new("group-name-save")
143 144 .primary()
144 .label("Save")
145 .label(tr("common.save"))
145 146 .disabled(problem.is_some())
146 147 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
147 148 ),
@@ -12,6 +12,7 @@ use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
13
13
14use super::widgets::icon;
14use super::widgets::icon;
15use crate::i18n::tr;
15use crate::app_state::AppState;
16use crate::app_state::AppState;
16use crate::theme;
17use crate::theme;
17
18
@@ -135,13 +136,13 @@ impl Render for GroupNameForm {
135 .gap(px(FORM_GAP))
136 .gap(px(FORM_GAP))
136 .child(
137 .child(
137 Button::new("group-name-cancel")
138 Button::new("group-name-cancel")
138 .label("Cancel")
139 .label(tr("common.cancel"))
139 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
140 .on_click(cx.listener(|form, _, window, cx| form.close(window, cx))),
140 )
141 )
141 .child(
142 .child(
142 Button::new("group-name-save")
143 Button::new("group-name-save")
143 .primary()
144 .primary()
144 .label("Save")
145 .label(tr("common.save"))
145 .disabled(problem.is_some())
146 .disabled(problem.is_some())
146 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
147 .on_click(cx.listener(|form, _, window, cx| form.save(window, cx))),
147 ),
148 ),
crates/app/src/views/join_dialog.rs +13 −7
@@ -5,13 +5,13 @@ use gpui_kit::component::{WindowExt as _, v_flex};
5 5 use gpui_kit::prelude::FluentBuilder as _;
6 6 use gpui_kit::*;
7 7
8 use crate::i18n::tr;
8 9 use crate::app_state::AppState;
9 10 use crate::theme;
10 11
11 12 const DIALOG_WIDTH: f32 = 380.;
12 13 const FIELD_GAP: f32 = 12.;
13 14 const LABEL_SIZE: f32 = 12.;
14 const TITLE: &str = "Join with a meeting ID";
15 15
16 16 struct JoinForm {
17 17 state: Entity<AppState>,
@@ -25,7 +25,7 @@ impl JoinForm {
25 25 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
26 26 let meeting_id = cx.new(|cx| InputState::new(window, cx).placeholder("123 456 789 012"));
27 27 let passcode = cx.new(|cx| {
28 InputState::new(window, cx).placeholder("Passcode (if the invitation has one)")
28 InputState::new(window, cx).placeholder(tr("calls.join_dialog.passcode_placeholder"))
29 29 });
30 30 let subscriptions = [
31 31 cx.subscribe_in(&meeting_id, window, Self::on_enter),
@@ -80,8 +80,14 @@ impl Render for JoinForm {
80 80 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
81 81 v_flex()
82 82 .gap(px(FIELD_GAP))
83 .child(labeled("Meeting ID", Input::new(&self.meeting_id)))
84 .child(labeled("Passcode", Input::new(&self.passcode)))
83 .child(labeled(
84 &tr("calls.join_dialog.meeting_id"),
85 Input::new(&self.meeting_id),
86 ))
87 .child(labeled(
88 &tr("calls.join_dialog.passcode"),
89 Input::new(&self.passcode),
90 ))
85 91 .when_some(self.error.clone(), |form, error| {
86 92 form.child(
87 93 div()
@@ -101,13 +107,13 @@ pub fn open_join_with_id(state: Entity<AppState>, window: &mut Window, cx: &mut
101 107 let footer = DialogFooter::new()
102 108 .child(
103 109 Button::new("join-cancel")
104 .label("Cancel")
110 .label(tr("common.cancel"))
105 111 .on_click(|_, window, cx| window.close_dialog(cx)),
106 112 )
107 113 .child(
108 114 Button::new("join-confirm")
109 115 .primary()
110 .label("Join")
116 .label(tr("common.join"))
111 117 .on_click(move |_, window, cx| {
112 118 if submit_form.update(cx, |form, cx| form.submit(cx)) {
113 119 window.close_dialog(cx);
@@ -115,7 +121,7 @@ pub fn open_join_with_id(state: Entity<AppState>, window: &mut Window, cx: &mut
115 121 }),
116 122 );
117 123 dialog
118 .title(TITLE)
124 .title(tr("calls.join_dialog.title"))
119 125 .w(px(DIALOG_WIDTH))
120 126 .child(form.clone())
121 127 .footer(footer)
@@ -5,13 +5,13 @@ use gpui_kit::component::{WindowExt as _, v_flex};
5use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::prelude::FluentBuilder as _;
6use gpui_kit::*;
6use gpui_kit::*;
7
7
8use crate::i18n::tr;
8use crate::app_state::AppState;
9use crate::app_state::AppState;
9use crate::theme;
10use crate::theme;
10
11
11const DIALOG_WIDTH: f32 = 380.;
12const DIALOG_WIDTH: f32 = 380.;
12const FIELD_GAP: f32 = 12.;
13const FIELD_GAP: f32 = 12.;
13const LABEL_SIZE: f32 = 12.;
14const LABEL_SIZE: f32 = 12.;
14const TITLE: &str = "Join with a meeting ID";
15
15
16struct JoinForm {
16struct JoinForm {
17 state: Entity<AppState>,
17 state: Entity<AppState>,
@@ -25,7 +25,7 @@ impl JoinForm {
25 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
25 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
26 let meeting_id = cx.new(|cx| InputState::new(window, cx).placeholder("123 456 789 012"));
26 let meeting_id = cx.new(|cx| InputState::new(window, cx).placeholder("123 456 789 012"));
27 let passcode = cx.new(|cx| {
27 let passcode = cx.new(|cx| {
28 InputState::new(window, cx).placeholder("Passcode (if the invitation has one)")
28 InputState::new(window, cx).placeholder(tr("calls.join_dialog.passcode_placeholder"))
29 });
29 });
30 let subscriptions = [
30 let subscriptions = [
31 cx.subscribe_in(&meeting_id, window, Self::on_enter),
31 cx.subscribe_in(&meeting_id, window, Self::on_enter),
@@ -80,8 +80,14 @@ impl Render for JoinForm {
80 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
80 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
81 v_flex()
81 v_flex()
82 .gap(px(FIELD_GAP))
82 .gap(px(FIELD_GAP))
83 .child(labeled("Meeting ID", Input::new(&self.meeting_id)))
83 .child(labeled(
84 .child(labeled("Passcode", Input::new(&self.passcode)))
84 &tr("calls.join_dialog.meeting_id"),
85 Input::new(&self.meeting_id),
86 ))
87 .child(labeled(
88 &tr("calls.join_dialog.passcode"),
89 Input::new(&self.passcode),
90 ))
85 .when_some(self.error.clone(), |form, error| {
91 .when_some(self.error.clone(), |form, error| {
86 form.child(
92 form.child(
87 div()
93 div()
@@ -101,13 +107,13 @@ pub fn open_join_with_id(state: Entity<AppState>, window: &mut Window, cx: &mut
101 let footer = DialogFooter::new()
107 let footer = DialogFooter::new()
102 .child(
108 .child(
103 Button::new("join-cancel")
109 Button::new("join-cancel")
104 .label("Cancel")
110 .label(tr("common.cancel"))
105 .on_click(|_, window, cx| window.close_dialog(cx)),
111 .on_click(|_, window, cx| window.close_dialog(cx)),
106 )
112 )
107 .child(
113 .child(
108 Button::new("join-confirm")
114 Button::new("join-confirm")
109 .primary()
115 .primary()
110 .label("Join")
116 .label(tr("common.join"))
111 .on_click(move |_, window, cx| {
117 .on_click(move |_, window, cx| {
112 if submit_form.update(cx, |form, cx| form.submit(cx)) {
118 if submit_form.update(cx, |form, cx| form.submit(cx)) {
113 window.close_dialog(cx);
119 window.close_dialog(cx);
@@ -115,7 +121,7 @@ pub fn open_join_with_id(state: Entity<AppState>, window: &mut Window, cx: &mut
115 }),
121 }),
116 );
122 );
117 dialog
123 dialog
118 .title(TITLE)
124 .title(tr("calls.join_dialog.title"))
119 .w(px(DIALOG_WIDTH))
125 .w(px(DIALOG_WIDTH))
120 .child(form.clone())
126 .child(form.clone())
121 .footer(footer)
127 .footer(footer)
crates/app/src/views/new_meeting_dialog.rs +26 −14
@@ -14,6 +14,7 @@ use gpui_kit::*;
14 14
15 15 use super::new_chat::{NewChatDraft, Pick};
16 16 use super::widgets::icon;
17 use crate::i18n::tr;
17 18 use crate::app_state::AppState;
18 19 use crate::call::{FormValues, Invitee, default_window, draft_from_form};
19 20 use crate::theme;
@@ -21,7 +22,6 @@ use crate::theme;
21 22 const DIALOG_WIDTH: f32 = 520.;
22 23 const FIELD_GAP: f32 = 12.;
23 24 const LABEL_SIZE: f32 = 12.;
24 const TITLE: &str = "New meeting";
25 25 const DATE_FORMAT: &str = "%a, %b %-d, %Y";
26 26 const DETAILS_MIN_ROWS: usize = 3;
27 27 const DETAILS_MAX_ROWS: usize = 6;
@@ -45,7 +45,9 @@ struct MeetingForm {
45 45 impl MeetingForm {
46 46 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
47 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"));
48 let title = cx.new(|cx| {
49 InputState::new(window, cx).placeholder(tr("calls.meeting.title_placeholder"))
50 });
49 51 let people_state = state.clone();
50 52 let people = cx.new(|cx| NewChatDraft::new(people_state, window, cx).compact());
51 53 let date = cx.new(|cx| {
@@ -66,7 +68,7 @@ impl MeetingForm {
66 68 let details = cx.new(|cx| {
67 69 TextareaState::new(window, cx)
68 70 .auto_grow(DETAILS_MIN_ROWS, DETAILS_MAX_ROWS)
69 .placeholder("Add details")
71 .placeholder(tr("calls.meeting.details_placeholder"))
70 72 });
71 73 MeetingForm {
72 74 state,
@@ -181,9 +183,9 @@ impl Render for MeetingForm {
181 183 v_flex()
182 184 .debug_selector(|| "new-meeting".into())
183 185 .gap(px(FIELD_GAP))
184 .child(labeled("Title", Input::new(&self.title)))
186 .child(labeled(&tr("calls.meeting.title_label"), Input::new(&self.title)))
185 187 .child(labeled(
186 "People",
188 &tr("calls.meeting.people"),
187 189 div()
188 190 .debug_selector(|| "new-meeting/people".into())
189 191 .rounded(px(6.))
@@ -197,22 +199,28 @@ impl Render for MeetingForm {
197 199 .gap(px(8.))
198 200 .items_end()
199 201 .child(div().w(px(DATE_FIELD_WIDTH)).child(labeled(
200 "Date",
202 &tr("calls.meeting.date"),
201 203 DatePicker::new(&self.date).cleanable(false),
202 204 )))
203 205 .child(
204 206 div()
205 207 .w(px(TIME_FIELD_WIDTH))
206 .child(labeled("Start", TimeField::new(&self.start))),
208 .child(labeled(
209 &tr("calls.meeting.start"),
210 TimeField::new(&self.start),
211 )),
207 212 )
208 213 .child(
209 214 div()
210 215 .w(px(TIME_FIELD_WIDTH))
211 .child(labeled("End", TimeField::new(&self.end))),
216 .child(labeled(&tr("calls.meeting.end"), TimeField::new(&self.end))),
212 217 ),
213 218 )
214 .child(labeled("Repeat", repeat_button))
215 .child(labeled("Details", Textarea::new(&self.details)))
219 .child(labeled(&tr("calls.meeting.repeat"), repeat_button))
220 .child(labeled(
221 &tr("calls.meeting.details"),
222 Textarea::new(&self.details),
223 ))
216 224 .child(
217 225 h_flex()
218 226 .gap(px(6.))
@@ -220,7 +228,7 @@ impl Render for MeetingForm {
220 228 .text_size(px(LABEL_SIZE))
221 229 .text_color(theme::text_muted())
222 230 .child(icon(IconName::Video, 14., theme::text_muted()))
223 .child("Teams meeting link is added"),
231 .child(tr("calls.meeting.teams_link_added")),
224 232 )
225 233 .when_some(self.error.clone(), |form, error| {
226 234 form.child(
@@ -255,19 +263,23 @@ pub fn open_new_meeting_with(
255 263 let footer = DialogFooter::new()
256 264 .child(
257 265 Button::new("meeting-cancel")
258 .label("Cancel")
266 .label(tr("common.cancel"))
259 267 .on_click(|_, window, cx| window.close_dialog(cx)),
260 268 )
261 269 .child(
262 270 Button::new("meeting-send")
263 271 .primary()
264 .label(if sending { "Sending..." } else { "Send" })
272 .label(if sending {
273 tr("common.sending")
274 } else {
275 tr("common.send")
276 })
265 277 .on_click(move |_, window, cx| {
266 278 submit_form.update(cx, |form, cx| form.submit(window, cx));
267 279 }),
268 280 );
269 281 dialog
270 .title(TITLE)
282 .title(tr("calls.meeting.new_title"))
271 283 .w(px(DIALOG_WIDTH))
272 284 .child(form.clone())
273 285 .footer(footer)
@@ -14,6 +14,7 @@ use gpui_kit::*;
14
14
15use super::new_chat::{NewChatDraft, Pick};
15use super::new_chat::{NewChatDraft, Pick};
16use super::widgets::icon;
16use super::widgets::icon;
17use crate::i18n::tr;
17use crate::app_state::AppState;
18use crate::app_state::AppState;
18use crate::call::{FormValues, Invitee, default_window, draft_from_form};
19use crate::call::{FormValues, Invitee, default_window, draft_from_form};
19use crate::theme;
20use crate::theme;
@@ -21,7 +22,6 @@ use crate::theme;
21const DIALOG_WIDTH: f32 = 520.;
22const DIALOG_WIDTH: f32 = 520.;
22const FIELD_GAP: f32 = 12.;
23const FIELD_GAP: f32 = 12.;
23const LABEL_SIZE: f32 = 12.;
24const LABEL_SIZE: f32 = 12.;
24const TITLE: &str = "New meeting";
25const DATE_FORMAT: &str = "%a, %b %-d, %Y";
25const DATE_FORMAT: &str = "%a, %b %-d, %Y";
26const DETAILS_MIN_ROWS: usize = 3;
26const DETAILS_MIN_ROWS: usize = 3;
27const DETAILS_MAX_ROWS: usize = 6;
27const DETAILS_MAX_ROWS: usize = 6;
@@ -45,7 +45,9 @@ struct MeetingForm {
45impl MeetingForm {
45impl MeetingForm {
46 fn new(state: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
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);
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"));
48 let title = cx.new(|cx| {
49 InputState::new(window, cx).placeholder(tr("calls.meeting.title_placeholder"))
50 });
49 let people_state = state.clone();
51 let people_state = state.clone();
50 let people = cx.new(|cx| NewChatDraft::new(people_state, window, cx).compact());
52 let people = cx.new(|cx| NewChatDraft::new(people_state, window, cx).compact());
51 let date = cx.new(|cx| {
53 let date = cx.new(|cx| {
@@ -66,7 +68,7 @@ impl MeetingForm {
66 let details = cx.new(|cx| {
68 let details = cx.new(|cx| {
67 TextareaState::new(window, cx)
69 TextareaState::new(window, cx)
68 .auto_grow(DETAILS_MIN_ROWS, DETAILS_MAX_ROWS)
70 .auto_grow(DETAILS_MIN_ROWS, DETAILS_MAX_ROWS)
69 .placeholder("Add details")
71 .placeholder(tr("calls.meeting.details_placeholder"))
70 });
72 });
71 MeetingForm {
73 MeetingForm {
72 state,
74 state,
@@ -181,9 +183,9 @@ impl Render for MeetingForm {
181 v_flex()
183 v_flex()
182 .debug_selector(|| "new-meeting".into())
184 .debug_selector(|| "new-meeting".into())
183 .gap(px(FIELD_GAP))
185 .gap(px(FIELD_GAP))
184 .child(labeled("Title", Input::new(&self.title)))
186 .child(labeled(&tr("calls.meeting.title_label"), Input::new(&self.title)))
185 .child(labeled(
187 .child(labeled(
186 "People",
188 &tr("calls.meeting.people"),
187 div()
189 div()
188 .debug_selector(|| "new-meeting/people".into())
190 .debug_selector(|| "new-meeting/people".into())
189 .rounded(px(6.))
191 .rounded(px(6.))
@@ -197,22 +199,28 @@ impl Render for MeetingForm {
197 .gap(px(8.))
199 .gap(px(8.))
198 .items_end()
200 .items_end()
199 .child(div().w(px(DATE_FIELD_WIDTH)).child(labeled(
201 .child(div().w(px(DATE_FIELD_WIDTH)).child(labeled(
200 "Date",
202 &tr("calls.meeting.date"),
201 DatePicker::new(&self.date).cleanable(false),
203 DatePicker::new(&self.date).cleanable(false),
202 )))
204 )))
203 .child(
205 .child(
204 div()
206 div()
205 .w(px(TIME_FIELD_WIDTH))
207 .w(px(TIME_FIELD_WIDTH))
206 .child(labeled("Start", TimeField::new(&self.start))),
208 .child(labeled(
209 &tr("calls.meeting.start"),
210 TimeField::new(&self.start),
211 )),
207 )
212 )
208 .child(
213 .child(
209 div()
214 div()
210 .w(px(TIME_FIELD_WIDTH))
215 .w(px(TIME_FIELD_WIDTH))
211 .child(labeled("End", TimeField::new(&self.end))),
216 .child(labeled(&tr("calls.meeting.end"), TimeField::new(&self.end))),
212 ),
217 ),
213 )
218 )
214 .child(labeled("Repeat", repeat_button))
219 .child(labeled(&tr("calls.meeting.repeat"), repeat_button))
215 .child(labeled("Details", Textarea::new(&self.details)))
220 .child(labeled(
221 &tr("calls.meeting.details"),
222 Textarea::new(&self.details),
223 ))
216 .child(
224 .child(
217 h_flex()
225 h_flex()
218 .gap(px(6.))
226 .gap(px(6.))
@@ -220,7 +228,7 @@ impl Render for MeetingForm {
220 .text_size(px(LABEL_SIZE))
228 .text_size(px(LABEL_SIZE))
221 .text_color(theme::text_muted())
229 .text_color(theme::text_muted())
222 .child(icon(IconName::Video, 14., theme::text_muted()))
230 .child(icon(IconName::Video, 14., theme::text_muted()))
223 .child("Teams meeting link is added"),
231 .child(tr("calls.meeting.teams_link_added")),
224 )
232 )
225 .when_some(self.error.clone(), |form, error| {
233 .when_some(self.error.clone(), |form, error| {
226 form.child(
234 form.child(
@@ -255,19 +263,23 @@ pub fn open_new_meeting_with(
255 let footer = DialogFooter::new()
263 let footer = DialogFooter::new()
256 .child(
264 .child(
257 Button::new("meeting-cancel")
265 Button::new("meeting-cancel")
258 .label("Cancel")
266 .label(tr("common.cancel"))
259 .on_click(|_, window, cx| window.close_dialog(cx)),
267 .on_click(|_, window, cx| window.close_dialog(cx)),
260 )
268 )
261 .child(
269 .child(
262 Button::new("meeting-send")
270 Button::new("meeting-send")
263 .primary()
271 .primary()
264 .label(if sending { "Sending..." } else { "Send" })
272 .label(if sending {
273 tr("common.sending")
274 } else {
275 tr("common.send")
276 })
265 .on_click(move |_, window, cx| {
277 .on_click(move |_, window, cx| {
266 submit_form.update(cx, |form, cx| form.submit(window, cx));
278 submit_form.update(cx, |form, cx| form.submit(window, cx));
267 }),
279 }),
268 );
280 );
269 dialog
281 dialog
270 .title(TITLE)
282 .title(tr("calls.meeting.new_title"))
271 .w(px(DIALOG_WIDTH))
283 .w(px(DIALOG_WIDTH))
272 .child(form.clone())
284 .child(form.clone())
273 .footer(footer)
285 .footer(footer)
crates/app/src/views/prejoin_view.rs +19 −15
@@ -14,6 +14,7 @@ use gpui_kit::*;
14 14 use super::avatar::person_avatar;
15 15 use super::call_extras::{CameraMenu, background_items};
16 16 use super::call_view::{device_items, round_control};
17 use crate::i18n::{tr, tr_args};
17 18 use crate::app_state::AppState;
18 19 use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
19 20 use crate::theme;
@@ -28,8 +29,6 @@ const PANE_PADDING: f32 = 12.;
28 29 const PREVIEW_MIN_HEIGHT: f32 = 60.;
29 30 const FRAME_TICK: Duration = Duration::from_millis(100);
30 31 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 32 const DEMO_MICROPHONES: [&str; 2] = ["Headset microphone", "Laptop microphone"];
34 33 const DEMO_SPEAKERS: [&str; 2] = ["Headset earphones", "Laptop speakers"];
35 34
@@ -52,7 +51,7 @@ pub struct PrejoinView {
52 51
53 52 struct DeviceSelect {
54 53 id: &'static str,
55 label: &'static str,
54 label: String,
56 55 entries: Vec<DeviceEntry>,
57 56 current: DeviceChoice,
58 57 enabled: bool,
@@ -82,7 +81,7 @@ fn label_of(entries: &[DeviceEntry], choice: &DeviceChoice) -> String {
82 81 entries
83 82 .iter()
84 83 .find(|entry| &entry.choice == choice)
85 .map_or_else(|| DEFAULT_LABEL.to_owned(), |entry| entry.label.clone())
84 .map_or_else(|| tr("calls.prejoin.default_device"), |entry| entry.label.clone())
86 85 }
87 86
88 87 impl PrejoinView {
@@ -270,8 +269,12 @@ impl PrejoinView {
270 269
271 270 fn preview_status(&self) -> String {
272 271 match self.preview.failure() {
273 Some(reason) => format!("Camera could not start: {reason}"),
274 None => "Starting camera...".to_owned(),
272 Some(reason) => {
273 let mut args = std::collections::HashMap::new();
274 args.insert("detail".to_owned(), reason.clone());
275 tr_args("calls.prejoin.camera_failed", &args)
276 }
277 None => tr("calls.prejoin.starting_camera"),
275 278 }
276 279 }
277 280
@@ -295,14 +298,15 @@ impl PrejoinView {
295 298 .child(person_avatar(
296 299 &state.directory,
297 300 me.as_ref().map(|me| me.user_id.as_str()),
298 me.as_ref().map_or("You", |me| me.display_name.as_str()),
301 me.as_ref()
302 .map_or(tr("common.you").as_str(), |me| me.display_name.as_str()),
299 303 AVATAR_SIZE,
300 304 ))
301 305 .child(
302 306 div()
303 307 .text_size(px(13.))
304 308 .text_color(theme::text_muted())
305 .child(CAMERA_OFF_TEXT),
309 .child(tr("calls.prejoin.camera_off")),
306 310 )
307 311 .into_any_element(),
308 312 };
@@ -362,7 +366,7 @@ impl PrejoinView {
362 366 .child(
363 367 Button::new("prejoin-background")
364 368 .outline()
365 .label("Background")
369 .label(tr("calls.prejoin.background"))
366 370 .icon(IconName::ChevronDown)
367 371 .dropdown_menu(move |menu: PopupMenu, _, _| {
368 372 background_items(menu, &background_app, &backgrounds)
@@ -473,7 +477,7 @@ impl Render for PrejoinView {
473 477 .child(self.select(
474 478 DeviceSelect {
475 479 id: "prejoin-camera-select",
476 label: "Camera",
480 label: tr("calls.prejoin.camera"),
477 481 entries: cameras,
478 482 current: camera,
479 483 enabled: true,
@@ -484,7 +488,7 @@ impl Render for PrejoinView {
484 488 .child(self.select(
485 489 DeviceSelect {
486 490 id: "prejoin-mic-select",
487 label: "Microphone",
491 label: tr("calls.prejoin.microphone"),
488 492 entries: inputs,
489 493 current: input,
490 494 enabled: audio_on,
@@ -495,7 +499,7 @@ impl Render for PrejoinView {
495 499 .child(self.select(
496 500 DeviceSelect {
497 501 id: "prejoin-speaker-select",
498 label: "Speaker",
502 label: tr("calls.prejoin.speaker"),
499 503 entries: outputs,
500 504 current: output,
501 505 enabled: audio_on,
@@ -520,13 +524,13 @@ impl Render for PrejoinView {
520 524 .child(
521 525 Button::new("prejoin-cancel")
522 526 .ghost()
523 .label("Cancel")
527 .label(tr("common.cancel"))
524 528 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
525 529 )
526 530 .child(
527 531 Button::new("prejoin-join")
528 532 .primary()
529 .label("Join now")
533 .label(tr("calls.prejoin.join_now"))
530 534 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
531 535 );
532 536 v_flex()
@@ -563,7 +567,7 @@ impl Render for PrejoinView {
563 567 .truncate()
564 568 .text_size(px(13.))
565 569 .text_color(theme::text_muted())
566 .child("Choose your video and audio settings, then join"),
570 .child(tr("calls.prejoin.choose_av")),
567 571 ),
568 572 )
569 573 .child(self.preview_box(cx))
@@ -14,6 +14,7 @@ use gpui_kit::*;
14use super::avatar::person_avatar;
14use super::avatar::person_avatar;
15use super::call_extras::{CameraMenu, background_items};
15use super::call_extras::{CameraMenu, background_items};
16use super::call_view::{device_items, round_control};
16use super::call_view::{device_items, round_control};
17use crate::i18n::{tr, tr_args};
17use crate::app_state::AppState;
18use crate::app_state::AppState;
18use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
19use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
19use crate::theme;
20use crate::theme;
@@ -28,8 +29,6 @@ const PANE_PADDING: f32 = 12.;
28const PREVIEW_MIN_HEIGHT: f32 = 60.;
29const PREVIEW_MIN_HEIGHT: f32 = 60.;
29const FRAME_TICK: Duration = Duration::from_millis(100);
30const FRAME_TICK: Duration = Duration::from_millis(100);
30const FPS_TICK: Duration = Duration::from_millis(500);
31const 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"];
32const DEMO_MICROPHONES: [&str; 2] = ["Headset microphone", "Laptop microphone"];
34const DEMO_SPEAKERS: [&str; 2] = ["Headset earphones", "Laptop speakers"];
33const DEMO_SPEAKERS: [&str; 2] = ["Headset earphones", "Laptop speakers"];
35
34
@@ -52,7 +51,7 @@ pub struct PrejoinView {
52
51
53struct DeviceSelect {
52struct DeviceSelect {
54 id: &'static str,
53 id: &'static str,
55 label: &'static str,
54 label: String,
56 entries: Vec<DeviceEntry>,
55 entries: Vec<DeviceEntry>,
57 current: DeviceChoice,
56 current: DeviceChoice,
58 enabled: bool,
57 enabled: bool,
@@ -82,7 +81,7 @@ fn label_of(entries: &[DeviceEntry], choice: &DeviceChoice) -> String {
82 entries
81 entries
83 .iter()
82 .iter()
84 .find(|entry| &entry.choice == choice)
83 .find(|entry| &entry.choice == choice)
85 .map_or_else(|| DEFAULT_LABEL.to_owned(), |entry| entry.label.clone())
84 .map_or_else(|| tr("calls.prejoin.default_device"), |entry| entry.label.clone())
86}
85}
87
86
88impl PrejoinView {
87impl PrejoinView {
@@ -270,8 +269,12 @@ impl PrejoinView {
270
269
271 fn preview_status(&self) -> String {
270 fn preview_status(&self) -> String {
272 match self.preview.failure() {
271 match self.preview.failure() {
273 Some(reason) => format!("Camera could not start: {reason}"),
272 Some(reason) => {
274 None => "Starting camera...".to_owned(),
273 let mut args = std::collections::HashMap::new();
274 args.insert("detail".to_owned(), reason.clone());
275 tr_args("calls.prejoin.camera_failed", &args)
276 }
277 None => tr("calls.prejoin.starting_camera"),
275 }
278 }
276 }
279 }
277
280
@@ -295,14 +298,15 @@ impl PrejoinView {
295 .child(person_avatar(
298 .child(person_avatar(
296 &state.directory,
299 &state.directory,
297 me.as_ref().map(|me| me.user_id.as_str()),
300 me.as_ref().map(|me| me.user_id.as_str()),
298 me.as_ref().map_or("You", |me| me.display_name.as_str()),
301 me.as_ref()
302 .map_or(tr("common.you").as_str(), |me| me.display_name.as_str()),
299 AVATAR_SIZE,
303 AVATAR_SIZE,
300 ))
304 ))
301 .child(
305 .child(
302 div()
306 div()
303 .text_size(px(13.))
307 .text_size(px(13.))
304 .text_color(theme::text_muted())
308 .text_color(theme::text_muted())
305 .child(CAMERA_OFF_TEXT),
309 .child(tr("calls.prejoin.camera_off")),
306 )
310 )
307 .into_any_element(),
311 .into_any_element(),
308 };
312 };
@@ -362,7 +366,7 @@ impl PrejoinView {
362 .child(
366 .child(
363 Button::new("prejoin-background")
367 Button::new("prejoin-background")
364 .outline()
368 .outline()
365 .label("Background")
369 .label(tr("calls.prejoin.background"))
366 .icon(IconName::ChevronDown)
370 .icon(IconName::ChevronDown)
367 .dropdown_menu(move |menu: PopupMenu, _, _| {
371 .dropdown_menu(move |menu: PopupMenu, _, _| {
368 background_items(menu, &background_app, &backgrounds)
372 background_items(menu, &background_app, &backgrounds)
@@ -473,7 +477,7 @@ impl Render for PrejoinView {
473 .child(self.select(
477 .child(self.select(
474 DeviceSelect {
478 DeviceSelect {
475 id: "prejoin-camera-select",
479 id: "prejoin-camera-select",
476 label: "Camera",
480 label: tr("calls.prejoin.camera"),
477 entries: cameras,
481 entries: cameras,
478 current: camera,
482 current: camera,
479 enabled: true,
483 enabled: true,
@@ -484,7 +488,7 @@ impl Render for PrejoinView {
484 .child(self.select(
488 .child(self.select(
485 DeviceSelect {
489 DeviceSelect {
486 id: "prejoin-mic-select",
490 id: "prejoin-mic-select",
487 label: "Microphone",
491 label: tr("calls.prejoin.microphone"),
488 entries: inputs,
492 entries: inputs,
489 current: input,
493 current: input,
490 enabled: audio_on,
494 enabled: audio_on,
@@ -495,7 +499,7 @@ impl Render for PrejoinView {
495 .child(self.select(
499 .child(self.select(
496 DeviceSelect {
500 DeviceSelect {
497 id: "prejoin-speaker-select",
501 id: "prejoin-speaker-select",
498 label: "Speaker",
502 label: tr("calls.prejoin.speaker"),
499 entries: outputs,
503 entries: outputs,
500 current: output,
504 current: output,
501 enabled: audio_on,
505 enabled: audio_on,
@@ -520,13 +524,13 @@ impl Render for PrejoinView {
520 .child(
524 .child(
521 Button::new("prejoin-cancel")
525 Button::new("prejoin-cancel")
522 .ghost()
526 .ghost()
523 .label("Cancel")
527 .label(tr("common.cancel"))
524 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
528 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
525 )
529 )
526 .child(
530 .child(
527 Button::new("prejoin-join")
531 Button::new("prejoin-join")
528 .primary()
532 .primary()
529 .label("Join now")
533 .label(tr("calls.prejoin.join_now"))
530 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
534 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
531 );
535 );
532 v_flex()
536 v_flex()
@@ -563,7 +567,7 @@ impl Render for PrejoinView {
563 .truncate()
567 .truncate()
564 .text_size(px(13.))
568 .text_size(px(13.))
565 .text_color(theme::text_muted())
569 .text_color(theme::text_muted())
566 .child("Choose your video and audio settings, then join"),
570 .child(tr("calls.prejoin.choose_av")),
567 ),
571 ),
568 )
572 )
569 .child(self.preview_box(cx))
573 .child(self.preview_box(cx))
crates/app/src/views/rail.rs +19 −11
@@ -9,6 +9,7 @@ use super::widgets::{RAIL_BADGE, badge_pill, filled_icon, icon};
9 9 use crate::activity::ActivityCenter;
10 10 use crate::agents::{AgentRuns, runs_handle};
11 11 use crate::app_state::AppState;
12 use crate::i18n::tr;
12 13 use crate::sidebar_model::{any_unread_channel, unread_chat_count};
13 14 use crate::theme;
14 15 use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};
@@ -25,10 +26,10 @@ enum RailBadge {
25 26 Dot,
26 27 }
27 28
28 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 #[derive(Debug, Clone, PartialEq, Eq)]
29 30 struct RailItem {
30 31 tab: SidebarTab,
31 label: &'static str,
32 label: String,
32 33 shortcut_label: &'static str,
33 34 icon: IconName,
34 35 badge: RailBadge,
@@ -50,21 +51,21 @@ fn rail_items(
50 51 let mut items = vec![
51 52 RailItem {
52 53 tab: SidebarTab::Activity,
53 label: "Activity",
54 label: tr("rail.activity"),
54 55 shortcut_label: "Open Activity",
55 56 icon: IconName::Bell,
56 57 badge: count_badge_for(activity_unread),
57 58 },
58 59 RailItem {
59 60 tab: SidebarTab::Chats,
60 label: "Chat",
61 label: tr("rail.chat"),
61 62 shortcut_label: "Show Chats",
62 63 icon: IconName::MessageSquare,
63 64 badge: count_badge_for(unread_chats),
64 65 },
65 66 RailItem {
66 67 tab: SidebarTab::Channels,
67 label: "Teams",
68 label: tr("rail.teams"),
68 69 shortcut_label: "Show Channels",
69 70 icon: IconName::Users,
70 71 badge: if channel_dot {
@@ -75,14 +76,14 @@ fn rail_items(
75 76 },
76 77 RailItem {
77 78 tab: SidebarTab::Calendar,
78 label: "Calendar",
79 label: tr("rail.calendar"),
79 80 shortcut_label: "Open Calendar",
80 81 icon: IconName::Calendar,
81 82 badge: RailBadge::None,
82 83 },
83 84 RailItem {
84 85 tab: SidebarTab::Calls,
85 label: "Calls",
86 label: tr("rail.calls"),
86 87 shortcut_label: "Show Calls",
87 88 icon: IconName::Phone,
88 89 badge: RailBadge::None,
@@ -91,7 +92,7 @@ fn rail_items(
91 92 if let Some(running) = agents_running {
92 93 items.push(RailItem {
93 94 tab: SidebarTab::Agents,
94 label: "Agents",
95 label: tr("rail.agents"),
95 96 shortcut_label: "Open Agents",
96 97 icon: IconName::Bot,
97 98 badge: count_badge_for(running),
@@ -103,7 +104,7 @@ fn rail_items(
103 104 fn tooltip_text(item: &RailItem) -> SharedString {
104 105 match keys_for_label(item.shortcut_label) {
105 106 Some(keys) => format!("{} ({keys})", item.label).into(),
106 None => item.label.into(),
107 None => item.label.clone().into(),
107 108 }
108 109 }
109 110
@@ -150,7 +151,7 @@ fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
150 151 .line_height(px(LABEL_HEIGHT))
151 152 .font_weight(FontWeight::SEMIBOLD)
152 153 .text_color(color)
153 .child(item.label),
154 .child(item.label.clone()),
154 155 )
155 156 .children(badge(item.badge))
156 157 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
@@ -252,11 +253,15 @@ impl Render for RailView {
252 253
253 254 #[cfg(test)]
254 255 mod tests {
256 use app_base::ui_locale::apply_locale;
257
255 258 use super::{RailBadge, count_badge_for, rail_items, tooltip_text};
259 use crate::i18n::tr;
256 260 use crate::views::sidebar::SidebarTab;
257 261
258 262 #[test]
259 263 fn items_follow_the_spec_order() {
264 apply_locale("en");
260 265 let tabs: Vec<SidebarTab> = rail_items(0, 0, false, None)
261 266 .iter()
262 267 .map(|item| item.tab)
@@ -275,17 +280,19 @@ mod tests {
275 280
276 281 #[test]
277 282 fn agents_comes_last_and_only_when_actions_exist() {
283 apply_locale("en");
278 284 assert_eq!(rail_items(0, 0, false, None).len(), 5);
279 285 let with_agents = rail_items(0, 0, false, Some(2));
280 286 assert_eq!(with_agents.len(), 6);
281 287 assert_eq!(with_agents[5].tab, SidebarTab::Agents);
282 assert_eq!(with_agents[5].label, "Agents");
288 assert_eq!(with_agents[5].label, tr("rail.agents"));
283 289 assert_eq!(with_agents[5].badge, RailBadge::Count(2));
284 290 assert_eq!(rail_items(0, 0, false, Some(0))[5].badge, RailBadge::None);
285 291 }
286 292
287 293 #[test]
288 294 fn badges_follow_the_unread_inputs() {
295 apply_locale("en");
289 296 let items = rail_items(3, 5, true, None);
290 297 assert_eq!(items[0].badge, RailBadge::Count(3));
291 298 assert_eq!(items[1].badge, RailBadge::Count(5));
@@ -300,6 +307,7 @@ mod tests {
300 307 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
301 308 #[test]
302 309 fn every_item_shows_its_shortcut_in_the_tooltip() {
310 apply_locale("en");
303 311 let items = rail_items(0, 0, false, None);
304 312 assert_eq!(tooltip_text(&items[0]), "Activity (Ctrl+1)");
305 313 assert!(items.iter().all(|item| tooltip_text(item).ends_with(')')));
@@ -9,6 +9,7 @@ use super::widgets::{RAIL_BADGE, badge_pill, filled_icon, icon};
9use crate::activity::ActivityCenter;
9use crate::activity::ActivityCenter;
10use crate::agents::{AgentRuns, runs_handle};
10use crate::agents::{AgentRuns, runs_handle};
11use crate::app_state::AppState;
11use crate::app_state::AppState;
12use crate::i18n::tr;
12use crate::sidebar_model::{any_unread_channel, unread_chat_count};
13use crate::sidebar_model::{any_unread_channel, unread_chat_count};
13use crate::theme;
14use crate::theme;
14use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};
15use app_ui_kit::layout::{RAIL_ITEM_WIDTH, RAIL_WIDTH};
@@ -25,10 +26,10 @@ enum RailBadge {
25 Dot,
26 Dot,
26}
27}
27
28
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29#[derive(Debug, Clone, PartialEq, Eq)]
29struct RailItem {
30struct RailItem {
30 tab: SidebarTab,
31 tab: SidebarTab,
31 label: &'static str,
32 label: String,
32 shortcut_label: &'static str,
33 shortcut_label: &'static str,
33 icon: IconName,
34 icon: IconName,
34 badge: RailBadge,
35 badge: RailBadge,
@@ -50,21 +51,21 @@ fn rail_items(
50 let mut items = vec![
51 let mut items = vec![
51 RailItem {
52 RailItem {
52 tab: SidebarTab::Activity,
53 tab: SidebarTab::Activity,
53 label: "Activity",
54 label: tr("rail.activity"),
54 shortcut_label: "Open Activity",
55 shortcut_label: "Open Activity",
55 icon: IconName::Bell,
56 icon: IconName::Bell,
56 badge: count_badge_for(activity_unread),
57 badge: count_badge_for(activity_unread),
57 },
58 },
58 RailItem {
59 RailItem {
59 tab: SidebarTab::Chats,
60 tab: SidebarTab::Chats,
60 label: "Chat",
61 label: tr("rail.chat"),
61 shortcut_label: "Show Chats",
62 shortcut_label: "Show Chats",
62 icon: IconName::MessageSquare,
63 icon: IconName::MessageSquare,
63 badge: count_badge_for(unread_chats),
64 badge: count_badge_for(unread_chats),
64 },
65 },
65 RailItem {
66 RailItem {
66 tab: SidebarTab::Channels,
67 tab: SidebarTab::Channels,
67 label: "Teams",
68 label: tr("rail.teams"),
68 shortcut_label: "Show Channels",
69 shortcut_label: "Show Channels",
69 icon: IconName::Users,
70 icon: IconName::Users,
70 badge: if channel_dot {
71 badge: if channel_dot {
@@ -75,14 +76,14 @@ fn rail_items(
75 },
76 },
76 RailItem {
77 RailItem {
77 tab: SidebarTab::Calendar,
78 tab: SidebarTab::Calendar,
78 label: "Calendar",
79 label: tr("rail.calendar"),
79 shortcut_label: "Open Calendar",
80 shortcut_label: "Open Calendar",
80 icon: IconName::Calendar,
81 icon: IconName::Calendar,
81 badge: RailBadge::None,
82 badge: RailBadge::None,
82 },
83 },
83 RailItem {
84 RailItem {
84 tab: SidebarTab::Calls,
85 tab: SidebarTab::Calls,
85 label: "Calls",
86 label: tr("rail.calls"),
86 shortcut_label: "Show Calls",
87 shortcut_label: "Show Calls",
87 icon: IconName::Phone,
88 icon: IconName::Phone,
88 badge: RailBadge::None,
89 badge: RailBadge::None,
@@ -91,7 +92,7 @@ fn rail_items(
91 if let Some(running) = agents_running {
92 if let Some(running) = agents_running {
92 items.push(RailItem {
93 items.push(RailItem {
93 tab: SidebarTab::Agents,
94 tab: SidebarTab::Agents,
94 label: "Agents",
95 label: tr("rail.agents"),
95 shortcut_label: "Open Agents",
96 shortcut_label: "Open Agents",
96 icon: IconName::Bot,
97 icon: IconName::Bot,
97 badge: count_badge_for(running),
98 badge: count_badge_for(running),
@@ -103,7 +104,7 @@ fn rail_items(
103fn tooltip_text(item: &RailItem) -> SharedString {
104fn tooltip_text(item: &RailItem) -> SharedString {
104 match keys_for_label(item.shortcut_label) {
105 match keys_for_label(item.shortcut_label) {
105 Some(keys) => format!("{} ({keys})", item.label).into(),
106 Some(keys) => format!("{} ({keys})", item.label).into(),
106 None => item.label.into(),
107 None => item.label.clone().into(),
107 }
108 }
108}
109}
109
110
@@ -150,7 +151,7 @@ fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
150 .line_height(px(LABEL_HEIGHT))
151 .line_height(px(LABEL_HEIGHT))
151 .font_weight(FontWeight::SEMIBOLD)
152 .font_weight(FontWeight::SEMIBOLD)
152 .text_color(color)
153 .text_color(color)
153 .child(item.label),
154 .child(item.label.clone()),
154 )
155 )
155 .children(badge(item.badge))
156 .children(badge(item.badge))
156 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
157 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
@@ -252,11 +253,15 @@ impl Render for RailView {
252
253
253#[cfg(test)]
254#[cfg(test)]
254mod tests {
255mod tests {
256 use app_base::ui_locale::apply_locale;
257
255 use super::{RailBadge, count_badge_for, rail_items, tooltip_text};
258 use super::{RailBadge, count_badge_for, rail_items, tooltip_text};
259 use crate::i18n::tr;
256 use crate::views::sidebar::SidebarTab;
260 use crate::views::sidebar::SidebarTab;
257
261
258 #[test]
262 #[test]
259 fn items_follow_the_spec_order() {
263 fn items_follow_the_spec_order() {
264 apply_locale("en");
260 let tabs: Vec<SidebarTab> = rail_items(0, 0, false, None)
265 let tabs: Vec<SidebarTab> = rail_items(0, 0, false, None)
261 .iter()
266 .iter()
262 .map(|item| item.tab)
267 .map(|item| item.tab)
@@ -275,17 +280,19 @@ mod tests {
275
280
276 #[test]
281 #[test]
277 fn agents_comes_last_and_only_when_actions_exist() {
282 fn agents_comes_last_and_only_when_actions_exist() {
283 apply_locale("en");
278 assert_eq!(rail_items(0, 0, false, None).len(), 5);
284 assert_eq!(rail_items(0, 0, false, None).len(), 5);
279 let with_agents = rail_items(0, 0, false, Some(2));
285 let with_agents = rail_items(0, 0, false, Some(2));
280 assert_eq!(with_agents.len(), 6);
286 assert_eq!(with_agents.len(), 6);
281 assert_eq!(with_agents[5].tab, SidebarTab::Agents);
287 assert_eq!(with_agents[5].tab, SidebarTab::Agents);
282 assert_eq!(with_agents[5].label, "Agents");
288 assert_eq!(with_agents[5].label, tr("rail.agents"));
283 assert_eq!(with_agents[5].badge, RailBadge::Count(2));
289 assert_eq!(with_agents[5].badge, RailBadge::Count(2));
284 assert_eq!(rail_items(0, 0, false, Some(0))[5].badge, RailBadge::None);
290 assert_eq!(rail_items(0, 0, false, Some(0))[5].badge, RailBadge::None);
285 }
291 }
286
292
287 #[test]
293 #[test]
288 fn badges_follow_the_unread_inputs() {
294 fn badges_follow_the_unread_inputs() {
295 apply_locale("en");
289 let items = rail_items(3, 5, true, None);
296 let items = rail_items(3, 5, true, None);
290 assert_eq!(items[0].badge, RailBadge::Count(3));
297 assert_eq!(items[0].badge, RailBadge::Count(3));
291 assert_eq!(items[1].badge, RailBadge::Count(5));
298 assert_eq!(items[1].badge, RailBadge::Count(5));
@@ -300,6 +307,7 @@ mod tests {
300 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
307 #[cfg_attr(target_os = "macos", ignore = "needs Ctrl bindings")]
301 #[test]
308 #[test]
302 fn every_item_shows_its_shortcut_in_the_tooltip() {
309 fn every_item_shows_its_shortcut_in_the_tooltip() {
310 apply_locale("en");
303 let items = rail_items(0, 0, false, None);
311 let items = rail_items(0, 0, false, None);
304 assert_eq!(tooltip_text(&items[0]), "Activity (Ctrl+1)");
312 assert_eq!(tooltip_text(&items[0]), "Activity (Ctrl+1)");
305 assert!(items.iter().all(|item| tooltip_text(item).ends_with(')')));
313 assert!(items.iter().all(|item| tooltip_text(item).ends_with(')')));
crates/app/src/views/recap_tab.rs +2 −1
@@ -18,6 +18,7 @@ use gpui_kit::*;
18 18
19 19 use super::shared_tab::{SharedRun, download_label, item_row};
20 20 use super::widgets::icon;
21 use crate::i18n::tr;
21 22 use crate::channel_files::SharedItem;
22 23 use crate::downloads::DownloadState;
23 24 use crate::recap::{
@@ -275,7 +276,7 @@ fn failure(reason: String, run: &RecapRun) -> AnyElement {
275 276 Button::new("recap-retry")
276 277 .ghost()
277 278 .compact()
278 .label("Retry")
279 .label(tr("common.retry"))
279 280 .on_click(move |_, window, cx| run(RecapCommand::Retry, window, cx)),
280 281 )
281 282 .into_any_element()
@@ -18,6 +18,7 @@ use gpui_kit::*;
18
18
19use super::shared_tab::{SharedRun, download_label, item_row};
19use super::shared_tab::{SharedRun, download_label, item_row};
20use super::widgets::icon;
20use super::widgets::icon;
21use crate::i18n::tr;
21use crate::channel_files::SharedItem;
22use crate::channel_files::SharedItem;
22use crate::downloads::DownloadState;
23use crate::downloads::DownloadState;
23use crate::recap::{
24use crate::recap::{
@@ -275,7 +276,7 @@ fn failure(reason: String, run: &RecapRun) -> AnyElement {
275 Button::new("recap-retry")
276 Button::new("recap-retry")
276 .ghost()
277 .ghost()
277 .compact()
278 .compact()
278 .label("Retry")
279 .label(tr("common.retry"))
279 .on_click(move |_, window, cx| run(RecapCommand::Retry, window, cx)),
280 .on_click(move |_, window, cx| run(RecapCommand::Retry, window, cx)),
280 )
281 )
281 .into_any_element()
282 .into_any_element()
crates/app/src/views/section_dialog.rs +2 −1
@@ -4,6 +4,7 @@ use gpui_kit::component::input::{Input, InputEvent, InputState};
4 4 use gpui_kit::component::{WindowExt as _, v_flex};
5 5 use gpui_kit::*;
6 6
7 use crate::i18n::tr;
7 8 use crate::app_state::AppState;
8 9
9 10 const DIALOG_WIDTH: f32 = 380.;
@@ -114,7 +115,7 @@ pub fn open_section_name_dialog(
114 115 let footer = DialogFooter::new()
115 116 .child(
116 117 Button::new("section-name-cancel")
117 .label("Cancel")
118 .label(tr("common.cancel"))
118 119 .on_click(|_, window, cx| window.close_dialog(cx)),
119 120 )
120 121 .child(
@@ -4,6 +4,7 @@ use gpui_kit::component::input::{Input, InputEvent, InputState};
4use gpui_kit::component::{WindowExt as _, v_flex};
4use gpui_kit::component::{WindowExt as _, v_flex};
5use gpui_kit::*;
5use gpui_kit::*;
6
6
7use crate::i18n::tr;
7use crate::app_state::AppState;
8use crate::app_state::AppState;
8
9
9const DIALOG_WIDTH: f32 = 380.;
10const DIALOG_WIDTH: f32 = 380.;
@@ -114,7 +115,7 @@ pub fn open_section_name_dialog(
114 let footer = DialogFooter::new()
115 let footer = DialogFooter::new()
115 .child(
116 .child(
116 Button::new("section-name-cancel")
117 Button::new("section-name-cancel")
117 .label("Cancel")
118 .label(tr("common.cancel"))
118 .on_click(|_, window, cx| window.close_dialog(cx)),
119 .on_click(|_, window, cx| window.close_dialog(cx)),
119 )
120 )
120 .child(
121 .child(
crates/app/src/views/shared_tab.rs +2 −1
@@ -16,6 +16,7 @@ use teams_core::{DriveEntry, FileKind};
16 16
17 17 use super::attachments::file_badge;
18 18 use super::widgets::{icon, menu_icon};
19 use crate::i18n::tr;
19 20 use crate::channel_files::{
20 21 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
21 22 };
@@ -465,7 +466,7 @@ pub fn render_library(view: LibraryView, run: &SharedRun) -> AnyElement {
465 466 Button::new("library-retry")
466 467 .ghost()
467 468 .compact()
468 .label("Retry")
469 .label(tr("common.retry"))
469 470 .on_click(move |_, window, cx| retry(SharedCommand::Retry, window, cx)),
470 471 )
471 472 .into_any_element()
@@ -16,6 +16,7 @@ use teams_core::{DriveEntry, FileKind};
16
16
17use super::attachments::file_badge;
17use super::attachments::file_badge;
18use super::widgets::{icon, menu_icon};
18use super::widgets::{icon, menu_icon};
19use crate::i18n::tr;
19use crate::channel_files::{
20use crate::channel_files::{
20 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
21 LibraryPath, MessageFilter, SharedContent, SharedItem, grouped_items, size_label,
21};
22};
@@ -465,7 +466,7 @@ pub fn render_library(view: LibraryView, run: &SharedRun) -> AnyElement {
465 Button::new("library-retry")
466 Button::new("library-retry")
466 .ghost()
467 .ghost()
467 .compact()
468 .compact()
468 .label("Retry")
469 .label(tr("common.retry"))
469 .on_click(move |_, window, cx| retry(SharedCommand::Retry, window, cx)),
470 .on_click(move |_, window, cx| retry(SharedCommand::Retry, window, cx)),
470 )
471 )
471 .into_any_element()
472 .into_any_element()
crates/app/src/views/shortcuts.rs +7 −5
@@ -1,6 +1,8 @@
1 1 use gpui_kit::component::input::Enter;
2 2 use gpui_kit::*;
3 3
4 use crate::i18n::tr;
5
4 6 use super::actions::{
5 7 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLastMessage, EditLink, InsertTableLine, NewChat,
6 8 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold,
@@ -95,12 +97,12 @@ impl Group {
95 97 Group::Calls,
96 98 ];
97 99
98 pub fn title(self) -> &'static str {
100 pub fn title(self) -> String {
99 101 match self {
100 Group::General => "General",
101 Group::Navigation => "Navigation",
102 Group::Composer => "Messages and composer",
103 Group::Calls => "Calls",
102 Group::General => tr("shortcuts.group.general"),
103 Group::Navigation => tr("shortcuts.group.navigation"),
104 Group::Composer => tr("shortcuts.group.composer"),
105 Group::Calls => tr("shortcuts.group.calls"),
104 106 }
105 107 }
106 108 }
@@ -1,6 +1,8 @@
1use gpui_kit::component::input::Enter;
1use gpui_kit::component::input::Enter;
2use gpui_kit::*;
2use gpui_kit::*;
3
3
4use crate::i18n::tr;
5
4use super::actions::{
6use super::actions::{
5 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLastMessage, EditLink, InsertTableLine, NewChat,
7 COMPOSER_KEY_CONTEXT as COMPOSER_CONTEXT, EditLastMessage, EditLink, InsertTableLine, NewChat,
6 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold,
8 OpenSwitcher, PastePlainText, RemoveTableLine, ReplyToHovered, ScheduleSend, ToggleBold,
@@ -95,12 +97,12 @@ impl Group {
95 Group::Calls,
97 Group::Calls,
96 ];
98 ];
97
99
98 pub fn title(self) -> &'static str {
100 pub fn title(self) -> String {
99 match self {
101 match self {
100 Group::General => "General",
102 Group::General => tr("shortcuts.group.general"),
101 Group::Navigation => "Navigation",
103 Group::Navigation => tr("shortcuts.group.navigation"),
102 Group::Composer => "Messages and composer",
104 Group::Composer => tr("shortcuts.group.composer"),
103 Group::Calls => "Calls",
105 Group::Calls => tr("shortcuts.group.calls"),
104 }
106 }
105 }
107 }
106}
108}
crates/app/src/views/shortcuts_dialog.rs +2 −1
@@ -4,6 +4,7 @@ use gpui_kit::*;
4 4
5 5 use super::shortcuts::{Group, shortcuts_in};
6 6 use super::widgets::symbol;
7 use crate::i18n::tr;
7 8 use crate::theme::{self, ElevatedSurface as _};
8 9
9 10 const CARD_WIDTH: f32 = 520.;
@@ -50,7 +51,7 @@ impl ShortcutsDialog {
50 51 .flex_1()
51 52 .text_size(px(15.))
52 53 .font_weight(FontWeight::SEMIBOLD)
53 .child("Keyboard shortcuts"),
54 .child(tr("shortcuts.title")),
54 55 )
55 56 .child(
56 57 div()
@@ -4,6 +4,7 @@ use gpui_kit::*;
4
4
5use super::shortcuts::{Group, shortcuts_in};
5use super::shortcuts::{Group, shortcuts_in};
6use super::widgets::symbol;
6use super::widgets::symbol;
7use crate::i18n::tr;
7use crate::theme::{self, ElevatedSurface as _};
8use crate::theme::{self, ElevatedSurface as _};
8
9
9const CARD_WIDTH: f32 = 520.;
10const CARD_WIDTH: f32 = 520.;
@@ -50,7 +51,7 @@ impl ShortcutsDialog {
50 .flex_1()
51 .flex_1()
51 .text_size(px(15.))
52 .text_size(px(15.))
52 .font_weight(FontWeight::SEMIBOLD)
53 .font_weight(FontWeight::SEMIBOLD)
53 .child("Keyboard shortcuts"),
54 .child(tr("shortcuts.title")),
54 )
55 )
55 .child(
56 .child(
56 div()
57 div()
crates/app/src/views/sidebar.rs +95 −89
@@ -2,11 +2,11 @@ use std::cell::{Cell, RefCell};
2 2 use std::collections::{HashMap, HashSet};
3 3
4 4 use chrono::{Local, Offset, Utc};
5 use gpui_kit::component::scroll::ScrollableElement as _;
6 5 use gpui_kit::assets::IconName;
7 6 use gpui_kit::component::button::{Button, ButtonVariants as _};
8 7 use gpui_kit::component::dialog::DialogFooter;
9 8 use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
9 use gpui_kit::component::scroll::ScrollableElement as _;
10 10 use gpui_kit::component::{Icon, Sizable as _, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11 11 use gpui_kit::prelude::FluentBuilder as _;
12 12 use gpui_kit::*;
@@ -18,14 +18,15 @@ use teams_core::team_avatar_key;
18 18
19 19 use super::activity_panel::ActivityPanel;
20 20 use super::avatar::{spec_avatar, team_avatar, with_presence};
21 use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
22 use super::scroll_edge::{scroll_offset, with_top_edge};
23 21 use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
22 use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
24 23 use super::create_channel_dialog::open_create_channel_dialog;
24 use super::last_views::LastViews;
25 use super::scroll_edge::{scroll_offset, with_top_edge};
25 26 use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
26 27 use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
28 use crate::i18n::{tr, tr_args};
27 29 use crate::agents::AgentsPanel;
28 use super::last_views::LastViews;
29 30 use crate::app_state::{AppEvent, AppState, QuickView, Selection};
30 31 use crate::channel_menu::{
31 32 ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
@@ -61,7 +62,6 @@ const PINNED_CHANNEL_HEIGHT: f32 = 48.;
61 62 const SECTION_HEIGHT: f32 = 30.;
62 63 const SECTION_GAP: f32 = 4.;
63 64 const QUICK_VIEWS_SECTION_ID: &str = "quick-views";
64 const QUICK_VIEWS_TITLE: &str = "Quick views";
65 65 const QUICK_ROW_HEIGHT: f32 = 32.;
66 66 const QUICK_ICON_SIZE: f32 = 18.;
67 67 const QUICK_VIEWS: [(QuickView, &str); 3] = [
@@ -71,15 +71,9 @@ const QUICK_VIEWS: [(QuickView, &str); 3] = [
71 71 ];
72 72 const HINT_HEIGHT: f32 = 26.;
73 73 const SEE_MORE_HEIGHT: f32 = 28.;
74 const LOADING_OLDER_LABEL: &str = "Loading older chats";
75 74 const FALLBACK_VIEWPORT: f32 = 900.;
76 75 const VIEWPORT_MARGIN: f32 = 300.;
77 76 const AVATAR_SIZE: f32 = 36.;
78 const PINNED_LABEL: &str = "Pinned";
79 const TEAMS_LABEL: &str = "Teams";
80 const MARK_ALL_READ_LABEL: &str = "Mark all as read";
81 const COLLAPSE_ALL_LABEL: &str = "Collapse all sections";
82 const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
83 77 const TEAM_ROW_HEIGHT: f32 = 36.;
84 78 const CHANNEL_ROW_HEIGHT: f32 = 32.;
85 79 const TEAM_ICON_SIZE: f32 = 20.;
@@ -87,8 +81,6 @@ const TEAM_ICON_RADIUS: f32 = 4.;
87 81 const CHANNEL_INDENT: f32 = 60.;
88 82 pub const CHANNEL_ROW_TAG: &str = "sidebar/channel-row";
89 83 pub const SEE_ALL_CHANNELS_TAG: &str = "sidebar/see-all-channels";
90 const SEE_ALL_CHANNELS: &str = "See all channels";
91 const SEE_FEWER_CHANNELS: &str = "See fewer channels";
92 84 const PRIVATE_MEMBERSHIP: &str = "private";
93 85 const REVEAL_ROW_HEIGHT: f32 = 32.;
94 86 const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
@@ -107,14 +99,14 @@ pub enum SidebarTab {
107 99 }
108 100
109 101 impl SidebarTab {
110 fn title(self) -> &'static str {
102 fn title(self) -> String {
111 103 match self {
112 SidebarTab::Activity => "Activity",
113 SidebarTab::Chats => "Chat",
114 SidebarTab::Channels => "Teams",
115 SidebarTab::Calendar => "Calendar",
116 SidebarTab::Calls => "Calls",
117 SidebarTab::Agents => "Agents",
104 SidebarTab::Activity => tr("rail.activity"),
105 SidebarTab::Chats => tr("rail.chat"),
106 SidebarTab::Channels => tr("rail.teams"),
107 SidebarTab::Calendar => tr("rail.calendar"),
108 SidebarTab::Calls => tr("rail.calls"),
109 SidebarTab::Agents => tr("rail.agents"),
118 110 }
119 111 }
120 112 }
@@ -205,7 +197,7 @@ fn drop_target(section: &Section) -> Option<Option<String>> {
205 197
206 198 fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem {
207 199 let state = state.clone();
208 PopupMenuItem::new("New section")
200 PopupMenuItem::new(tr("sidebar.new_section"))
209 201 .icon(menu_icon(IconName::Plus))
210 202 .disabled(read_only)
211 203 .on_click(move |_, window, cx| {
@@ -215,7 +207,7 @@ fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem
215 207
216 208 fn move_section_item(
217 209 state: &Entity<AppState>,
218 label: &'static str,
210 label: String,
219 211 glyph: IconName,
220 212 folder_id: &str,
221 213 target_id: Option<&String>,
@@ -249,7 +241,7 @@ fn section_menu(
249 241 name: target.name.clone(),
250 242 };
251 243 popup = popup.item(
252 PopupMenuItem::new("Rename section")
244 PopupMenuItem::new(tr("sidebar.rename_section"))
253 245 .icon(menu_icon(IconName::Pencil))
254 246 .disabled(target.read_only)
255 247 .on_click(move |_, window, cx| {
@@ -266,7 +258,7 @@ fn section_menu(
266 258 popup = popup
267 259 .item(move_section_item(
268 260 state,
269 "Move up",
261 tr("sidebar.move_up"),
270 262 IconName::ArrowUp,
271 263 &target.id,
272 264 target.previous_id.as_ref(),
@@ -274,7 +266,7 @@ fn section_menu(
274 266 ))
275 267 .item(move_section_item(
276 268 state,
277 "Move down",
269 tr("sidebar.move_down"),
278 270 IconName::ArrowDown,
279 271 &target.id,
280 272 target.next_id.as_ref(),
@@ -288,7 +280,9 @@ fn section_menu(
288 280 let (folder_id, name) = (target.id.clone(), target.name.clone());
289 281 popup = popup.separator().item(
290 282 PopupMenuItem::element(|_, _| {
291 div().text_color(theme::red_soft()).child("Delete section")
283 div()
284 .text_color(theme::red_soft())
285 .child(tr("sidebar.delete_section"))
292 286 })
293 287 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
294 288 .disabled(target.read_only)
@@ -309,15 +303,17 @@ fn confirm_delete_section(
309 303 ) {
310 304 let state = state.clone();
311 305 let folder_id = folder_id.to_owned();
312 let heading = format!("Delete section \"{}\"?", truncated(name, TITLE_LIMIT));
306 let mut args = HashMap::new();
307 args.insert("name".to_owned(), truncated(name, TITLE_LIMIT));
308 let heading = tr_args("sidebar.delete_section_title", &args);
313 309 window.open_alert_dialog(cx, move |alert, _, _| {
314 310 let state = state.clone();
315 311 let folder_id = folder_id.clone();
316 312 let cancel = Button::new("delete-section-cancel")
317 .label("Cancel")
313 .label(tr("common.cancel"))
318 314 .on_click(|_, window, cx| window.close_dialog(cx));
319 315 let delete = Button::new("delete-section-confirm")
320 .label("Delete")
316 .label(tr("common.delete"))
321 317 .danger()
322 318 .on_click(move |_, window, cx| {
323 319 state.update(cx, |state, cx| state.delete_section(&folder_id, cx));
@@ -325,7 +321,7 @@ fn confirm_delete_section(
325 321 });
326 322 alert
327 323 .title(heading.clone())
328 .description("Chats in it move back to Chats.")
324 .description(tr("sidebar.delete_section_detail"))
329 325 .footer(DialogFooter::new().child(cancel).child(delete))
330 326 .on_ok(|_, _, _| false)
331 327 });
@@ -397,14 +393,14 @@ fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
397 393 div()
398 394 .flex_none()
399 395 .text_color(theme::accent_text())
400 .child("Draft:"),
396 .child(tr("sidebar.draft_prefix")),
401 397 )
402 398 .child(div().truncate().child(text.clone())),
403 399 LocalPreview::NotSent => row.child(
404 400 div()
405 401 .flex_none()
406 402 .text_color(theme::red_soft())
407 .child("Not sent"),
403 .child(tr("sidebar.not_sent")),
408 404 ),
409 405 }
410 406 }
@@ -559,15 +555,12 @@ impl SidebarView {
559 555 self.last_views.remember(current);
560 556 }
561 557 let first_chat_id = state.sidebar.chats.first().map(|chat| chat.id.as_str());
562 if let Some(selection) =
563 self.last_views
564 .restore(
565 tab,
566 state.selection.as_ref(),
567 first_chat_id,
568 first_channel_id.as_deref(),
569 )
570 {
558 if let Some(selection) = self.last_views.restore(
559 tab,
560 state.selection.as_ref(),
561 first_chat_id,
562 first_channel_id.as_deref(),
563 ) {
571 564 self.state
572 565 .update(cx, |state, cx| state.select(selection, cx));
573 566 }
@@ -604,7 +597,9 @@ impl SidebarView {
604 597
605 598 fn first_channel_id(&self, cx: &App) -> Option<String> {
606 599 let input = self.channel_order_input(self.state.read(cx), None);
607 visible_channel_ids(&input).first().map(|id| (*id).to_owned())
600 visible_channel_ids(&input)
601 .first()
602 .map(|id| (*id).to_owned())
608 603 }
609 604
610 605 fn channel_order_input<'a>(
@@ -659,7 +654,9 @@ impl SidebarView {
659 654 .cursor_pointer()
660 655 .when(active, |button| button.bg(theme::popup_hover()))
661 656 .hover(|button| button.bg(theme::popup_hover()))
662 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
657 .tooltip(|window, cx| {
658 Tooltip::new(tr("sidebar.new_chat_shortcut")).build(window, cx)
659 })
663 660 .child(icon(IconName::Pencil, 16., theme::text_soft()))
664 661 .on_click(cx.listener(|this, _, _, cx| {
665 662 this.state.update(cx, |state, cx| state.start_new_chat(cx));
@@ -675,12 +672,12 @@ impl SidebarView {
675 672 .ghost()
676 673 .size(px(NEW_CHAT_BUTTON_SIZE))
677 674 .rounded(px(8.))
678 .tooltip("More options")
675 .tooltip(tr("sidebar.more_options"))
679 676 .dropdown_menu(move |menu, _, _| {
680 677 let (read_state, collapse_state) = (state.clone(), state.clone());
681 678 let section_ids = section_ids.clone();
682 679 menu.item(
683 PopupMenuItem::new(MARK_ALL_READ_LABEL)
680 PopupMenuItem::new(tr("sidebar.mark_all_read"))
684 681 .icon(menu_icon(IconName::CheckCheck))
685 682 .disabled(read_only)
686 683 .on_click(move |_, _, cx| {
@@ -688,7 +685,7 @@ impl SidebarView {
688 685 }),
689 686 )
690 687 .item(
691 PopupMenuItem::new(COLLAPSE_ALL_LABEL)
688 PopupMenuItem::new(tr("sidebar.collapse_all"))
692 689 .icon(menu_icon(IconName::ChevronsDownUp))
693 690 .on_click(move |_, _, cx| {
694 691 let ids = section_ids.clone();
@@ -718,11 +715,11 @@ impl SidebarView {
718 715 .ghost()
719 716 .size(px(NEW_CHAT_BUTTON_SIZE))
720 717 .rounded(px(8.))
721 .tooltip("More options")
718 .tooltip(tr("sidebar.more_options"))
722 719 .dropdown_menu(move |menu, _, _| {
723 720 let (state, view, team_ids) = (state.clone(), view.clone(), team_ids.clone());
724 721 menu.item(
725 PopupMenuItem::new(MARK_ALL_READ_LABEL)
722 PopupMenuItem::new(tr("sidebar.mark_all_read"))
726 723 .icon(menu_icon(IconName::CheckCheck))
727 724 .disabled(read_only)
728 725 .on_click(move |_, _, cx| {
@@ -730,7 +727,7 @@ impl SidebarView {
730 727 }),
731 728 )
732 729 .item(
733 PopupMenuItem::new(COLLAPSE_ALL_LABEL)
730 PopupMenuItem::new(tr("sidebar.collapse_all"))
734 731 .icon(menu_icon(IconName::ChevronsDownUp))
735 732 .on_click(move |_, _, cx| {
736 733 let team_ids = team_ids.clone();
@@ -773,14 +770,14 @@ impl SidebarView {
773 770 .truncate()
774 771 .text_size(px(14.))
775 772 .text_color(theme::text())
776 .child("New chat"),
773 .child(tr("sidebar.new_chat")),
777 774 )
778 775 .child(
779 776 div()
780 777 .truncate()
781 778 .text_size(px(12.5))
782 779 .text_color(theme::text_muted())
783 .child("Draft"),
780 .child(tr("sidebar.draft")),
784 781 ),
785 782 )
786 783 }
@@ -885,7 +882,7 @@ impl SidebarView {
885 882 .text_size(px(12.))
886 883 .font_weight(FontWeight::SEMIBOLD)
887 884 .text_color(theme::text_soft())
888 .child(QUICK_VIEWS_TITLE),
885 .child(tr("sidebar.quick_views")),
889 886 )
890 887 .on_click(cx.listener(|this, _, _, cx| {
891 888 this.state.update(cx, |state, cx| {
@@ -896,7 +893,8 @@ impl SidebarView {
896 893 let mut height = SECTION_GAP + SECTION_HEIGHT;
897 894 if !collapsed {
898 895 for (view, glyph) in QUICK_VIEWS {
899 section = section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
896 section =
897 section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
900 898 height += QUICK_ROW_HEIGHT;
901 899 }
902 900 }
@@ -939,9 +937,11 @@ impl SidebarView {
939 937 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
940 938 let toggle_id = section.id.clone();
941 939 let label = if section.hidden_count > 0 {
942 format!("See more ({})", section.hidden_count)
940 let mut args = HashMap::new();
941 args.insert("count".to_owned(), section.hidden_count.to_string());
942 tr_args("sidebar.see_more", &args)
943 943 } else {
944 "See less".to_owned()
944 tr("sidebar.see_less")
945 945 };
946 946 div()
947 947 .id(SharedString::from(format!("see-more-{}", section.id)))
@@ -1076,7 +1076,6 @@ impl SidebarView {
1076 1076 );
1077 1077 let state = self.state.clone();
1078 1078 let chat_id = item.id.clone();
1079 let (warm_state, warm_chat_id) = (self.state.clone(), item.id.clone());
1080 1079 let dragged = DraggedChat {
1081 1080 id: item.id.clone(),
1082 1081 title: item.title.clone(),
@@ -1109,7 +1108,7 @@ impl SidebarView {
1109 1108 .ghost()
1110 1109 .xsmall()
1111 1110 .icon(IconName::Ellipsis)
1112 .tooltip("More options")
1111 .tooltip(tr("sidebar.more_options"))
1113 1112 .dropdown_menu(move |popup, window, cx| {
1114 1113 chat_menu(popup, window, cx, &more_context, &more_target)
1115 1114 }),
@@ -1145,11 +1144,6 @@ impl SidebarView {
1145 1144 .child(avatar)
1146 1145 .child(lines)
1147 1146 .child(more_button)
1148 .on_hover(move |hovered, _, cx| {
1149 if *hovered {
1150 warm_state.update(cx, |state, _| state.warm_chat(&warm_chat_id));
1151 }
1152 })
1153 1147 .on_click(move |_, _, cx| {
1154 1148 let selection = Selection::Chat(chat_id.clone());
1155 1149 state.update(cx, |state, cx| state.select(selection, cx));
@@ -1315,7 +1309,7 @@ impl SidebarView {
1315 1309 .text_size(px(12.5))
1316 1310 .italic()
1317 1311 .text_color(theme::text_faint())
1318 .child(LOADING_OLDER_LABEL),
1312 .child(tr("sidebar.loading_older")),
1319 1313 );
1320 1314 }
1321 1315 let selected_chat_id = self.selected_chat_id(cx);
@@ -1447,7 +1441,7 @@ impl SidebarView {
1447 1441 .into_any_element()
1448 1442 }
1449 1443
1450 fn plain_header(&self, label: &str) -> impl IntoElement {
1444 fn plain_header(&self, label: impl Into<SharedString>) -> impl IntoElement {
1451 1445 div()
1452 1446 .h(px(SECTION_HEIGHT))
1453 1447 .mt(px(SECTION_GAP))
@@ -1457,7 +1451,7 @@ impl SidebarView {
1457 1451 .text_size(px(12.))
1458 1452 .font_weight(FontWeight::SEMIBOLD)
1459 1453 .text_color(theme::text_soft())
1460 .child(label.to_owned())
1454 .child(label.into())
1461 1455 }
1462 1456
1463 1457 fn team_block(
@@ -1527,7 +1521,12 @@ impl SidebarView {
1527 1521 cx.notify();
1528 1522 }))
1529 1523 .context_menu(move |popup, _, _| {
1530 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_menu_flags)
1524 team_menu(
1525 popup,
1526 team_menu_state.clone(),
1527 &team_menu_id,
1528 team_menu_flags,
1529 )
1531 1530 }),
1532 1531 );
1533 1532 if !expanded {
@@ -1596,7 +1595,11 @@ impl SidebarView {
1596 1595 .hover(|row| row.bg(theme::row_hover()))
1597 1596 .text_size(px(13.5))
1598 1597 .text_color(theme::accent_text())
1599 .child(if open { SEE_FEWER_CHANNELS } else { SEE_ALL_CHANNELS })
1598 .child(if open {
1599 tr("sidebar.see_fewer_channels")
1600 } else {
1601 tr("sidebar.see_all_channels")
1602 })
1600 1603 .on_click(on_click)
1601 1604 }
1602 1605
@@ -1682,11 +1685,11 @@ impl SidebarView {
1682 1685 .child(channel.name.clone()),
1683 1686 )
1684 1687 .when(is_private_channel(channel), |name| {
1685 name.child(
1686 div()
1687 .flex_none()
1688 .child(symbol("lock", 14., theme::text_muted())),
1689 )
1688 name.child(div().flex_none().child(symbol(
1689 "lock",
1690 14.,
1691 theme::text_muted(),
1692 )))
1690 1693 }),
1691 1694 )
1692 1695 .children(notification_badge(notifications.level))
@@ -1766,7 +1769,7 @@ impl SidebarView {
1766 1769 })
1767 1770 .collect();
1768 1771 if !pinned.is_empty() {
1769 list = list.child(self.plain_header(PINNED_LABEL));
1772 list = list.child(self.plain_header(tr("sidebar.pinned")));
1770 1773 for (entry, channel) in pinned {
1771 1774 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1772 1775 list = list.child(self.channel_row(
@@ -1778,7 +1781,7 @@ impl SidebarView {
1778 1781 ));
1779 1782 }
1780 1783 }
1781 list = list.child(self.plain_header(TEAMS_LABEL));
1784 list = list.child(self.plain_header(tr("sidebar.teams")));
1782 1785 let hidden_teams: Vec<&SidebarTeam> =
1783 1786 sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1784 1787 for entry in sidebar
@@ -1796,7 +1799,7 @@ impl SidebarView {
1796 1799 let open = self.hidden_teams_open || holds_selection;
1797 1800 list = list.child(self.reveal_row(
1798 1801 "hidden-teams".into(),
1799 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1802 format!("{} ({})", tr("sidebar.hidden_teams"), hidden_teams.len()),
1800 1803 open,
1801 1804 10.,
1802 1805 cx.listener(|this, _, _, cx| {
@@ -1973,7 +1976,7 @@ fn team_menu(
1973 1976 TeamMenuItem::AddChannel => {}
1974 1977 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1975 1978 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1976 TeamMenuItem::ManageTeam => state.open_manage_team(&action_id, cx),
1979 TeamMenuItem::ManageTeam => state.manage_team_in_browser(&action_id, cx),
1977 1980 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1978 1981 });
1979 1982 }),
@@ -1993,11 +1996,11 @@ fn notifications_submenu(
1993 1996 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1994 1997 popup.submenu_with_icon(
1995 1998 Some(menu_icon(IconName::Bell)),
1996 "Notifications",
1999 tr("sidebar.notifications"),
1997 2000 window,
1998 2001 cx,
1999 2002 move |submenu, _, _| {
2000 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
2003 let level_item = |label: String, level: ChannelNotificationLevel| {
2001 2004 let (state, channel_id) = (state.clone(), channel_id.clone());
2002 2005 PopupMenuItem::new(label)
2003 2006 .checked(notifications.level == level)
@@ -2015,14 +2018,20 @@ fn notifications_submenu(
2015 2018 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
2016 2019 submenu
2017 2020 .item(level_item(
2018 "Banner and activity",
2021 tr("sidebar.notify_banner_activity"),
2019 2022 ChannelNotificationLevel::BannerAndFeed,
2020 2023 ))
2021 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
2022 .item(level_item("Off", ChannelNotificationLevel::Off))
2024 .item(level_item(
2025 tr("sidebar.notify_activity_only"),
2026 ChannelNotificationLevel::Feed,
2027 ))
2028 .item(level_item(
2029 tr("sidebar.notify_off"),
2030 ChannelNotificationLevel::Off,
2031 ))
2023 2032 .separator()
2024 2033 .item(
2025 PopupMenuItem::new("Include thread replies")
2034 PopupMenuItem::new(tr("sidebar.include_thread_replies"))
2026 2035 .checked(notifications.include_replies)
2027 2036 .disabled(notifications.level == ChannelNotificationLevel::Off)
2028 2037 .on_click(move |_, _, cx| {
@@ -2131,7 +2140,7 @@ impl Render for SidebarView {
2131 2140 v_flex()
2132 2141 .flex_none()
2133 2142 .child(
2134 page_header(self.tab.title())
2143 page_header(&self.tab.title())
2135 2144 .child(self.chat_list_menu_button(cx))
2136 2145 .child(self.filter_toggle_button(cx))
2137 2146 .child(self.new_chat_button(cx)),
@@ -2142,14 +2151,14 @@ impl Render for SidebarView {
2142 2151 v_flex()
2143 2152 .flex_none()
2144 2153 .child(
2145 page_header(self.tab.title())
2154 page_header(&self.tab.title())
2146 2155 .child(self.channel_list_menu_button(cx))
2147 2156 .child(self.channel_filter_button(cx))
2148 2157 .child(self.new_channel_items_button(cx)),
2149 2158 )
2150 2159 .child(self.channel_filter_bar(cx)),
2151 2160 ),
2152 SidebarTab::Agents => Some(page_header(self.tab.title())),
2161 SidebarTab::Agents => Some(page_header(&self.tab.title())),
2153 2162 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None,
2154 2163 };
2155 2164 v_flex()
@@ -2169,10 +2178,7 @@ impl Render for SidebarView {
2169 2178 mod tests {
2170 2179 use std::collections::HashSet;
2171 2180
2172 use super::{
2173 drop_target, parse_collapsed_teams, serialize_collapsed_teams,
2174 team_expanded,
2175 };
2181 use super::{drop_target, parse_collapsed_teams, serialize_collapsed_teams, team_expanded};
2176 2182 use crate::data::PENDING_FOLDER_PREFIX;
2177 2183 use crate::sidebar_model::{Section, SectionKind};
2178 2184
@@ -2,11 +2,11 @@ use std::cell::{Cell, RefCell};
2use std::collections::{HashMap, HashSet};
2use std::collections::{HashMap, HashSet};
3
3
4use chrono::{Local, Offset, Utc};
4use chrono::{Local, Offset, Utc};
5use gpui_kit::component::scroll::ScrollableElement as _;
6use gpui_kit::assets::IconName;
5use gpui_kit::assets::IconName;
7use gpui_kit::component::button::{Button, ButtonVariants as _};
6use gpui_kit::component::button::{Button, ButtonVariants as _};
8use gpui_kit::component::dialog::DialogFooter;
7use gpui_kit::component::dialog::DialogFooter;
9use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
8use gpui_kit::component::menu::{ContextMenuExt as _, DropdownMenu as _, PopupMenu, PopupMenuItem};
9use gpui_kit::component::scroll::ScrollableElement as _;
10use gpui_kit::component::{Icon, Sizable as _, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
10use gpui_kit::component::{Icon, Sizable as _, WindowExt as _, h_flex, tooltip::Tooltip, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
12use gpui_kit::*;
@@ -18,14 +18,15 @@ use teams_core::team_avatar_key;
18
18
19use super::activity_panel::ActivityPanel;
19use super::activity_panel::ActivityPanel;
20use super::avatar::{spec_avatar, team_avatar, with_presence};
20use super::avatar::{spec_avatar, team_avatar, with_presence};
21use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
22use super::scroll_edge::{scroll_offset, with_top_edge};
23use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
21use super::channel_admin_dialogs::{confirm_delete_channel, open_edit_channel_dialog};
22use super::chat_menu::{ChatMenuTarget, MenuContext, chat_menu};
24use super::create_channel_dialog::open_create_channel_dialog;
23use super::create_channel_dialog::open_create_channel_dialog;
24use super::last_views::LastViews;
25use super::scroll_edge::{scroll_offset, with_top_edge};
25use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
26use super::section_dialog::{SectionNameTarget, open_section_name_dialog};
26use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
27use super::widgets::{count_badge, icon, menu_icon, page_header, symbol, unread_marker};
28use crate::i18n::{tr, tr_args};
27use crate::agents::AgentsPanel;
29use crate::agents::AgentsPanel;
28use super::last_views::LastViews;
29use crate::app_state::{AppEvent, AppState, QuickView, Selection};
30use crate::app_state::{AppEvent, AppState, QuickView, Selection};
30use crate::channel_menu::{
31use crate::channel_menu::{
31 ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
32 ChannelMenuItem, MenuEntry, TeamMenuItem, TeamMenuState, channel_menu_entries,
@@ -61,7 +62,6 @@ const PINNED_CHANNEL_HEIGHT: f32 = 48.;
61const SECTION_HEIGHT: f32 = 30.;
62const SECTION_HEIGHT: f32 = 30.;
62const SECTION_GAP: f32 = 4.;
63const SECTION_GAP: f32 = 4.;
63const QUICK_VIEWS_SECTION_ID: &str = "quick-views";
64const QUICK_VIEWS_SECTION_ID: &str = "quick-views";
64const QUICK_VIEWS_TITLE: &str = "Quick views";
65const QUICK_ROW_HEIGHT: f32 = 32.;
65const QUICK_ROW_HEIGHT: f32 = 32.;
66const QUICK_ICON_SIZE: f32 = 18.;
66const QUICK_ICON_SIZE: f32 = 18.;
67const QUICK_VIEWS: [(QuickView, &str); 3] = [
67const QUICK_VIEWS: [(QuickView, &str); 3] = [
@@ -71,15 +71,9 @@ const QUICK_VIEWS: [(QuickView, &str); 3] = [
71];
71];
72const HINT_HEIGHT: f32 = 26.;
72const HINT_HEIGHT: f32 = 26.;
73const SEE_MORE_HEIGHT: f32 = 28.;
73const SEE_MORE_HEIGHT: f32 = 28.;
74const LOADING_OLDER_LABEL: &str = "Loading older chats";
75const FALLBACK_VIEWPORT: f32 = 900.;
74const FALLBACK_VIEWPORT: f32 = 900.;
76const VIEWPORT_MARGIN: f32 = 300.;
75const VIEWPORT_MARGIN: f32 = 300.;
77const AVATAR_SIZE: f32 = 36.;
76const AVATAR_SIZE: f32 = 36.;
78const PINNED_LABEL: &str = "Pinned";
79const TEAMS_LABEL: &str = "Teams";
80const MARK_ALL_READ_LABEL: &str = "Mark all as read";
81const COLLAPSE_ALL_LABEL: &str = "Collapse all sections";
82const HIDDEN_TEAMS_LABEL: &str = "Hidden teams";
83const TEAM_ROW_HEIGHT: f32 = 36.;
77const TEAM_ROW_HEIGHT: f32 = 36.;
84const CHANNEL_ROW_HEIGHT: f32 = 32.;
78const CHANNEL_ROW_HEIGHT: f32 = 32.;
85const TEAM_ICON_SIZE: f32 = 20.;
79const TEAM_ICON_SIZE: f32 = 20.;
@@ -87,8 +81,6 @@ const TEAM_ICON_RADIUS: f32 = 4.;
87const CHANNEL_INDENT: f32 = 60.;
81const CHANNEL_INDENT: f32 = 60.;
88pub const CHANNEL_ROW_TAG: &str = "sidebar/channel-row";
82pub const CHANNEL_ROW_TAG: &str = "sidebar/channel-row";
89pub const SEE_ALL_CHANNELS_TAG: &str = "sidebar/see-all-channels";
83pub const SEE_ALL_CHANNELS_TAG: &str = "sidebar/see-all-channels";
90const SEE_ALL_CHANNELS: &str = "See all channels";
91const SEE_FEWER_CHANNELS: &str = "See fewer channels";
92const PRIVATE_MEMBERSHIP: &str = "private";
84const PRIVATE_MEMBERSHIP: &str = "private";
93const REVEAL_ROW_HEIGHT: f32 = 32.;
85const REVEAL_ROW_HEIGHT: f32 = 32.;
94const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
86const NEW_CHAT_BUTTON_SIZE: f32 = 32.;
@@ -107,14 +99,14 @@ pub enum SidebarTab {
107}
99}
108
100
109impl SidebarTab {
101impl SidebarTab {
110 fn title(self) -> &'static str {
102 fn title(self) -> String {
111 match self {
103 match self {
112 SidebarTab::Activity => "Activity",
104 SidebarTab::Activity => tr("rail.activity"),
113 SidebarTab::Chats => "Chat",
105 SidebarTab::Chats => tr("rail.chat"),
114 SidebarTab::Channels => "Teams",
106 SidebarTab::Channels => tr("rail.teams"),
115 SidebarTab::Calendar => "Calendar",
107 SidebarTab::Calendar => tr("rail.calendar"),
116 SidebarTab::Calls => "Calls",
108 SidebarTab::Calls => tr("rail.calls"),
117 SidebarTab::Agents => "Agents",
109 SidebarTab::Agents => tr("rail.agents"),
118 }
110 }
119 }
111 }
120}
112}
@@ -205,7 +197,7 @@ fn drop_target(section: &Section) -> Option<Option<String>> {
205
197
206fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem {
198fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem {
207 let state = state.clone();
199 let state = state.clone();
208 PopupMenuItem::new("New section")
200 PopupMenuItem::new(tr("sidebar.new_section"))
209 .icon(menu_icon(IconName::Plus))
201 .icon(menu_icon(IconName::Plus))
210 .disabled(read_only)
202 .disabled(read_only)
211 .on_click(move |_, window, cx| {
203 .on_click(move |_, window, cx| {
@@ -215,7 +207,7 @@ fn new_section_item(state: &Entity<AppState>, read_only: bool) -> PopupMenuItem
215
207
216fn move_section_item(
208fn move_section_item(
217 state: &Entity<AppState>,
209 state: &Entity<AppState>,
218 label: &'static str,
210 label: String,
219 glyph: IconName,
211 glyph: IconName,
220 folder_id: &str,
212 folder_id: &str,
221 target_id: Option<&String>,
213 target_id: Option<&String>,
@@ -249,7 +241,7 @@ fn section_menu(
249 name: target.name.clone(),
241 name: target.name.clone(),
250 };
242 };
251 popup = popup.item(
243 popup = popup.item(
252 PopupMenuItem::new("Rename section")
244 PopupMenuItem::new(tr("sidebar.rename_section"))
253 .icon(menu_icon(IconName::Pencil))
245 .icon(menu_icon(IconName::Pencil))
254 .disabled(target.read_only)
246 .disabled(target.read_only)
255 .on_click(move |_, window, cx| {
247 .on_click(move |_, window, cx| {
@@ -266,7 +258,7 @@ fn section_menu(
266 popup = popup
258 popup = popup
267 .item(move_section_item(
259 .item(move_section_item(
268 state,
260 state,
269 "Move up",
261 tr("sidebar.move_up"),
270 IconName::ArrowUp,
262 IconName::ArrowUp,
271 &target.id,
263 &target.id,
272 target.previous_id.as_ref(),
264 target.previous_id.as_ref(),
@@ -274,7 +266,7 @@ fn section_menu(
274 ))
266 ))
275 .item(move_section_item(
267 .item(move_section_item(
276 state,
268 state,
277 "Move down",
269 tr("sidebar.move_down"),
278 IconName::ArrowDown,
270 IconName::ArrowDown,
279 &target.id,
271 &target.id,
280 target.next_id.as_ref(),
272 target.next_id.as_ref(),
@@ -288,7 +280,9 @@ fn section_menu(
288 let (folder_id, name) = (target.id.clone(), target.name.clone());
280 let (folder_id, name) = (target.id.clone(), target.name.clone());
289 popup = popup.separator().item(
281 popup = popup.separator().item(
290 PopupMenuItem::element(|_, _| {
282 PopupMenuItem::element(|_, _| {
291 div().text_color(theme::red_soft()).child("Delete section")
283 div()
284 .text_color(theme::red_soft())
285 .child(tr("sidebar.delete_section"))
292 })
286 })
293 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
287 .icon(menu_icon(IconName::Trash).text_color(theme::red_soft()))
294 .disabled(target.read_only)
288 .disabled(target.read_only)
@@ -309,15 +303,17 @@ fn confirm_delete_section(
309) {
303) {
310 let state = state.clone();
304 let state = state.clone();
311 let folder_id = folder_id.to_owned();
305 let folder_id = folder_id.to_owned();
312 let heading = format!("Delete section \"{}\"?", truncated(name, TITLE_LIMIT));
306 let mut args = HashMap::new();
307 args.insert("name".to_owned(), truncated(name, TITLE_LIMIT));
308 let heading = tr_args("sidebar.delete_section_title", &args);
313 window.open_alert_dialog(cx, move |alert, _, _| {
309 window.open_alert_dialog(cx, move |alert, _, _| {
314 let state = state.clone();
310 let state = state.clone();
315 let folder_id = folder_id.clone();
311 let folder_id = folder_id.clone();
316 let cancel = Button::new("delete-section-cancel")
312 let cancel = Button::new("delete-section-cancel")
317 .label("Cancel")
313 .label(tr("common.cancel"))
318 .on_click(|_, window, cx| window.close_dialog(cx));
314 .on_click(|_, window, cx| window.close_dialog(cx));
319 let delete = Button::new("delete-section-confirm")
315 let delete = Button::new("delete-section-confirm")
320 .label("Delete")
316 .label(tr("common.delete"))
321 .danger()
317 .danger()
322 .on_click(move |_, window, cx| {
318 .on_click(move |_, window, cx| {
323 state.update(cx, |state, cx| state.delete_section(&folder_id, cx));
319 state.update(cx, |state, cx| state.delete_section(&folder_id, cx));
@@ -325,7 +321,7 @@ fn confirm_delete_section(
325 });
321 });
326 alert
322 alert
327 .title(heading.clone())
323 .title(heading.clone())
328 .description("Chats in it move back to Chats.")
324 .description(tr("sidebar.delete_section_detail"))
329 .footer(DialogFooter::new().child(cancel).child(delete))
325 .footer(DialogFooter::new().child(cancel).child(delete))
330 .on_ok(|_, _, _| false)
326 .on_ok(|_, _, _| false)
331 });
327 });
@@ -397,14 +393,14 @@ fn local_preview_row(preview: &LocalPreview, color: Hsla) -> Div {
397 div()
393 div()
398 .flex_none()
394 .flex_none()
399 .text_color(theme::accent_text())
395 .text_color(theme::accent_text())
400 .child("Draft:"),
396 .child(tr("sidebar.draft_prefix")),
401 )
397 )
402 .child(div().truncate().child(text.clone())),
398 .child(div().truncate().child(text.clone())),
403 LocalPreview::NotSent => row.child(
399 LocalPreview::NotSent => row.child(
404 div()
400 div()
405 .flex_none()
401 .flex_none()
406 .text_color(theme::red_soft())
402 .text_color(theme::red_soft())
407 .child("Not sent"),
403 .child(tr("sidebar.not_sent")),
408 ),
404 ),
409 }
405 }
410}
406}
@@ -559,15 +555,12 @@ impl SidebarView {
559 self.last_views.remember(current);
555 self.last_views.remember(current);
560 }
556 }
561 let first_chat_id = state.sidebar.chats.first().map(|chat| chat.id.as_str());
557 let first_chat_id = state.sidebar.chats.first().map(|chat| chat.id.as_str());
562 if let Some(selection) =
558 if let Some(selection) = self.last_views.restore(
563 self.last_views
559 tab,
564 .restore(
560 state.selection.as_ref(),
565 tab,
561 first_chat_id,
566 state.selection.as_ref(),
562 first_channel_id.as_deref(),
567 first_chat_id,
563 ) {
568 first_channel_id.as_deref(),
569 )
570 {
571 self.state
564 self.state
572 .update(cx, |state, cx| state.select(selection, cx));
565 .update(cx, |state, cx| state.select(selection, cx));
573 }
566 }
@@ -604,7 +597,9 @@ impl SidebarView {
604
597
605 fn first_channel_id(&self, cx: &App) -> Option<String> {
598 fn first_channel_id(&self, cx: &App) -> Option<String> {
606 let input = self.channel_order_input(self.state.read(cx), None);
599 let input = self.channel_order_input(self.state.read(cx), None);
607 visible_channel_ids(&input).first().map(|id| (*id).to_owned())
600 visible_channel_ids(&input)
601 .first()
602 .map(|id| (*id).to_owned())
608 }
603 }
609
604
610 fn channel_order_input<'a>(
605 fn channel_order_input<'a>(
@@ -659,7 +654,9 @@ impl SidebarView {
659 .cursor_pointer()
654 .cursor_pointer()
660 .when(active, |button| button.bg(theme::popup_hover()))
655 .when(active, |button| button.bg(theme::popup_hover()))
661 .hover(|button| button.bg(theme::popup_hover()))
656 .hover(|button| button.bg(theme::popup_hover()))
662 .tooltip(|window, cx| Tooltip::new("New chat (Ctrl+N)").build(window, cx))
657 .tooltip(|window, cx| {
658 Tooltip::new(tr("sidebar.new_chat_shortcut")).build(window, cx)
659 })
663 .child(icon(IconName::Pencil, 16., theme::text_soft()))
660 .child(icon(IconName::Pencil, 16., theme::text_soft()))
664 .on_click(cx.listener(|this, _, _, cx| {
661 .on_click(cx.listener(|this, _, _, cx| {
665 this.state.update(cx, |state, cx| state.start_new_chat(cx));
662 this.state.update(cx, |state, cx| state.start_new_chat(cx));
@@ -675,12 +672,12 @@ impl SidebarView {
675 .ghost()
672 .ghost()
676 .size(px(NEW_CHAT_BUTTON_SIZE))
673 .size(px(NEW_CHAT_BUTTON_SIZE))
677 .rounded(px(8.))
674 .rounded(px(8.))
678 .tooltip("More options")
675 .tooltip(tr("sidebar.more_options"))
679 .dropdown_menu(move |menu, _, _| {
676 .dropdown_menu(move |menu, _, _| {
680 let (read_state, collapse_state) = (state.clone(), state.clone());
677 let (read_state, collapse_state) = (state.clone(), state.clone());
681 let section_ids = section_ids.clone();
678 let section_ids = section_ids.clone();
682 menu.item(
679 menu.item(
683 PopupMenuItem::new(MARK_ALL_READ_LABEL)
680 PopupMenuItem::new(tr("sidebar.mark_all_read"))
684 .icon(menu_icon(IconName::CheckCheck))
681 .icon(menu_icon(IconName::CheckCheck))
685 .disabled(read_only)
682 .disabled(read_only)
686 .on_click(move |_, _, cx| {
683 .on_click(move |_, _, cx| {
@@ -688,7 +685,7 @@ impl SidebarView {
688 }),
685 }),
689 )
686 )
690 .item(
687 .item(
691 PopupMenuItem::new(COLLAPSE_ALL_LABEL)
688 PopupMenuItem::new(tr("sidebar.collapse_all"))
692 .icon(menu_icon(IconName::ChevronsDownUp))
689 .icon(menu_icon(IconName::ChevronsDownUp))
693 .on_click(move |_, _, cx| {
690 .on_click(move |_, _, cx| {
694 let ids = section_ids.clone();
691 let ids = section_ids.clone();
@@ -718,11 +715,11 @@ impl SidebarView {
718 .ghost()
715 .ghost()
719 .size(px(NEW_CHAT_BUTTON_SIZE))
716 .size(px(NEW_CHAT_BUTTON_SIZE))
720 .rounded(px(8.))
717 .rounded(px(8.))
721 .tooltip("More options")
718 .tooltip(tr("sidebar.more_options"))
722 .dropdown_menu(move |menu, _, _| {
719 .dropdown_menu(move |menu, _, _| {
723 let (state, view, team_ids) = (state.clone(), view.clone(), team_ids.clone());
720 let (state, view, team_ids) = (state.clone(), view.clone(), team_ids.clone());
724 menu.item(
721 menu.item(
725 PopupMenuItem::new(MARK_ALL_READ_LABEL)
722 PopupMenuItem::new(tr("sidebar.mark_all_read"))
726 .icon(menu_icon(IconName::CheckCheck))
723 .icon(menu_icon(IconName::CheckCheck))
727 .disabled(read_only)
724 .disabled(read_only)
728 .on_click(move |_, _, cx| {
725 .on_click(move |_, _, cx| {
@@ -730,7 +727,7 @@ impl SidebarView {
730 }),
727 }),
731 )
728 )
732 .item(
729 .item(
733 PopupMenuItem::new(COLLAPSE_ALL_LABEL)
730 PopupMenuItem::new(tr("sidebar.collapse_all"))
734 .icon(menu_icon(IconName::ChevronsDownUp))
731 .icon(menu_icon(IconName::ChevronsDownUp))
735 .on_click(move |_, _, cx| {
732 .on_click(move |_, _, cx| {
736 let team_ids = team_ids.clone();
733 let team_ids = team_ids.clone();
@@ -773,14 +770,14 @@ impl SidebarView {
773 .truncate()
770 .truncate()
774 .text_size(px(14.))
771 .text_size(px(14.))
775 .text_color(theme::text())
772 .text_color(theme::text())
776 .child("New chat"),
773 .child(tr("sidebar.new_chat")),
777 )
774 )
778 .child(
775 .child(
779 div()
776 div()
780 .truncate()
777 .truncate()
781 .text_size(px(12.5))
778 .text_size(px(12.5))
782 .text_color(theme::text_muted())
779 .text_color(theme::text_muted())
783 .child("Draft"),
780 .child(tr("sidebar.draft")),
784 ),
781 ),
785 )
782 )
786 }
783 }
@@ -885,7 +882,7 @@ impl SidebarView {
885 .text_size(px(12.))
882 .text_size(px(12.))
886 .font_weight(FontWeight::SEMIBOLD)
883 .font_weight(FontWeight::SEMIBOLD)
887 .text_color(theme::text_soft())
884 .text_color(theme::text_soft())
888 .child(QUICK_VIEWS_TITLE),
885 .child(tr("sidebar.quick_views")),
889 )
886 )
890 .on_click(cx.listener(|this, _, _, cx| {
887 .on_click(cx.listener(|this, _, _, cx| {
891 this.state.update(cx, |state, cx| {
888 this.state.update(cx, |state, cx| {
@@ -896,7 +893,8 @@ impl SidebarView {
896 let mut height = SECTION_GAP + SECTION_HEIGHT;
893 let mut height = SECTION_GAP + SECTION_HEIGHT;
897 if !collapsed {
894 if !collapsed {
898 for (view, glyph) in QUICK_VIEWS {
895 for (view, glyph) in QUICK_VIEWS {
899 section = section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
896 section =
897 section.child(self.quick_view_row(view, glyph, open_view == Some(view), cx));
900 height += QUICK_ROW_HEIGHT;
898 height += QUICK_ROW_HEIGHT;
901 }
899 }
902 }
900 }
@@ -939,9 +937,11 @@ impl SidebarView {
939 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
937 fn see_more_row(&self, section: &Section, cx: &mut Context<Self>) -> impl IntoElement {
940 let toggle_id = section.id.clone();
938 let toggle_id = section.id.clone();
941 let label = if section.hidden_count > 0 {
939 let label = if section.hidden_count > 0 {
942 format!("See more ({})", section.hidden_count)
940 let mut args = HashMap::new();
941 args.insert("count".to_owned(), section.hidden_count.to_string());
942 tr_args("sidebar.see_more", &args)
943 } else {
943 } else {
944 "See less".to_owned()
944 tr("sidebar.see_less")
945 };
945 };
946 div()
946 div()
947 .id(SharedString::from(format!("see-more-{}", section.id)))
947 .id(SharedString::from(format!("see-more-{}", section.id)))
@@ -1076,7 +1076,6 @@ impl SidebarView {
1076 );
1076 );
1077 let state = self.state.clone();
1077 let state = self.state.clone();
1078 let chat_id = item.id.clone();
1078 let chat_id = item.id.clone();
1079 let (warm_state, warm_chat_id) = (self.state.clone(), item.id.clone());
1080 let dragged = DraggedChat {
1079 let dragged = DraggedChat {
1081 id: item.id.clone(),
1080 id: item.id.clone(),
1082 title: item.title.clone(),
1081 title: item.title.clone(),
@@ -1109,7 +1108,7 @@ impl SidebarView {
1109 .ghost()
1108 .ghost()
1110 .xsmall()
1109 .xsmall()
1111 .icon(IconName::Ellipsis)
1110 .icon(IconName::Ellipsis)
1112 .tooltip("More options")
1111 .tooltip(tr("sidebar.more_options"))
1113 .dropdown_menu(move |popup, window, cx| {
1112 .dropdown_menu(move |popup, window, cx| {
1114 chat_menu(popup, window, cx, &more_context, &more_target)
1113 chat_menu(popup, window, cx, &more_context, &more_target)
1115 }),
1114 }),
@@ -1145,11 +1144,6 @@ impl SidebarView {
1145 .child(avatar)
1144 .child(avatar)
1146 .child(lines)
1145 .child(lines)
1147 .child(more_button)
1146 .child(more_button)
1148 .on_hover(move |hovered, _, cx| {
1149 if *hovered {
1150 warm_state.update(cx, |state, _| state.warm_chat(&warm_chat_id));
1151 }
1152 })
1153 .on_click(move |_, _, cx| {
1147 .on_click(move |_, _, cx| {
1154 let selection = Selection::Chat(chat_id.clone());
1148 let selection = Selection::Chat(chat_id.clone());
1155 state.update(cx, |state, cx| state.select(selection, cx));
1149 state.update(cx, |state, cx| state.select(selection, cx));
@@ -1315,7 +1309,7 @@ impl SidebarView {
1315 .text_size(px(12.5))
1309 .text_size(px(12.5))
1316 .italic()
1310 .italic()
1317 .text_color(theme::text_faint())
1311 .text_color(theme::text_faint())
1318 .child(LOADING_OLDER_LABEL),
1312 .child(tr("sidebar.loading_older")),
1319 );
1313 );
1320 }
1314 }
1321 let selected_chat_id = self.selected_chat_id(cx);
1315 let selected_chat_id = self.selected_chat_id(cx);
@@ -1447,7 +1441,7 @@ impl SidebarView {
1447 .into_any_element()
1441 .into_any_element()
1448 }
1442 }
1449
1443
1450 fn plain_header(&self, label: &str) -> impl IntoElement {
1444 fn plain_header(&self, label: impl Into<SharedString>) -> impl IntoElement {
1451 div()
1445 div()
1452 .h(px(SECTION_HEIGHT))
1446 .h(px(SECTION_HEIGHT))
1453 .mt(px(SECTION_GAP))
1447 .mt(px(SECTION_GAP))
@@ -1457,7 +1451,7 @@ impl SidebarView {
1457 .text_size(px(12.))
1451 .text_size(px(12.))
1458 .font_weight(FontWeight::SEMIBOLD)
1452 .font_weight(FontWeight::SEMIBOLD)
1459 .text_color(theme::text_soft())
1453 .text_color(theme::text_soft())
1460 .child(label.to_owned())
1454 .child(label.into())
1461 }
1455 }
1462
1456
1463 fn team_block(
1457 fn team_block(
@@ -1527,7 +1521,12 @@ impl SidebarView {
1527 cx.notify();
1521 cx.notify();
1528 }))
1522 }))
1529 .context_menu(move |popup, _, _| {
1523 .context_menu(move |popup, _, _| {
1530 team_menu(popup, team_menu_state.clone(), &team_menu_id, team_menu_flags)
1524 team_menu(
1525 popup,
1526 team_menu_state.clone(),
1527 &team_menu_id,
1528 team_menu_flags,
1529 )
1531 }),
1530 }),
1532 );
1531 );
1533 if !expanded {
1532 if !expanded {
@@ -1596,7 +1595,11 @@ impl SidebarView {
1596 .hover(|row| row.bg(theme::row_hover()))
1595 .hover(|row| row.bg(theme::row_hover()))
1597 .text_size(px(13.5))
1596 .text_size(px(13.5))
1598 .text_color(theme::accent_text())
1597 .text_color(theme::accent_text())
1599 .child(if open { SEE_FEWER_CHANNELS } else { SEE_ALL_CHANNELS })
1598 .child(if open {
1599 tr("sidebar.see_fewer_channels")
1600 } else {
1601 tr("sidebar.see_all_channels")
1602 })
1600 .on_click(on_click)
1603 .on_click(on_click)
1601 }
1604 }
1602
1605
@@ -1682,11 +1685,11 @@ impl SidebarView {
1682 .child(channel.name.clone()),
1685 .child(channel.name.clone()),
1683 )
1686 )
1684 .when(is_private_channel(channel), |name| {
1687 .when(is_private_channel(channel), |name| {
1685 name.child(
1688 name.child(div().flex_none().child(symbol(
1686 div()
1689 "lock",
1687 .flex_none()
1690 14.,
1688 .child(symbol("lock", 14., theme::text_muted())),
1691 theme::text_muted(),
1689 )
1692 )))
1690 }),
1693 }),
1691 )
1694 )
1692 .children(notification_badge(notifications.level))
1695 .children(notification_badge(notifications.level))
@@ -1766,7 +1769,7 @@ impl SidebarView {
1766 })
1769 })
1767 .collect();
1770 .collect();
1768 if !pinned.is_empty() {
1771 if !pinned.is_empty() {
1769 list = list.child(self.plain_header(PINNED_LABEL));
1772 list = list.child(self.plain_header(tr("sidebar.pinned")));
1770 for (entry, channel) in pinned {
1773 for (entry, channel) in pinned {
1771 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1774 let is_selected = selected == Some(Selection::Channel(channel.id.clone()));
1772 list = list.child(self.channel_row(
1775 list = list.child(self.channel_row(
@@ -1778,7 +1781,7 @@ impl SidebarView {
1778 ));
1781 ));
1779 }
1782 }
1780 }
1783 }
1781 list = list.child(self.plain_header(TEAMS_LABEL));
1784 list = list.child(self.plain_header(tr("sidebar.teams")));
1782 let hidden_teams: Vec<&SidebarTeam> =
1785 let hidden_teams: Vec<&SidebarTeam> =
1783 sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1786 sidebar.teams.iter().filter(|entry| entry.hidden).collect();
1784 for entry in sidebar
1787 for entry in sidebar
@@ -1796,7 +1799,7 @@ impl SidebarView {
1796 let open = self.hidden_teams_open || holds_selection;
1799 let open = self.hidden_teams_open || holds_selection;
1797 list = list.child(self.reveal_row(
1800 list = list.child(self.reveal_row(
1798 "hidden-teams".into(),
1801 "hidden-teams".into(),
1799 format!("{HIDDEN_TEAMS_LABEL} ({})", hidden_teams.len()),
1802 format!("{} ({})", tr("sidebar.hidden_teams"), hidden_teams.len()),
1800 open,
1803 open,
1801 10.,
1804 10.,
1802 cx.listener(|this, _, _, cx| {
1805 cx.listener(|this, _, _, cx| {
@@ -1973,7 +1976,7 @@ fn team_menu(
1973 TeamMenuItem::AddChannel => {}
1976 TeamMenuItem::AddChannel => {}
1974 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1977 TeamMenuItem::Show => state.set_team_shown(&action_id, true, cx),
1975 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1978 TeamMenuItem::Hide => state.set_team_shown(&action_id, false, cx),
1976 TeamMenuItem::ManageTeam => state.open_manage_team(&action_id, cx),
1979 TeamMenuItem::ManageTeam => state.manage_team_in_browser(&action_id, cx),
1977 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1980 TeamMenuItem::CopyLink => state.copy_team_link(&action_id, cx),
1978 });
1981 });
1979 }),
1982 }),
@@ -1993,11 +1996,11 @@ fn notifications_submenu(
1993 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1996 let (state, channel_id) = (state.clone(), channel_id.to_owned());
1994 popup.submenu_with_icon(
1997 popup.submenu_with_icon(
1995 Some(menu_icon(IconName::Bell)),
1998 Some(menu_icon(IconName::Bell)),
1996 "Notifications",
1999 tr("sidebar.notifications"),
1997 window,
2000 window,
1998 cx,
2001 cx,
1999 move |submenu, _, _| {
2002 move |submenu, _, _| {
2000 let level_item = |label: &'static str, level: ChannelNotificationLevel| {
2003 let level_item = |label: String, level: ChannelNotificationLevel| {
2001 let (state, channel_id) = (state.clone(), channel_id.clone());
2004 let (state, channel_id) = (state.clone(), channel_id.clone());
2002 PopupMenuItem::new(label)
2005 PopupMenuItem::new(label)
2003 .checked(notifications.level == level)
2006 .checked(notifications.level == level)
@@ -2015,14 +2018,20 @@ fn notifications_submenu(
2015 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
2018 let (replies_state, replies_id) = (state.clone(), channel_id.clone());
2016 submenu
2019 submenu
2017 .item(level_item(
2020 .item(level_item(
2018 "Banner and activity",
2021 tr("sidebar.notify_banner_activity"),
2019 ChannelNotificationLevel::BannerAndFeed,
2022 ChannelNotificationLevel::BannerAndFeed,
2020 ))
2023 ))
2021 .item(level_item("Activity only", ChannelNotificationLevel::Feed))
2024 .item(level_item(
2022 .item(level_item("Off", ChannelNotificationLevel::Off))
2025 tr("sidebar.notify_activity_only"),
2026 ChannelNotificationLevel::Feed,
2027 ))
2028 .item(level_item(
2029 tr("sidebar.notify_off"),
2030 ChannelNotificationLevel::Off,
2031 ))
2023 .separator()
2032 .separator()
2024 .item(
2033 .item(
2025 PopupMenuItem::new("Include thread replies")
2034 PopupMenuItem::new(tr("sidebar.include_thread_replies"))
2026 .checked(notifications.include_replies)
2035 .checked(notifications.include_replies)
2027 .disabled(notifications.level == ChannelNotificationLevel::Off)
2036 .disabled(notifications.level == ChannelNotificationLevel::Off)
2028 .on_click(move |_, _, cx| {
2037 .on_click(move |_, _, cx| {
@@ -2131,7 +2140,7 @@ impl Render for SidebarView {
2131 v_flex()
2140 v_flex()
2132 .flex_none()
2141 .flex_none()
2133 .child(
2142 .child(
2134 page_header(self.tab.title())
2143 page_header(&self.tab.title())
2135 .child(self.chat_list_menu_button(cx))
2144 .child(self.chat_list_menu_button(cx))
2136 .child(self.filter_toggle_button(cx))
2145 .child(self.filter_toggle_button(cx))
2137 .child(self.new_chat_button(cx)),
2146 .child(self.new_chat_button(cx)),
@@ -2142,14 +2151,14 @@ impl Render for SidebarView {
2142 v_flex()
2151 v_flex()
2143 .flex_none()
2152 .flex_none()
2144 .child(
2153 .child(
2145 page_header(self.tab.title())
2154 page_header(&self.tab.title())
2146 .child(self.channel_list_menu_button(cx))
2155 .child(self.channel_list_menu_button(cx))
2147 .child(self.channel_filter_button(cx))
2156 .child(self.channel_filter_button(cx))
2148 .child(self.new_channel_items_button(cx)),
2157 .child(self.new_channel_items_button(cx)),
2149 )
2158 )
2150 .child(self.channel_filter_bar(cx)),
2159 .child(self.channel_filter_bar(cx)),
2151 ),
2160 ),
2152 SidebarTab::Agents => Some(page_header(self.tab.title())),
2161 SidebarTab::Agents => Some(page_header(&self.tab.title())),
2153 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None,
2162 SidebarTab::Activity | SidebarTab::Calls | SidebarTab::Calendar => None,
2154 };
2163 };
2155 v_flex()
2164 v_flex()
@@ -2169,10 +2178,7 @@ impl Render for SidebarView {
2169mod tests {
2178mod tests {
2170 use std::collections::HashSet;
2179 use std::collections::HashSet;
2171
2180
2172 use super::{
2181 use super::{drop_target, parse_collapsed_teams, serialize_collapsed_teams, team_expanded};
2173 drop_target, parse_collapsed_teams, serialize_collapsed_teams,
2174 team_expanded,
2175 };
2176 use crate::data::PENDING_FOLDER_PREFIX;
2182 use crate::data::PENDING_FOLDER_PREFIX;
2177 use crate::sidebar_model::{Section, SectionKind};
2183 use crate::sidebar_model::{Section, SectionKind};
2178
2184
crates/app/src/views/sidebar/channel_filter_bar.rs +34 −15
@@ -8,15 +8,14 @@ use gpui_kit::*;
8 8
9 9 use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarView};
10 10 use crate::app_state::Selection;
11 use crate::channel_filter::{CHANNEL_FILTER_PLACEHOLDER, UNREAD_PILL};
12 use crate::chat_filter::{CLOSE_FILTER_TEXT, SHOW_FILTER_TEXT};
11 use crate::channel_filter::{channel_filter_placeholder, channel_unread_pill};
12 use crate::chat_filter::{filter_close_box, filter_show_box};
13 use crate::i18n::tr;
13 14 use crate::theme;
14 15 use crate::views::create_channel_dialog::open_create_channel_dialog;
15 16 use crate::views::widgets::{icon, menu_icon};
16 17
17 18 pub const CHANNEL_FILTER_TAG: &str = "shell/islands/sidebar/channel-filter";
18 const NEW_CHANNEL_LABEL: &str = "New channel";
19 const NEW_MESSAGE_LABEL: &str = "New message";
20 19 const INPUT_HEIGHT: f32 = 32.;
21 20 const PILL_HEIGHT: f32 = 24.;
22 21 const SIDE_INSET: f32 = 16.;
@@ -43,11 +42,16 @@ impl SidebarView {
43 42 cx.notify();
44 43 }
45 44
46 fn channel_filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
45 fn channel_filter_input(
46 &mut self,
47 window: &mut Window,
48 cx: &mut Context<Self>,
49 ) -> Entity<InputState> {
47 50 if let Some(input) = &self.channel_filter_input {
48 51 return input.clone();
49 52 }
50 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CHANNEL_FILTER_PLACEHOLDER));
53 let input =
54 cx.new(|cx| InputState::new(window, cx).placeholder(channel_filter_placeholder()));
51 55 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
52 56 if matches!(event, InputEvent::Change) {
53 57 this.channel_filter.text = input.read(cx).value().to_string();
@@ -61,7 +65,11 @@ impl SidebarView {
61 65
62 66 pub(super) fn channel_filter_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
63 67 let open = self.channel_filter_open;
64 let label = if open { CLOSE_FILTER_TEXT } else { SHOW_FILTER_TEXT };
68 let label = if open {
69 filter_close_box()
70 } else {
71 filter_show_box()
72 };
65 73 div()
66 74 .id("channel-filter-toggle")
67 75 .size(px(NEW_CHAT_BUTTON_SIZE))
@@ -73,11 +81,15 @@ impl SidebarView {
73 81 .cursor_pointer()
74 82 .when(open, |button| button.bg(theme::popup_hover()))
75 83 .hover(|button| button.bg(theme::popup_hover()))
76 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
84 .tooltip(move |window, cx| Tooltip::new(label.clone()).build(window, cx))
77 85 .child(icon(
78 86 IconName::Search,
79 87 16.,
80 if open { theme::accent_text() } else { theme::text_soft() },
88 if open {
89 theme::accent_text()
90 } else {
91 theme::text_soft()
92 },
81 93 ))
82 94 .on_click(cx.listener(|this, _, window, cx| this.toggle_channel_filter(window, cx)))
83 95 }
@@ -92,7 +104,12 @@ impl SidebarView {
92 104 .sidebar
93 105 .teams
94 106 .iter()
95 .find(|entry| entry.channels.iter().any(|channel| &channel.id == channel_id))
107 .find(|entry| {
108 entry
109 .channels
110 .iter()
111 .any(|channel| &channel.id == channel_id)
112 })
96 113 .filter(|entry| entry.rights.add_channel && !app.mode.read_only)
97 114 .map(|entry| entry.team.id.clone()),
98 115 _ => None,
@@ -102,11 +119,11 @@ impl SidebarView {
102 119 .ghost()
103 120 .size(px(NEW_CHAT_BUTTON_SIZE))
104 121 .rounded(px(8.))
105 .tooltip("New items")
122 .tooltip(tr("sidebar.new_items"))
106 123 .dropdown_menu(move |menu, _, _| {
107 124 let (state, team_id, sidebar) = (state.clone(), team_id.clone(), sidebar.clone());
108 125 menu.item(
109 PopupMenuItem::new(NEW_MESSAGE_LABEL)
126 PopupMenuItem::new(tr("sidebar.new_message"))
110 127 .icon(menu_icon(IconName::MessageSquare))
111 128 .disabled(!channel_selected)
112 129 .on_click(move |_, _, cx| {
@@ -116,7 +133,7 @@ impl SidebarView {
116 133 }),
117 134 )
118 135 .item(
119 PopupMenuItem::new(NEW_CHANNEL_LABEL)
136 PopupMenuItem::new(tr("sidebar.new_channel"))
120 137 .icon(menu_icon(IconName::Hash))
121 138 .disabled(team_id.is_none())
122 139 .on_click(move |_, window, cx| {
@@ -154,13 +171,15 @@ impl SidebarView {
154 171 .rounded_full()
155 172 .text_size(px(12.))
156 173 .cursor_pointer()
157 .when(selected, |chip| chip.bg(theme::accent()).text_color(theme::on_accent()))
174 .when(selected, |chip| {
175 chip.bg(theme::accent()).text_color(theme::on_accent())
176 })
158 177 .when(!selected, |chip| {
159 178 chip.bg(theme::surface_raised())
160 179 .text_color(theme::text_soft())
161 180 .hover(|chip| chip.bg(theme::border_strong()))
162 181 })
163 .child(UNREAD_PILL)
182 .child(channel_unread_pill())
164 183 .on_click(cx.listener(|this, _, _, cx| {
165 184 this.channel_filter.unread_only = !this.channel_filter.unread_only;
166 185 cx.notify();
@@ -8,15 +8,14 @@ use gpui_kit::*;
8
8
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarView};
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarView};
10use crate::app_state::Selection;
10use crate::app_state::Selection;
11use crate::channel_filter::{CHANNEL_FILTER_PLACEHOLDER, UNREAD_PILL};
11use crate::channel_filter::{channel_filter_placeholder, channel_unread_pill};
12use crate::chat_filter::{CLOSE_FILTER_TEXT, SHOW_FILTER_TEXT};
12use crate::chat_filter::{filter_close_box, filter_show_box};
13use crate::i18n::tr;
13use crate::theme;
14use crate::theme;
14use crate::views::create_channel_dialog::open_create_channel_dialog;
15use crate::views::create_channel_dialog::open_create_channel_dialog;
15use crate::views::widgets::{icon, menu_icon};
16use crate::views::widgets::{icon, menu_icon};
16
17
17pub const CHANNEL_FILTER_TAG: &str = "shell/islands/sidebar/channel-filter";
18pub const CHANNEL_FILTER_TAG: &str = "shell/islands/sidebar/channel-filter";
18const NEW_CHANNEL_LABEL: &str = "New channel";
19const NEW_MESSAGE_LABEL: &str = "New message";
20const INPUT_HEIGHT: f32 = 32.;
19const INPUT_HEIGHT: f32 = 32.;
21const PILL_HEIGHT: f32 = 24.;
20const PILL_HEIGHT: f32 = 24.;
22const SIDE_INSET: f32 = 16.;
21const SIDE_INSET: f32 = 16.;
@@ -43,11 +42,16 @@ impl SidebarView {
43 cx.notify();
42 cx.notify();
44 }
43 }
45
44
46 fn channel_filter_input(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Entity<InputState> {
45 fn channel_filter_input(
46 &mut self,
47 window: &mut Window,
48 cx: &mut Context<Self>,
49 ) -> Entity<InputState> {
47 if let Some(input) = &self.channel_filter_input {
50 if let Some(input) = &self.channel_filter_input {
48 return input.clone();
51 return input.clone();
49 }
52 }
50 let input = cx.new(|cx| InputState::new(window, cx).placeholder(CHANNEL_FILTER_PLACEHOLDER));
53 let input =
54 cx.new(|cx| InputState::new(window, cx).placeholder(channel_filter_placeholder()));
51 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
55 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
52 if matches!(event, InputEvent::Change) {
56 if matches!(event, InputEvent::Change) {
53 this.channel_filter.text = input.read(cx).value().to_string();
57 this.channel_filter.text = input.read(cx).value().to_string();
@@ -61,7 +65,11 @@ impl SidebarView {
61
65
62 pub(super) fn channel_filter_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
66 pub(super) fn channel_filter_button(&self, cx: &mut Context<Self>) -> impl IntoElement {
63 let open = self.channel_filter_open;
67 let open = self.channel_filter_open;
64 let label = if open { CLOSE_FILTER_TEXT } else { SHOW_FILTER_TEXT };
68 let label = if open {
69 filter_close_box()
70 } else {
71 filter_show_box()
72 };
65 div()
73 div()
66 .id("channel-filter-toggle")
74 .id("channel-filter-toggle")
67 .size(px(NEW_CHAT_BUTTON_SIZE))
75 .size(px(NEW_CHAT_BUTTON_SIZE))
@@ -73,11 +81,15 @@ impl SidebarView {
73 .cursor_pointer()
81 .cursor_pointer()
74 .when(open, |button| button.bg(theme::popup_hover()))
82 .when(open, |button| button.bg(theme::popup_hover()))
75 .hover(|button| button.bg(theme::popup_hover()))
83 .hover(|button| button.bg(theme::popup_hover()))
76 .tooltip(move |window, cx| Tooltip::new(label).build(window, cx))
84 .tooltip(move |window, cx| Tooltip::new(label.clone()).build(window, cx))
77 .child(icon(
85 .child(icon(
78 IconName::Search,
86 IconName::Search,
79 16.,
87 16.,
80 if open { theme::accent_text() } else { theme::text_soft() },
88 if open {
89 theme::accent_text()
90 } else {
91 theme::text_soft()
92 },
81 ))
93 ))
82 .on_click(cx.listener(|this, _, window, cx| this.toggle_channel_filter(window, cx)))
94 .on_click(cx.listener(|this, _, window, cx| this.toggle_channel_filter(window, cx)))
83 }
95 }
@@ -92,7 +104,12 @@ impl SidebarView {
92 .sidebar
104 .sidebar
93 .teams
105 .teams
94 .iter()
106 .iter()
95 .find(|entry| entry.channels.iter().any(|channel| &channel.id == channel_id))
107 .find(|entry| {
108 entry
109 .channels
110 .iter()
111 .any(|channel| &channel.id == channel_id)
112 })
96 .filter(|entry| entry.rights.add_channel && !app.mode.read_only)
113 .filter(|entry| entry.rights.add_channel && !app.mode.read_only)
97 .map(|entry| entry.team.id.clone()),
114 .map(|entry| entry.team.id.clone()),
98 _ => None,
115 _ => None,
@@ -102,11 +119,11 @@ impl SidebarView {
102 .ghost()
119 .ghost()
103 .size(px(NEW_CHAT_BUTTON_SIZE))
120 .size(px(NEW_CHAT_BUTTON_SIZE))
104 .rounded(px(8.))
121 .rounded(px(8.))
105 .tooltip("New items")
122 .tooltip(tr("sidebar.new_items"))
106 .dropdown_menu(move |menu, _, _| {
123 .dropdown_menu(move |menu, _, _| {
107 let (state, team_id, sidebar) = (state.clone(), team_id.clone(), sidebar.clone());
124 let (state, team_id, sidebar) = (state.clone(), team_id.clone(), sidebar.clone());
108 menu.item(
125 menu.item(
109 PopupMenuItem::new(NEW_MESSAGE_LABEL)
126 PopupMenuItem::new(tr("sidebar.new_message"))
110 .icon(menu_icon(IconName::MessageSquare))
127 .icon(menu_icon(IconName::MessageSquare))
111 .disabled(!channel_selected)
128 .disabled(!channel_selected)
112 .on_click(move |_, _, cx| {
129 .on_click(move |_, _, cx| {
@@ -116,7 +133,7 @@ impl SidebarView {
116 }),
133 }),
117 )
134 )
118 .item(
135 .item(
119 PopupMenuItem::new(NEW_CHANNEL_LABEL)
136 PopupMenuItem::new(tr("sidebar.new_channel"))
120 .icon(menu_icon(IconName::Hash))
137 .icon(menu_icon(IconName::Hash))
121 .disabled(team_id.is_none())
138 .disabled(team_id.is_none())
122 .on_click(move |_, window, cx| {
139 .on_click(move |_, window, cx| {
@@ -154,13 +171,15 @@ impl SidebarView {
154 .rounded_full()
171 .rounded_full()
155 .text_size(px(12.))
172 .text_size(px(12.))
156 .cursor_pointer()
173 .cursor_pointer()
157 .when(selected, |chip| chip.bg(theme::accent()).text_color(theme::on_accent()))
174 .when(selected, |chip| {
175 chip.bg(theme::accent()).text_color(theme::on_accent())
176 })
158 .when(!selected, |chip| {
177 .when(!selected, |chip| {
159 chip.bg(theme::surface_raised())
178 chip.bg(theme::surface_raised())
160 .text_color(theme::text_soft())
179 .text_color(theme::text_soft())
161 .hover(|chip| chip.bg(theme::border_strong()))
180 .hover(|chip| chip.bg(theme::border_strong()))
162 })
181 })
163 .child(UNREAD_PILL)
182 .child(channel_unread_pill())
164 .on_click(cx.listener(|this, _, _, cx| {
183 .on_click(cx.listener(|this, _, _, cx| {
165 this.channel_filter.unread_only = !this.channel_filter.unread_only;
184 this.channel_filter.unread_only = !this.channel_filter.unread_only;
166 cx.notify();
185 cx.notify();
crates/app/src/views/sidebar/chat_filter_bar.rs +14 −9
@@ -9,9 +9,10 @@ use gpui_kit::*;
9 9 use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10 10 use crate::app_state::Selection;
11 11 use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill,
13 FILTER_PLACEHOLDER, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
12 ChatFilterPill, filter_clear_all, filter_clear_text, filter_close_box, filter_no_matches,
13 filter_placeholder, filter_show_box, mentioned_conversations,
14 14 };
15 use crate::i18n::tr_args;
15 16 use crate::theme;
16 17 use crate::views::widgets::icon;
17 18
@@ -83,7 +84,7 @@ impl SidebarView {
83 84 if let Some(input) = &self.filter_input {
84 85 return input.clone();
85 86 }
86 let input = cx.new(|cx| InputState::new(window, cx).placeholder(FILTER_PLACEHOLDER));
87 let input = cx.new(|cx| InputState::new(window, cx).placeholder(filter_placeholder()));
87 88 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 89 if matches!(event, InputEvent::Change) {
89 90 this.chat_filter.text = input.read(cx).value().to_string();
@@ -99,9 +100,9 @@ impl SidebarView {
99 100 let open = self.filter_box_open;
100 101 let active = open || self.chat_filter.is_active();
101 102 let label = if open {
102 CLOSE_FILTER_TEXT
103 filter_close_box()
103 104 } else {
104 SHOW_FILTER_TEXT
105 filter_show_box()
105 106 };
106 107 div()
107 108 .id("chat-filter-toggle")
@@ -115,7 +116,9 @@ impl SidebarView {
115 116 .when(active, |button| button.bg(theme::popup_hover()))
116 117 .hover(|button| button.bg(theme::popup_hover()))
117 118 .tooltip(move |window, cx| {
118 Tooltip::new(format!("{label} (Ctrl+Shift+F)")).build(window, cx)
119 let mut args = std::collections::HashMap::new();
120 args.insert("label".to_owned(), label.clone());
121 Tooltip::new(tr_args("sidebar.filter.show_shortcut", &args)).build(window, cx)
119 122 })
120 123 .child(icon(
121 124 IconName::Funnel,
@@ -181,7 +184,9 @@ impl SidebarView {
181 184 .rounded(px(6.))
182 185 .cursor_pointer()
183 186 .hover(|button| button.bg(theme::popup_hover()))
184 .tooltip(|window, cx| Tooltip::new(CLEAR_FILTER_TEXT).build(window, cx))
187 .tooltip(|window, cx| {
188 Tooltip::new(filter_clear_text()).build(window, cx)
189 })
185 190 .child(icon(IconName::X, 14., theme::text_muted()))
186 191 .on_click(cx.listener(|this, _, window, cx| {
187 192 this.chat_filter.text.clear();
@@ -260,7 +265,7 @@ impl SidebarView {
260 265 div()
261 266 .text_size(px(13.))
262 267 .text_color(theme::text_muted())
263 .child(NO_MATCHES),
268 .child(filter_no_matches()),
264 269 )
265 270 .child(
266 271 div()
@@ -274,7 +279,7 @@ impl SidebarView {
274 279 .text_size(px(12.))
275 280 .text_color(theme::accent_text())
276 281 .hover(|button| button.bg(theme::surface_raised()))
277 .child(CLEAR_FILTERS)
282 .child(filter_clear_all())
278 283 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
279 284 )
280 285 }
@@ -9,9 +9,10 @@ use gpui_kit::*;
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
9use super::{NEW_CHAT_BUTTON_SIZE, SidebarEvent, SidebarTab, SidebarView};
10use crate::app_state::Selection;
10use crate::app_state::Selection;
11use crate::chat_filter::{
11use crate::chat_filter::{
12 CLEAR_FILTER_TEXT, CLEAR_FILTERS, CLOSE_FILTER_TEXT, ChatFilterPill,
12 ChatFilterPill, filter_clear_all, filter_clear_text, filter_close_box, filter_no_matches,
13 FILTER_PLACEHOLDER, NO_MATCHES, SHOW_FILTER_TEXT, mentioned_conversations,
13 filter_placeholder, filter_show_box, mentioned_conversations,
14};
14};
15use crate::i18n::tr_args;
15use crate::theme;
16use crate::theme;
16use crate::views::widgets::icon;
17use crate::views::widgets::icon;
17
18
@@ -83,7 +84,7 @@ impl SidebarView {
83 if let Some(input) = &self.filter_input {
84 if let Some(input) = &self.filter_input {
84 return input.clone();
85 return input.clone();
85 }
86 }
86 let input = cx.new(|cx| InputState::new(window, cx).placeholder(FILTER_PLACEHOLDER));
87 let input = cx.new(|cx| InputState::new(window, cx).placeholder(filter_placeholder()));
87 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 let subscription = cx.subscribe_in(&input, window, |this, input, event, _, cx| {
88 if matches!(event, InputEvent::Change) {
89 if matches!(event, InputEvent::Change) {
89 this.chat_filter.text = input.read(cx).value().to_string();
90 this.chat_filter.text = input.read(cx).value().to_string();
@@ -99,9 +100,9 @@ impl SidebarView {
99 let open = self.filter_box_open;
100 let open = self.filter_box_open;
100 let active = open || self.chat_filter.is_active();
101 let active = open || self.chat_filter.is_active();
101 let label = if open {
102 let label = if open {
102 CLOSE_FILTER_TEXT
103 filter_close_box()
103 } else {
104 } else {
104 SHOW_FILTER_TEXT
105 filter_show_box()
105 };
106 };
106 div()
107 div()
107 .id("chat-filter-toggle")
108 .id("chat-filter-toggle")
@@ -115,7 +116,9 @@ impl SidebarView {
115 .when(active, |button| button.bg(theme::popup_hover()))
116 .when(active, |button| button.bg(theme::popup_hover()))
116 .hover(|button| button.bg(theme::popup_hover()))
117 .hover(|button| button.bg(theme::popup_hover()))
117 .tooltip(move |window, cx| {
118 .tooltip(move |window, cx| {
118 Tooltip::new(format!("{label} (Ctrl+Shift+F)")).build(window, cx)
119 let mut args = std::collections::HashMap::new();
120 args.insert("label".to_owned(), label.clone());
121 Tooltip::new(tr_args("sidebar.filter.show_shortcut", &args)).build(window, cx)
119 })
122 })
120 .child(icon(
123 .child(icon(
121 IconName::Funnel,
124 IconName::Funnel,
@@ -181,7 +184,9 @@ impl SidebarView {
181 .rounded(px(6.))
184 .rounded(px(6.))
182 .cursor_pointer()
185 .cursor_pointer()
183 .hover(|button| button.bg(theme::popup_hover()))
186 .hover(|button| button.bg(theme::popup_hover()))
184 .tooltip(|window, cx| Tooltip::new(CLEAR_FILTER_TEXT).build(window, cx))
187 .tooltip(|window, cx| {
188 Tooltip::new(filter_clear_text()).build(window, cx)
189 })
185 .child(icon(IconName::X, 14., theme::text_muted()))
190 .child(icon(IconName::X, 14., theme::text_muted()))
186 .on_click(cx.listener(|this, _, window, cx| {
191 .on_click(cx.listener(|this, _, window, cx| {
187 this.chat_filter.text.clear();
192 this.chat_filter.text.clear();
@@ -260,7 +265,7 @@ impl SidebarView {
260 div()
265 div()
261 .text_size(px(13.))
266 .text_size(px(13.))
262 .text_color(theme::text_muted())
267 .text_color(theme::text_muted())
263 .child(NO_MATCHES),
268 .child(filter_no_matches()),
264 )
269 )
265 .child(
270 .child(
266 div()
271 div()
@@ -274,7 +279,7 @@ impl SidebarView {
274 .text_size(px(12.))
279 .text_size(px(12.))
275 .text_color(theme::accent_text())
280 .text_color(theme::accent_text())
276 .hover(|button| button.bg(theme::surface_raised()))
281 .hover(|button| button.bg(theme::surface_raised()))
277 .child(CLEAR_FILTERS)
282 .child(filter_clear_all())
278 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
283 .on_click(cx.listener(|this, _, window, cx| this.clear_filters(window, cx))),
279 )
284 )
280 }
285 }
crates/app/src/views/status_menu.rs +25 −24
@@ -13,8 +13,9 @@ use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKin
13 13 use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14 14 use super::widgets::{menu_icon, symbol};
15 15 use crate::app_state::AppState;
16 use crate::notify::pause;
16 use crate::i18n::tr;
17 17 use crate::data::{Person, PresenceKind};
18 use crate::notify::pause;
18 19 use crate::own_status::{
19 20 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 21 presence_kind_for, state_summary, work_location_label,
@@ -26,8 +27,6 @@ pub const MENU_WIDTH: f32 = 250.;
26 27 pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
27 28 pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
28 29 pub(crate) const SETTINGS_MORE_TAG: &str = "shell/title-bar/settings-more";
29 const SETTINGS_MORE_TITLE: &str = "Settings and more";
30 const VIEW_ACCOUNT_LABEL: &str = "View account";
31 30 const VIEW_ACCOUNT_URL: &str = "https://myaccount.microsoft.com";
32 31 const TITLE_PRESENCE_SIZE: f32 = 14.;
33 32 const HEADER_AVATAR_SIZE: f32 = 40.;
@@ -170,7 +169,7 @@ fn header(context: &MenuContext, cx: &App) -> Div {
170 169 .text_size(px(12.))
171 170 .text_color(theme::text_soft())
172 171 .hover(|link| link.text_color(theme::accent_text()))
173 .child(VIEW_ACCOUNT_LABEL)
172 .child(tr("status_menu.view_account"))
174 173 .child(menu_icon(IconName::ExternalLink).size(px(12.)))
175 174 .on_click(|_, _, cx| cx.open_url(VIEW_ACCOUNT_URL)),
176 175 )
@@ -212,7 +211,7 @@ fn status_menu(
212 211 .item(pause_item(&context.app, window, cx))
213 212 .item(work_location_item(context, window, cx))
214 213 .item(
215 PopupMenuItem::new("Set status message")
214 PopupMenuItem::new(tr("status_menu.set_status_message"))
216 215 .icon(menu_icon(IconName::Pencil))
217 216 .on_click(move |_, _, cx| {
218 217 message_app.update(cx, |state, cx| state.request_status_message(cx));
@@ -234,16 +233,18 @@ fn pause_item(
234 233 let menu = STATUS_DURATIONS.iter().fold(menu, |menu, duration| {
235 234 let app = app.clone();
236 235 let duration = *duration;
237 menu.item(PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
238 let until = duration.expires_at(Local::now());
239 app.update(cx, |state, cx| state.pause_notifications(until, cx));
240 }))
236 menu.item(
237 PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
238 let until = duration.expires_at(Local::now());
239 app.update(cx, |state, cx| state.pause_notifications(until, cx));
240 }),
241 )
241 242 });
242 243 if !paused {
243 244 return menu;
244 245 }
245 246 menu.separator().item(
246 PopupMenuItem::new("Resume notifications")
247 PopupMenuItem::new(tr("status_menu.resume_notifications"))
247 248 .icon(menu_icon(IconName::BellRing))
248 249 .on_click(move |_, _, cx| {
249 250 resume_app.update(cx, |state, cx| state.resume_notifications(cx));
@@ -266,7 +267,7 @@ pub fn settings_more_button(app: &Entity<AppState>) -> AnyElement {
266 267 Button::new("title-settings-more")
267 268 .ghost()
268 269 .icon(IconName::Ellipsis)
269 .tooltip(SETTINGS_MORE_TITLE)
270 .tooltip(tr("shell.settings_and_more"))
270 271 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
271 272 settings_more_menu(popup, window, cx, &app)
272 273 }),
@@ -291,7 +292,7 @@ fn settings_more_menu(
291 292 let popup = popup
292 293 .min_w(px(MENU_WIDTH))
293 294 .item(
294 PopupMenuItem::new("Settings")
295 PopupMenuItem::new(tr("common.settings"))
295 296 .icon(menu_icon(IconName::Settings))
296 297 .on_click(move |_, _, cx| {
297 298 settings_app.update(cx, |state, cx| {
@@ -301,7 +302,7 @@ fn settings_more_menu(
301 302 )
302 303 .separator()
303 304 .item(
304 PopupMenuItem::new("Chat list")
305 PopupMenuItem::new(tr("status_menu.chat_list"))
305 306 .icon(menu_icon(IconName::LayoutList))
306 307 .on_click(move |_, _, cx| {
307 308 chat_list_app.update(cx, |state, cx| {
@@ -310,7 +311,7 @@ fn settings_more_menu(
310 311 }),
311 312 )
312 313 .item(
313 PopupMenuItem::new("Translation")
314 PopupMenuItem::new(tr("status_menu.translation"))
314 315 .icon(menu_icon(IconName::Languages))
315 316 .on_click(move |_, _, cx| {
316 317 translation_app.update(cx, |state, cx| {
@@ -319,7 +320,7 @@ fn settings_more_menu(
319 320 }),
320 321 )
321 322 .item(
322 PopupMenuItem::new("Notification settings")
323 PopupMenuItem::new(tr("status_menu.notification_settings"))
323 324 .icon(menu_icon(IconName::Bell))
324 325 .on_click(move |_, _, cx| {
325 326 notification_app.update(cx, |state, cx| {
@@ -328,7 +329,7 @@ fn settings_more_menu(
328 329 }),
329 330 )
330 331 .item(
331 PopupMenuItem::new("Make a test call")
332 PopupMenuItem::new(tr("status_menu.test_call"))
332 333 .icon(menu_icon(IconName::Phone))
333 334 .on_click(move |_, _, cx| {
334 335 call_app.update(cx, |state, cx| state.start_test_call(cx));
@@ -341,7 +342,7 @@ fn settings_more_menu(
341 342 return popup;
342 343 }
343 344 popup.item(
344 PopupMenuItem::new("Simulate incoming call")
345 PopupMenuItem::new(tr("status_menu.simulate_incoming"))
345 346 .icon(menu_icon(IconName::Phone))
346 347 .on_click(move |_, _, cx| {
347 348 ring_app.update(cx, |state, cx| state.demo_incoming_ring(cx));
@@ -365,7 +366,7 @@ fn work_location_item(
365 366 let current = context.status.work_location;
366 367 let app = context.app.clone();
367 368 let submenu = PopupMenu::build(window, cx, move |menu, _, _| {
368 let pick = |label: &'static str, kind: WorkLocationKind| {
369 let pick = |label: String, kind: WorkLocationKind| {
369 370 let app = app.clone();
370 371 PopupMenuItem::new(label)
371 372 .icon(work_location_icon(Some(kind)))
@@ -375,14 +376,14 @@ fn work_location_item(
375 376 };
376 377 let clear_app = app.clone();
377 378 let menu = menu
378 .item(PopupMenuItem::label("Set work location for today"))
379 .item(pick("Office", WorkLocationKind::Office))
380 .item(pick("Remote", WorkLocationKind::Remote));
379 .item(PopupMenuItem::label(tr("status_menu.work_location_today")))
380 .item(pick(tr("status_menu.office"), WorkLocationKind::Office))
381 .item(pick(tr("status_menu.remote"), WorkLocationKind::Remote));
381 382 if current.is_none() {
382 383 return menu;
383 384 }
384 385 menu.separator().item(
385 PopupMenuItem::new("Clear work location")
386 PopupMenuItem::new(tr("status_menu.clear_work_location"))
386 387 .icon(menu_icon(IconName::X))
387 388 .on_click(move |_, _, cx| {
388 389 clear_app.update(cx, |state, cx| state.set_own_work_location(None, cx));
@@ -427,12 +428,12 @@ fn state_menu(
427 428 popup
428 429 .separator()
429 430 .item(
430 PopupMenuItem::submenu("Duration", durations)
431 PopupMenuItem::submenu(tr("status_menu.duration"), durations)
431 432 .icon(menu_icon(IconName::Clock))
432 433 .disabled(target.is_none()),
433 434 )
434 435 .item(
435 PopupMenuItem::new("Reset status")
436 PopupMenuItem::new(tr("status_menu.reset_status"))
436 437 .icon(menu_icon(IconName::RotateCcw))
437 438 .on_click(move |_, _, cx| {
438 439 reset_app.update(cx, |state, cx| state.set_own_availability(None, cx));
@@ -13,8 +13,9 @@ use teams_core::{ForcedAvailability, ForcedKind, PresenceStatus, WorkLocationKin
13use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
13use super::avatar::{person_avatar, status_glyph, with_presence, with_presence_badge};
14use super::widgets::{menu_icon, symbol};
14use super::widgets::{menu_icon, symbol};
15use crate::app_state::AppState;
15use crate::app_state::AppState;
16use crate::notify::pause;
16use crate::i18n::tr;
17use crate::data::{Person, PresenceKind};
17use crate::data::{Person, PresenceKind};
18use crate::notify::pause;
18use crate::own_status::{
19use crate::own_status::{
19 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 STATUS_CHOICES, STATUS_DURATIONS, StateSummary, StatusDuration, choice_label, duration_target,
20 presence_kind_for, state_summary, work_location_label,
21 presence_kind_for, state_summary, work_location_label,
@@ -26,8 +27,6 @@ pub const MENU_WIDTH: f32 = 250.;
26pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
27pub(crate) const TITLE_AVATAR_SIZE: f32 = 28.;
27pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
28pub(crate) const OWN_AVATAR_DISC: &str = "shell/title-bar/own-status/avatar/disc";
28pub(crate) const SETTINGS_MORE_TAG: &str = "shell/title-bar/settings-more";
29pub(crate) const SETTINGS_MORE_TAG: &str = "shell/title-bar/settings-more";
29const SETTINGS_MORE_TITLE: &str = "Settings and more";
30const VIEW_ACCOUNT_LABEL: &str = "View account";
31const VIEW_ACCOUNT_URL: &str = "https://myaccount.microsoft.com";
30const VIEW_ACCOUNT_URL: &str = "https://myaccount.microsoft.com";
32const TITLE_PRESENCE_SIZE: f32 = 14.;
31const TITLE_PRESENCE_SIZE: f32 = 14.;
33const HEADER_AVATAR_SIZE: f32 = 40.;
32const HEADER_AVATAR_SIZE: f32 = 40.;
@@ -170,7 +169,7 @@ fn header(context: &MenuContext, cx: &App) -> Div {
170 .text_size(px(12.))
169 .text_size(px(12.))
171 .text_color(theme::text_soft())
170 .text_color(theme::text_soft())
172 .hover(|link| link.text_color(theme::accent_text()))
171 .hover(|link| link.text_color(theme::accent_text()))
173 .child(VIEW_ACCOUNT_LABEL)
172 .child(tr("status_menu.view_account"))
174 .child(menu_icon(IconName::ExternalLink).size(px(12.)))
173 .child(menu_icon(IconName::ExternalLink).size(px(12.)))
175 .on_click(|_, _, cx| cx.open_url(VIEW_ACCOUNT_URL)),
174 .on_click(|_, _, cx| cx.open_url(VIEW_ACCOUNT_URL)),
176 )
175 )
@@ -212,7 +211,7 @@ fn status_menu(
212 .item(pause_item(&context.app, window, cx))
211 .item(pause_item(&context.app, window, cx))
213 .item(work_location_item(context, window, cx))
212 .item(work_location_item(context, window, cx))
214 .item(
213 .item(
215 PopupMenuItem::new("Set status message")
214 PopupMenuItem::new(tr("status_menu.set_status_message"))
216 .icon(menu_icon(IconName::Pencil))
215 .icon(menu_icon(IconName::Pencil))
217 .on_click(move |_, _, cx| {
216 .on_click(move |_, _, cx| {
218 message_app.update(cx, |state, cx| state.request_status_message(cx));
217 message_app.update(cx, |state, cx| state.request_status_message(cx));
@@ -234,16 +233,18 @@ fn pause_item(
234 let menu = STATUS_DURATIONS.iter().fold(menu, |menu, duration| {
233 let menu = STATUS_DURATIONS.iter().fold(menu, |menu, duration| {
235 let app = app.clone();
234 let app = app.clone();
236 let duration = *duration;
235 let duration = *duration;
237 menu.item(PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
236 menu.item(
238 let until = duration.expires_at(Local::now());
237 PopupMenuItem::new(duration.label()).on_click(move |_, _, cx| {
239 app.update(cx, |state, cx| state.pause_notifications(until, cx));
238 let until = duration.expires_at(Local::now());
240 }))
239 app.update(cx, |state, cx| state.pause_notifications(until, cx));
240 }),
241 )
241 });
242 });
242 if !paused {
243 if !paused {
243 return menu;
244 return menu;
244 }
245 }
245 menu.separator().item(
246 menu.separator().item(
246 PopupMenuItem::new("Resume notifications")
247 PopupMenuItem::new(tr("status_menu.resume_notifications"))
247 .icon(menu_icon(IconName::BellRing))
248 .icon(menu_icon(IconName::BellRing))
248 .on_click(move |_, _, cx| {
249 .on_click(move |_, _, cx| {
249 resume_app.update(cx, |state, cx| state.resume_notifications(cx));
250 resume_app.update(cx, |state, cx| state.resume_notifications(cx));
@@ -266,7 +267,7 @@ pub fn settings_more_button(app: &Entity<AppState>) -> AnyElement {
266 Button::new("title-settings-more")
267 Button::new("title-settings-more")
267 .ghost()
268 .ghost()
268 .icon(IconName::Ellipsis)
269 .icon(IconName::Ellipsis)
269 .tooltip(SETTINGS_MORE_TITLE)
270 .tooltip(tr("shell.settings_and_more"))
270 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
271 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, window, cx| {
271 settings_more_menu(popup, window, cx, &app)
272 settings_more_menu(popup, window, cx, &app)
272 }),
273 }),
@@ -291,7 +292,7 @@ fn settings_more_menu(
291 let popup = popup
292 let popup = popup
292 .min_w(px(MENU_WIDTH))
293 .min_w(px(MENU_WIDTH))
293 .item(
294 .item(
294 PopupMenuItem::new("Settings")
295 PopupMenuItem::new(tr("common.settings"))
295 .icon(menu_icon(IconName::Settings))
296 .icon(menu_icon(IconName::Settings))
296 .on_click(move |_, _, cx| {
297 .on_click(move |_, _, cx| {
297 settings_app.update(cx, |state, cx| {
298 settings_app.update(cx, |state, cx| {
@@ -301,7 +302,7 @@ fn settings_more_menu(
301 )
302 )
302 .separator()
303 .separator()
303 .item(
304 .item(
304 PopupMenuItem::new("Chat list")
305 PopupMenuItem::new(tr("status_menu.chat_list"))
305 .icon(menu_icon(IconName::LayoutList))
306 .icon(menu_icon(IconName::LayoutList))
306 .on_click(move |_, _, cx| {
307 .on_click(move |_, _, cx| {
307 chat_list_app.update(cx, |state, cx| {
308 chat_list_app.update(cx, |state, cx| {
@@ -310,7 +311,7 @@ fn settings_more_menu(
310 }),
311 }),
311 )
312 )
312 .item(
313 .item(
313 PopupMenuItem::new("Translation")
314 PopupMenuItem::new(tr("status_menu.translation"))
314 .icon(menu_icon(IconName::Languages))
315 .icon(menu_icon(IconName::Languages))
315 .on_click(move |_, _, cx| {
316 .on_click(move |_, _, cx| {
316 translation_app.update(cx, |state, cx| {
317 translation_app.update(cx, |state, cx| {
@@ -319,7 +320,7 @@ fn settings_more_menu(
319 }),
320 }),
320 )
321 )
321 .item(
322 .item(
322 PopupMenuItem::new("Notification settings")
323 PopupMenuItem::new(tr("status_menu.notification_settings"))
323 .icon(menu_icon(IconName::Bell))
324 .icon(menu_icon(IconName::Bell))
324 .on_click(move |_, _, cx| {
325 .on_click(move |_, _, cx| {
325 notification_app.update(cx, |state, cx| {
326 notification_app.update(cx, |state, cx| {
@@ -328,7 +329,7 @@ fn settings_more_menu(
328 }),
329 }),
329 )
330 )
330 .item(
331 .item(
331 PopupMenuItem::new("Make a test call")
332 PopupMenuItem::new(tr("status_menu.test_call"))
332 .icon(menu_icon(IconName::Phone))
333 .icon(menu_icon(IconName::Phone))
333 .on_click(move |_, _, cx| {
334 .on_click(move |_, _, cx| {
334 call_app.update(cx, |state, cx| state.start_test_call(cx));
335 call_app.update(cx, |state, cx| state.start_test_call(cx));
@@ -341,7 +342,7 @@ fn settings_more_menu(
341 return popup;
342 return popup;
342 }
343 }
343 popup.item(
344 popup.item(
344 PopupMenuItem::new("Simulate incoming call")
345 PopupMenuItem::new(tr("status_menu.simulate_incoming"))
345 .icon(menu_icon(IconName::Phone))
346 .icon(menu_icon(IconName::Phone))
346 .on_click(move |_, _, cx| {
347 .on_click(move |_, _, cx| {
347 ring_app.update(cx, |state, cx| state.demo_incoming_ring(cx));
348 ring_app.update(cx, |state, cx| state.demo_incoming_ring(cx));
@@ -365,7 +366,7 @@ fn work_location_item(
365 let current = context.status.work_location;
366 let current = context.status.work_location;
366 let app = context.app.clone();
367 let app = context.app.clone();
367 let submenu = PopupMenu::build(window, cx, move |menu, _, _| {
368 let submenu = PopupMenu::build(window, cx, move |menu, _, _| {
368 let pick = |label: &'static str, kind: WorkLocationKind| {
369 let pick = |label: String, kind: WorkLocationKind| {
369 let app = app.clone();
370 let app = app.clone();
370 PopupMenuItem::new(label)
371 PopupMenuItem::new(label)
371 .icon(work_location_icon(Some(kind)))
372 .icon(work_location_icon(Some(kind)))
@@ -375,14 +376,14 @@ fn work_location_item(
375 };
376 };
376 let clear_app = app.clone();
377 let clear_app = app.clone();
377 let menu = menu
378 let menu = menu
378 .item(PopupMenuItem::label("Set work location for today"))
379 .item(PopupMenuItem::label(tr("status_menu.work_location_today")))
379 .item(pick("Office", WorkLocationKind::Office))
380 .item(pick(tr("status_menu.office"), WorkLocationKind::Office))
380 .item(pick("Remote", WorkLocationKind::Remote));
381 .item(pick(tr("status_menu.remote"), WorkLocationKind::Remote));
381 if current.is_none() {
382 if current.is_none() {
382 return menu;
383 return menu;
383 }
384 }
384 menu.separator().item(
385 menu.separator().item(
385 PopupMenuItem::new("Clear work location")
386 PopupMenuItem::new(tr("status_menu.clear_work_location"))
386 .icon(menu_icon(IconName::X))
387 .icon(menu_icon(IconName::X))
387 .on_click(move |_, _, cx| {
388 .on_click(move |_, _, cx| {
388 clear_app.update(cx, |state, cx| state.set_own_work_location(None, cx));
389 clear_app.update(cx, |state, cx| state.set_own_work_location(None, cx));
@@ -427,12 +428,12 @@ fn state_menu(
427 popup
428 popup
428 .separator()
429 .separator()
429 .item(
430 .item(
430 PopupMenuItem::submenu("Duration", durations)
431 PopupMenuItem::submenu(tr("status_menu.duration"), durations)
431 .icon(menu_icon(IconName::Clock))
432 .icon(menu_icon(IconName::Clock))
432 .disabled(target.is_none()),
433 .disabled(target.is_none()),
433 )
434 )
434 .item(
435 .item(
435 PopupMenuItem::new("Reset status")
436 PopupMenuItem::new(tr("status_menu.reset_status"))
436 .icon(menu_icon(IconName::RotateCcw))
437 .icon(menu_icon(IconName::RotateCcw))
437 .on_click(move |_, _, cx| {
438 .on_click(move |_, _, cx| {
438 reset_app.update(cx, |state, cx| state.set_own_availability(None, cx));
439 reset_app.update(cx, |state, cx| state.set_own_availability(None, cx));
crates/app/src/views/status_message_dialog.rs +2 −1
@@ -13,6 +13,7 @@ use gpui_kit::*;
13 13 use teams_core::StatusNote;
14 14
15 15 use super::widgets::symbol;
16 use crate::i18n::tr;
16 17 use crate::app_state::AppState;
17 18 use crate::own_status::{NOTE_DURATIONS, NOTE_LIMIT, NoteDuration, clamp_note};
18 19 use crate::theme::{self, ElevatedSurface as _};
@@ -300,7 +301,7 @@ impl Render for StatusMessageDialog {
300 301 .child(
301 302 Button::new("status-message-cancel")
302 303 .ghost()
303 .label("Cancel")
304 .label(tr("common.cancel"))
304 305 .on_click(cx.listener(|_, _, _, cx| {
305 306 cx.emit(StatusMessageDialogEvent::Close)
306 307 })),
@@ -13,6 +13,7 @@ use gpui_kit::*;
13use teams_core::StatusNote;
13use teams_core::StatusNote;
14
14
15use super::widgets::symbol;
15use super::widgets::symbol;
16use crate::i18n::tr;
16use crate::app_state::AppState;
17use crate::app_state::AppState;
17use crate::own_status::{NOTE_DURATIONS, NOTE_LIMIT, NoteDuration, clamp_note};
18use crate::own_status::{NOTE_DURATIONS, NOTE_LIMIT, NoteDuration, clamp_note};
18use crate::theme::{self, ElevatedSurface as _};
19use crate::theme::{self, ElevatedSurface as _};
@@ -300,7 +301,7 @@ impl Render for StatusMessageDialog {
300 .child(
301 .child(
301 Button::new("status-message-cancel")
302 Button::new("status-message-cancel")
302 .ghost()
303 .ghost()
303 .label("Cancel")
304 .label(tr("common.cancel"))
304 .on_click(cx.listener(|_, _, _, cx| {
305 .on_click(cx.listener(|_, _, _, cx| {
305 cx.emit(StatusMessageDialogEvent::Close)
306 cx.emit(StatusMessageDialogEvent::Close)
306 })),
307 })),
crates/app/src/views/transfer_picker.rs +2 −1
@@ -12,6 +12,7 @@ use gpui_kit::*;
12 12 use super::avatar::person_avatar;
13 13 use super::switcher::clamp_highlight;
14 14 use super::widgets::icon;
15 use crate::i18n::tr;
15 16 use crate::app_state::AppState;
16 17 use crate::call::TransferCandidate;
17 18 use crate::fuzzy;
@@ -228,7 +229,7 @@ impl Render for TransferPicker {
228 229 .child(
229 230 Button::new("transfer-cancel")
230 231 .ghost()
231 .label("Cancel")
232 .label(tr("common.cancel"))
232 233 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
233 234 )
234 235 .children(match self.mode {
@@ -12,6 +12,7 @@ use gpui_kit::*;
12use super::avatar::person_avatar;
12use super::avatar::person_avatar;
13use super::switcher::clamp_highlight;
13use super::switcher::clamp_highlight;
14use super::widgets::icon;
14use super::widgets::icon;
15use crate::i18n::tr;
15use crate::app_state::AppState;
16use crate::app_state::AppState;
16use crate::call::TransferCandidate;
17use crate::call::TransferCandidate;
17use crate::fuzzy;
18use crate::fuzzy;
@@ -228,7 +229,7 @@ impl Render for TransferPicker {
228 .child(
229 .child(
229 Button::new("transfer-cancel")
230 Button::new("transfer-cancel")
230 .ghost()
231 .ghost()
231 .label("Cancel")
232 .label(tr("common.cancel"))
232 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
233 .on_click(cx.listener(|this, _, _, cx| this.close(cx))),
233 )
234 )
234 .children(match self.mode {
235 .children(match self.mode {
crates/calling/src/call.rs +1359 −360
@@ -1,7 +1,7 @@
1 1 use std::collections::BTreeMap;
2 2 use std::path::PathBuf;
3 3 use std::sync::Arc;
4 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4 use std::sync::atomic::{AtomicBool, Ordering};
5 5 use std::time::Duration;
6 6
7 7 use chatsvc::TrouterCallback;
@@ -24,51 +24,86 @@ use crate::background::{BackgroundChoice, BackgroundPicture};
24 24 use crate::breakout::{self, RoomWatcher};
25 25 use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
26 26 use crate::camera::{CameraDevice, list_cameras};
27 use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
27 28 use crate::captions::{
28 29 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
29 30 parse_caption_message,
30 31 };
31 32 use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
32 use crate::diagnostics::{CallDiagnostics, StatsSample};
33 33 use crate::data_channel::Depacketizer;
34 34 use crate::device_watch::{self, Debounce};
35 35 use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
36 use crate::diagnostics::{CallDiagnostics, StatsSample};
36 37 use crate::end::EndKind;
37 38 use crate::engine::{CallEngine, EngineConfig, Inner};
38 39 use crate::error::{Error, Result};
39 use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
40 use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, offer_sends_video, rewrite_directions, stop_sending_on};
40 use crate::health::{
41 CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats,
42 };
43 use crate::hold::{
44 HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, is_hold, keep_media_running,
45 offer_modalities, offer_sends_video, rewrite_directions, stop_sending_on,
46 };
47 use crate::meeting_options::{self, OptionWrite};
41 48 use crate::mic_processing::MicSettings;
42 49 use crate::mute::{MuteCommand, MuteEffect};
43 use crate::push::CallNotification;
44 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
45 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
46 use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
47 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
50 use crate::notices::{
51 ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,
52 BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,
53 CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTIONS_JOIN_FAILED_NOTICE,
54 CAPTION_LANGUAGE_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE, CHANGE_RUNNING_NOTICE,
55 CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE, DENY_FAILED_NOTICE,
56 HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE,
57 LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE,
58 MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE,
59 MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE,
60 RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE,
61 CAPTIONS_START_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE, RECORDING_NOT_STARTED_NOTICE,
62 RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,
63 REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,
64 SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,
65 STOP_SPOTLIGHT_FAILED_NOTICE, TRANSFER_CALL_FAILED_NOTICE, TRANSFER_FAILED_NOTICE,
66 TRANSFER_NOT_ALLOWED_NOTICE, TRANSFERRING_NOTICE, VIDEO_FAILED_NOTICE,
67 WHITEBOARD_OPEN_FAILED_NOTICE, WHITEBOARDS_MEETINGS_ONLY_NOTICE, notice_with_detail,
68 };
48 69 use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
49 use crate::meeting_options::{self, OptionWrite};
70 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
71 use crate::push::CallNotification;
50 72 use crate::recording::{Consent, RecordingPlan, RecordingStatus};
73 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
74 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
51 75 use crate::roster::{Roster, direct_roster};
52 use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
76 use crate::screen::{
77 ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources,
78 share_sources_for_menu, share_thumbnail,
79 };
80 use crate::sdp::{
81 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
82 to_browser_answer, to_teams_answer, to_teams_offer,
83 };
84 use crate::send_control::{RequestFilter, parse_request};
53 85 use crate::signaling::{
54 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
55 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
86 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
87 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
88 escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body,
56 89 };
57 90 use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
58 91 use crate::state::{CallSignal, CallState};
59 92 use crate::timeline::{Timeline, TimelineEntry};
60 93 use crate::transfer::{Replacement, TransferEvent, TransferTarget};
94 use crate::trouter_events::{
95 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
96 };
61 97 use crate::video_frame::{VideoKey, VideoPicture};
62 98 use crate::video_layout::{
63 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
99 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter,
100 SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines,
101 offer_plan, one_to_one_plan,
64 102 };
65 use crate::send_control::{RequestFilter, parse_request};
66 use crate::video_send::{LocalVideo, SendSource, VideoMode};
67 use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
68 use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
69 use crate::trouter_events::{
70 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
103 use crate::video_receive::{
104 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
71 105 };
106 use crate::video_send::{LocalVideo, SendSource, VideoMode};
72 107 use crate::whiteboard;
73 108
74 109 const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
@@ -92,15 +127,16 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
92 127 const BOT_PREFIX: &str = "28:";
93 128 const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
94 129 const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
130 /// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends.
131 const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15);
95 132 const GATHERING_LIMIT: Duration = Duration::from_secs(5);
96 const RELAY_SETTLE: Duration = Duration::from_millis(200);
133 const GATHERING_QUIET: Duration = Duration::from_millis(500);
97 134 const GATHERING_POLL: Duration = Duration::from_millis(50);
98 135 const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
99 136 const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
100 137 const GLARE_CODE: i64 = 491;
101 138 const RETARGET_WAIT: Duration = Duration::from_secs(20);
102 139 const CAMERA_STREAM: &str = "camera";
103 const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
104 140
105 141 #[derive(Debug, Clone)]
106 142 pub struct CallOptions {
@@ -199,7 +235,10 @@ pub struct CallReport {
199 235 #[derive(Debug, Clone)]
200 236 pub enum CallSpec {
201 237 Echo,
202 People { callees: Vec<Callee>, thread_id: String },
238 People {
239 callees: Vec<Callee>,
240 thread_id: String,
241 },
203 242 Meeting(MeetingTarget),
204 243 }
205 244
@@ -247,11 +286,16 @@ pub(crate) enum Plan {
247 286 }
248 287
249 288 fn data_channel_from_env() -> bool {
250 !matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))
289 !matches!(
290 std::env::var(DATA_CHANNEL_ENV).ok().as_deref(),
291 Some("0" | "off")
292 )
251 293 }
252 294
253 295 pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
254 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
296 let seconds = seconds
297 .unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS)
298 .max(MIN_KEEP_ALIVE_SECONDS);
255 299 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
256 300 }
257 301
@@ -286,19 +330,19 @@ struct PeerSession {
286 330 struct Gathered {
287 331 candidates: Arc<std::sync::Mutex<Vec<String>>>,
288 332 complete: Arc<AtomicBool>,
289 relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
290 waited_ms: Arc<AtomicU64>,
291 }
292
293 /// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
294 fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
295 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
333 relay_seen: Arc<AtomicBool>,
334 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
296 335 }
297 336
298 337 impl Gathered {
338 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
299 339 fn settled(&self) -> bool {
300 let since_udp_relay = self.relay_seen_at.lock().expect("relay time lock").map(|at| at.elapsed());
301 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
340 let quiet = self
341 .last_candidate
342 .lock()
343 .expect("candidate time lock")
344 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
345 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
302 346 }
303 347
304 348 async fn candidates(&self) -> Vec<String> {
@@ -307,14 +351,8 @@ impl Gathered {
307 351 tokio::time::sleep(GATHERING_POLL).await;
308 352 }
309 353 self.complete.store(true, Ordering::SeqCst);
310 self.waited_ms.store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
311 354 self.candidates.lock().expect("candidates lock").clone()
312 355 }
313
314 fn summary(&self) -> String {
315 let count = self.candidates.lock().expect("candidates lock").len();
316 format!("{count} candidate(s) after {} ms", self.waited_ms.load(Ordering::SeqCst))
317 }
318 356 }
319 357
320 358 async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
@@ -439,14 +477,22 @@ pub async fn run_test_call(
439 477 endpoint_storage_key: "__testCallEpid".into(),
440 478 },
441 479 };
442 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
443 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
480 let (engine, _events) =
481 CallEngine::start(session.clone(), poll_session.clone(), config).await?;
482 let report = engine
483 .run(Plan::Outgoing(CallSpec::Echo), options, control)
484 .await;
444 485 engine.stop().await;
445 486 report
446 487 }
447 488
448 489 impl CallEngine {
449 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
490 pub(crate) async fn run(
491 &self,
492 plan: Plan,
493 options: CallOptions,
494 mut control: CallControl,
495 ) -> Result<CallReport> {
450 496 let inner = self.inner.as_ref();
451 497 let _one_call_at_a_time = if options.concurrent {
452 498 None
@@ -463,7 +509,14 @@ impl CallEngine {
463 509 };
464 510 let timeline = Timeline::new(options.trace);
465 511 let stay_awake = crate::awake::StayAwake::new();
466 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
512 timeline.record(
513 "stay awake",
514 if stay_awake.holding() {
515 "system and display kept awake"
516 } else {
517 "not available"
518 },
519 );
467 520 let mut report = CallReport::default();
468 521 let mut state = CallState::Idle;
469 522 advance(&mut state, CallSignal::Dial, &control);
@@ -493,14 +546,24 @@ impl CallEngine {
493 546 }
494 547 };
495 548 dump_timeline(&options, &timeline, failure.as_ref());
496 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
549 let cancelled = live.cancel_leave
550 || matches!(
551 &state,
552 CallState::Ended {
553 reason: crate::state::EndReason::Cancelled
554 }
555 );
497 556 tear_down(live, inner, &timeline, &mut report, cancelled).await;
498 557 let recording = recording.lock().await;
499 558 report.recorded_samples = recording.samples.len();
500 559 report.timeline = timeline.entries();
501 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
560 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(
561 &report,
562 timeline.sdp_summaries(),
563 ))));
502 564 if let Some(path) = &options.wav_path {
503 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
565 write_wav(path, &recording.samples)
566 .map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
504 567 }
505 568 match failure {
506 569 Some(error) => Err(error),
@@ -509,23 +572,32 @@ impl CallEngine {
509 572 }
510 573 }
511 574
512 fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {
575 fn open_peer(
576 factory: &PeerConnectionFactory,
577 grant: &RelayGrant,
578 relay_host: &str,
579 with_data_channel: bool,
580 ) -> Result<PeerSession> {
513 581 let mut configuration = RtcConfiguration::default();
514 582 configuration.ice_servers = vec![grant.ice_server(relay_host)];
515 583 let peer = factory
516 584 .create_peer_connection(configuration)
517 585 .map_err(|error| Error::Webrtc(error.to_string()))?;
518 586 let (sender, events) = mpsc::unbounded_channel();
519 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
587 let data_channel = with_data_channel
588 .then(|| open_data_channel(&peer, sender.clone()))
589 .transpose()?;
520 590 let gathered = Gathered::default();
521 591 let candidate_sink = gathered.candidates.clone();
522 let relay_seen_at = gathered.relay_seen_at.clone();
592 let relay_seen = gathered.relay_seen.clone();
593 let last_candidate = gathered.last_candidate.clone();
523 594 peer.on_ice_candidate(Some(Box::new(move |candidate| {
524 595 if candidate.sdp_mline_index() == 0 {
525 596 let text = candidate.candidate();
526 597 if is_udp_relay(&text) {
527 relay_seen_at.lock().expect("relay time lock").get_or_insert_with(Instant::now);
598 relay_seen.store(true, Ordering::SeqCst);
528 599 }
600 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
529 601 candidate_sink.lock().expect("candidates lock").push(text);
530 602 }
531 603 })));
@@ -552,10 +624,18 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
552 624 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
553 625 }
554 626 })));
555 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
627 Ok(PeerSession {
628 peer,
629 events,
630 _data_channel: data_channel,
631 gathered,
632 })
556 633 }
557 634
558 fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
635 fn open_data_channel(
636 peer: &PeerConnection,
637 sender: mpsc::UnboundedSender<PeerEvent>,
638 ) -> Result<DataChannel> {
559 639 let channel = peer
560 640 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
561 641 .map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -565,7 +645,13 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
565 645 Ok(channel)
566 646 }
567 647
568 fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
648 fn one_to_one_directions<'a>(
649 camera: bool,
650 share: bool,
651 camera_mid: &'a str,
652 share_mid: Option<&'a str>,
653 remote_shares: bool,
654 ) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
569 655 move |line| match line.kind {
570 656 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
571 657 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
@@ -593,15 +679,33 @@ fn share_mid_in(offer_text: &str) -> Option<String> {
593 679 }
594 680
595 681 #[allow(clippy::too_many_arguments)]
596 fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
682 fn directions_for(
683 layout: Layout,
684 hold: bool,
685 camera: bool,
686 share: bool,
687 camera_mid: &str,
688 share_mid: Option<&str>,
689 remote_shares: bool,
690 text: &str,
691 ) -> String {
597 692 match (hold, layout) {
598 693 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
599 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
694 (false, Layout::OneToOne) => rewrite_directions(
695 text,
696 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
697 ),
600 698 (false, Layout::Conference) => text.to_owned(),
601 699 }
602 700 }
603 701
604 async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
702 async fn create_offer(
703 peer: &PeerConnection,
704 factory: &PeerConnectionFactory,
705 track: &RtcAudioTrack,
706 layout: Layout,
707 gathered: Option<&Gathered>,
708 ) -> Result<OfferedMedia> {
605 709 let transceiver_init = RtpTransceiverInit {
606 710 direction: RtpTransceiverDirection::SendRecv,
607 711 stream_ids: vec![MIC_STREAM.into()],
@@ -621,7 +725,16 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
621 725 })
622 726 .await
623 727 .map_err(|error| Error::Webrtc(error.to_string()))?;
624 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
728 let browser_offer = directions_for(
729 layout,
730 false,
731 false,
732 false,
733 CAMERA_MID,
734 Some(ONE_TO_ONE_SHARE_MID),
735 false,
736 &offer.to_string(),
737 );
625 738 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
626 739 peer.set_local_description(description)
627 740 .await
@@ -629,7 +742,13 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
629 742 let mut numbers = random_u32;
630 743 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
631 744 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
632 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
745 Ok(OfferedMedia {
746 browser_offer,
747 signaled,
748 video,
749 plan,
750 modalities: accepted_modalities(false),
751 })
633 752 }
634 753
635 754 struct AnsweredMedia {
@@ -640,11 +759,20 @@ struct AnsweredMedia {
640 759 }
641 760
642 761 fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
643 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
762 remote
763 .lines
764 .iter()
765 .find(|line| line.role == LineRole::MainVideo)
766 .and_then(|line| line.browser_mids.first().cloned())
644 767 }
645 768
646 769 fn share_mids(remote: &RemoteOffer) -> Vec<String> {
647 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
770 remote
771 .lines
772 .iter()
773 .filter(|line| line.role == LineRole::ScreenShare)
774 .filter_map(|line| line.browser_mids.first().cloned())
775 .collect()
648 776 }
649 777
650 778 async fn answer_offer(
@@ -658,17 +786,32 @@ async fn answer_offer(
658 786 ) -> Result<AnsweredMedia> {
659 787 let remote = from_teams_offer(teams_offer)?;
660 788 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
661 peer.set_remote_description(description).await.map_err(|error| {
662 let lines: Vec<String> = remote.lines.iter().map(|line| format!("{:?}{:?}", line.role, line.browser_mids)).collect();
663 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
664 })?;
789 peer.set_remote_description(description)
790 .await
791 .map_err(|error| {
792 let lines: Vec<String> = remote
793 .lines
794 .iter()
795 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
796 .collect();
797 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
798 })?;
665 799 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
666 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
800 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
801 Vec::new()
802 } else {
803 share_mids(&remote)
804 };
667 805 for transceiver in peer.transceivers() {
668 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
669 let unused = transceiver
670 .mid()
671 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
806 let is_video = matches!(
807 transceiver.receiver().track(),
808 Some(MediaStreamTrack::Video(_))
809 );
810 let unused = transceiver.mid().is_some_and(|mid| {
811 Some(&mid) != camera_mid.as_ref()
812 && !kept_share_mids.contains(&mid)
813 && Some(&mid) != sending_share_mid.as_ref()
814 });
672 815 if is_video && unused {
673 816 let _ = transceiver.stop();
674 817 }
@@ -686,7 +829,10 @@ async fn answer_offer(
686 829 .await
687 830 .map_err(|error| Error::Webrtc(error.to_string()))?;
688 831 let mut answer_text = answer.to_string();
689 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
832 for mid in kept_share_mids
833 .iter()
834 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
835 {
690 836 answer_text = stop_sending_on(&answer_text, mid);
691 837 }
692 838 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
@@ -699,7 +845,12 @@ async fn answer_offer(
699 845 let receiving_share_mid = kept_share_mids
700 846 .into_iter()
701 847 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
702 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
848 .find(|mid| {
849 matches!(
850 direction_of(&answer_text, mid).as_deref(),
851 Some("recvonly" | "sendrecv")
852 )
853 });
703 854 let mut numbers = random_u32;
704 855 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
705 856 Ok(AnsweredMedia {
@@ -714,7 +865,10 @@ fn new_media_leg_id() -> String {
714 865 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
715 866 }
716 867
717 async fn setup_step<T, E>(control: &mut CallControl, step: impl std::future::Future<Output = std::result::Result<T, E>>) -> Result<T>
868 async fn setup_step<T, E>(
869 control: &mut CallControl,
870 step: impl std::future::Future<Output = std::result::Result<T, E>>,
871 ) -> Result<T>
718 872 where
719 873 Error: From<E>,
720 874 {
@@ -759,12 +913,16 @@ async fn drive(
759 913 report: &mut CallReport,
760 914 ) -> Result<()> {
761 915 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
762 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
916 control.send(CallUpdate::OwnIdentity {
917 mri: own_mri.clone(),
918 });
763 919 let (spec, incoming) = match plan {
764 920 Plan::Outgoing(spec) => (Some(spec), None),
765 921 Plan::Incoming(incoming) => (None, Some(*incoming)),
766 922 };
767 let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);
923 let accept_mode = incoming
924 .as_ref()
925 .map_or(AcceptMode::Audio, |incoming| incoming.accept);
768 926 let (links, participant, mut callbacks, incoming_media) = match incoming {
769 927 Some(IncomingCall {
770 928 accept: _,
@@ -773,7 +931,12 @@ async fn drive(
773 931 links,
774 932 participant,
775 933 callbacks,
776 }) => (links, participant, callbacks, Some((notification, attached))),
934 }) => (
935 links,
936 participant,
937 callbacks,
938 Some((notification, attached)),
939 ),
777 940 None => {
778 941 let links = inner.callback_links();
779 942 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
@@ -786,15 +949,26 @@ async fn drive(
786 949
787 950 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
788 951 let thread_id = control
789 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
952 .until_hangup(find_echo_bot_thread(
953 &inner.session,
954 &inner.identity.object_id,
955 ))
790 956 .await??;
791 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
957 timeline.record(
958 "echo bot chat",
959 if thread_id.is_some() { "found" } else { "none" },
960 );
792 961 thread_id
793 962 } else {
794 963 None
795 964 };
796 let grant = control.until_hangup(inner.relay.grant(&inner.session)).await??;
797 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
965 let grant = control
966 .until_hangup(fetch_relay_grant(&inner.session))
967 .await??;
968 timeline.record(
969 "GET trap/tokens",
970 format!("relay grant, expires in {} s", grant.expires_in_seconds),
971 );
798 972
799 973 let factory = devices::shared_factory();
800 974 let mut input = options.input.clone();
@@ -802,15 +976,34 @@ async fn drive(
802 976 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
803 977 control.send(CallUpdate::ListenOnly(audio.listen_only));
804 978 let mut device_lists = devices::list_devices(&factory);
805 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
806 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
979 let mut applied_input = devices::applied_device(
980 &device_lists.inputs,
981 &input,
982 devices::system_default_id(Flow::Capture).as_deref(),
983 );
984 let mut applied_output = devices::applied_device(
985 &device_lists.outputs,
986 &output,
987 devices::system_default_id(Flow::Render).as_deref(),
988 );
807 989 let (_device_watcher, mut device_changes) = device_watch::watch();
808 990 let mut device_debounce = Debounce::default();
809 991 timeline.record(
810 992 "audio setup",
811 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
993 format!(
994 "listen only {}, {} input(s), {} output(s); {}",
995 audio.listen_only,
996 device_lists.inputs.len(),
997 device_lists.outputs.len(),
998 audio.adm_state
999 ),
1000 );
1001 record_audio_devices(
1002 timeline,
1003 &device_lists,
1004 applied_input.as_ref(),
1005 applied_output.as_ref(),
812 1006 );
813 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
814 1007 control.send(CallUpdate::Devices(device_lists.clone()));
815 1008 control.send(CallUpdate::Selected {
816 1009 input: input.clone(),
@@ -818,7 +1011,13 @@ async fn drive(
818 1011 });
819 1012 let track = audio.track.clone();
820 1013 live.audio = Some(audio);
821 let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates());
1014 let mut local_video = LocalVideo::new(
1015 &factory,
1016 options.video,
1017 control.video.clone(),
1018 control.updates(),
1019 );
1020 local_video.attach_timeline(timeline.clone());
822 1021 let mut camera_choice = options.camera.clone();
823 1022 if options.start_camera {
824 1023 match local_video.preview_camera(&camera_choice) {
@@ -828,9 +1027,11 @@ async fn drive(
828 1027 }
829 1028 let mut media_description_request = 1u32;
830 1029 refresh_cameras(control.updates(), options.video, timeline.clone());
1030 control.send(CallUpdate::SharePicker(current_share_picker()));
831 1031 refresh_share_sources(control.updates(), options.video, false);
832 1032
833 let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
1033 let wants_data_channel =
1034 options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
834 1035 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
835 1036 live.peers.push(current.peer.clone());
836 1037
@@ -854,7 +1055,9 @@ async fn drive(
854 1055 _ => None,
855 1056 };
856 1057 let people_thread = match &spec {
857 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
1058 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => {
1059 Some(thread_id.clone())
1060 }
858 1061 _ => incoming_media
859 1062 .as_ref()
860 1063 .filter(|(notification, _)| !notification.is_multi_party)
@@ -863,7 +1066,9 @@ async fn drive(
863 1066 .thread_id
864 1067 .clone()
865 1068 .filter(|thread| *thread != notification.caller.mri)
866 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
1069 .or_else(|| {
1070 one_to_one_thread(&inner.identity.object_id, &notification.caller.mri)
1071 })
867 1072 }),
868 1073 };
869 1074 let mut layout = match &spec {
@@ -871,8 +1076,12 @@ async fn drive(
871 1076 _ => Layout::Conference,
872 1077 };
873 1078 let peer_mri = match &spec {
874 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),
875 _ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),
1079 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => {
1080 Some(callees[0].mri.clone())
1081 }
1082 _ => incoming_media
1083 .as_ref()
1084 .map(|(notification, _)| notification.caller.mri.clone()),
876 1085 };
877 1086 let mut layout_plan: OfferPlan;
878 1087 let mut direct_video_mid: Option<String> = None;
@@ -884,14 +1093,26 @@ async fn drive(
884 1093 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
885 1094 let offer_started = Instant::now();
886 1095 let media = control
887 .until_hangup(create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)))
1096 .until_hangup(create_offer(
1097 &current.peer,
1098 &factory,
1099 &track,
1100 layout,
1101 direct_invite.then_some(&current.gathered),
1102 ))
888 1103 .await??;
889 timeline.record("offer created", format!("{} ms", offer_started.elapsed().as_millis()));
1104 timeline.record(
1105 "offer created",
1106 format!("{} ms", offer_started.elapsed().as_millis()),
1107 );
890 1108 layout_plan = media.plan.clone();
891 1109 if layout == Layout::OneToOne {
892 1110 direct_video_mid = Some(CAMERA_MID.to_owned());
893 1111 }
894 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
1112 timeline.record(
1113 "setLocalDescription",
1114 format!("{} m-line(s) signaled", media.signaled.lines.len()),
1115 );
895 1116 timeline.record_sdp("local offer", &media.signaled.sdp);
896 1117 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
897 1118 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
@@ -950,7 +1171,11 @@ async fn drive(
950 1171 threadless: notification.thread_id.is_none(),
951 1172 });
952 1173 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
953 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
1174 layout = if one_to_one {
1175 Layout::OneToOne
1176 } else {
1177 Layout::Conference
1178 };
954 1179 let camera_track = local_video.camera_track();
955 1180 let video_answer = match accept_mode {
956 1181 _ if !one_to_one => AnswerVideo::Reject,
@@ -958,21 +1183,34 @@ async fn drive(
958 1183 _ => AnswerVideo::Receive,
959 1184 };
960 1185 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
961 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
1186 let answered = answer_offer(
1187 &current.peer,
1188 Some(&track),
1189 &teams_offer,
1190 video_answer,
1191 None,
1192 false,
1193 one_to_one.then_some(&current.gathered),
1194 )
1195 .await?;
962 1196 layout_plan = answered.remote.plan();
963 1197 direct_video_mid = answered.camera_mid.clone();
964 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
965 if one_to_one {
966 timeline.record("ice gathered", current.gathered.summary());
967 }
1198 timeline.record(
1199 "setRemoteDescription",
1200 format!(
1201 "offer applied, {} signaled line(s)",
1202 answered.remote.lines.len()
1203 ),
1204 );
968 1205 timeline.record_sdp("remote offer", &teams_offer);
969 1206 timeline.record_sdp("local answer", &answered.answer_sdp);
970 1207 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
971 let acceptance_url = attached
972 .links
973 .get("acceptance")
974 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
975 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
1208 let acceptance_url = attached.links.get("acceptance").ok_or_else(|| {
1209 Error::Signaling("attach answer without an acceptance link".into())
1210 })?;
1211 let modalities = accepted_modalities(
1212 matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(),
1213 );
976 1214 let acknowledged = signaling
977 1215 .accept(
978 1216 acceptance_url,
@@ -991,20 +1229,37 @@ async fn drive(
991 1229 media_links.extend(acknowledged);
992 1230 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
993 1231 let camera = peer_transceiver(&current.peer, mid);
994 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
1232 match camera.map(|camera| {
1233 local_video.set_lines(VideoLines {
1234 camera,
1235 share: None,
1236 })
1237 }) {
995 1238 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
996 1239 Ok(()) => sending_camera = true,
997 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1240 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(
1241 CAMERA_START_NOTICE,
1242 error,
1243 ))),
998 1244 },
999 Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),
1000 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
1245 Some(Err(error)) => {
1246 timeline.record("video lines not attached", error.to_string())
1247 }
1248 None => timeline.record(
1249 "video lines not attached",
1250 "no transceiver for the camera line",
1251 ),
1001 1252 }
1002 1253 }
1003 1254 keep_alive_link = media_links.get("callLeg").cloned();
1004 1255 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1005 1256 conversation
1006 1257 }
1007 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
1258 _ => {
1259 return Err(Error::Callback(
1260 "call plan without an offer or an invitation".into(),
1261 ));
1262 }
1008 1263 };
1009 1264 let remote = live.remote.clone().expect("remote call set above");
1010 1265 live.broker_running.store(true, Ordering::SeqCst);
@@ -1016,11 +1271,20 @@ async fn drive(
1016 1271
1017 1272 let initial = MuteEffect::initial(is_meeting);
1018 1273 let mut muted = initial.muted;
1019 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
1274 live.audio
1275 .as_ref()
1276 .expect("audio set above")
1277 .track
1278 .set_enabled(initial.track_enabled);
1020 1279 if muted {
1021 1280 control.send(CallUpdate::Muted(true));
1022 1281 }
1023 match setup_step(control, signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted)).await {
1282 match setup_step(
1283 control,
1284 signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted),
1285 )
1286 .await
1287 {
1024 1288 Err(Error::Cancelled) => return Err(Error::Cancelled),
1025 1289 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1026 1290 Ok(()) => {}
@@ -1038,7 +1302,13 @@ async fn drive(
1038 1302 && roster.apply_snapshot(snapshot)
1039 1303 {
1040 1304 let entries = roster.entries();
1041 timeline.record("roster", format!("{} participant(s) from the conversation answer", entries.len()));
1305 timeline.record(
1306 "roster",
1307 format!(
1308 "{} participant(s) from the conversation answer",
1309 entries.len()
1310 ),
1311 );
1042 1312 control.send(CallUpdate::Roster(entries));
1043 1313 }
1044 1314 let mut lobby = false;
@@ -1063,7 +1333,25 @@ async fn drive(
1063 1333 crate::noise_stage::apply(mic_settings);
1064 1334 let mut audio_disabled = false;
1065 1335 let mut remote_audio: Option<RtcAudioTrack> = None;
1066 sync_software_audio(&factory, options, &input, muted, None, &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1336 sync_software_audio(
1337 &factory,
1338 options,
1339 &input,
1340 muted,
1341 None,
1342 &current.peer,
1343 &track,
1344 software_wanted(
1345 mic_settings,
1346 share_sound_wanted,
1347 &local_video,
1348 live.audio.as_ref(),
1349 ),
1350 false,
1351 &mut software_audio,
1352 control,
1353 timeline,
1354 );
1067 1355 let mut own_hand: Option<String> = None;
1068 1356 let mut depacketizer = Depacketizer::default();
1069 1357 let mut caption_flow = CaptionFlow::default();
@@ -1083,6 +1371,7 @@ async fn drive(
1083 1371 let mut send_requests = RequestFilter::default();
1084 1372 let mut send_capabilities = SendCapabilityReporter::default();
1085 1373 let mut same_peer_deadline: Option<Instant> = None;
1374 let mut same_peer_grace_until: Option<Instant> = None;
1086 1375 let mut meeting_chat = conversation.chat_thread.clone();
1087 1376 if let Some(thread) = &meeting_chat {
1088 1377 control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -1095,6 +1384,7 @@ async fn drive(
1095 1384 }
1096 1385 let mut start_camera_pending = options.start_camera;
1097 1386 let mut share_pending: Option<ShareSource> = None;
1387 let mut portal_pending: Option<ShareKind> = None;
1098 1388 let mut glare_resend: Option<GlareResend> = None;
1099 1389 let mut deferred_changes: Vec<Change> = Vec::new();
1100 1390 let mut remote_direct_share: Option<String> = None;
@@ -1109,10 +1399,19 @@ async fn drive(
1109 1399 {
1110 1400 control.defer(CallCommand::StartShare(source));
1111 1401 }
1112 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1113 && let Some(pending) = next.take()
1402 if video_possible(remote_set, layout, negotiator.path())
1403 && let Some(kind) = portal_pending.take()
1114 1404 {
1115 timeline.record("escalation", "new peer connection connected, old one dropped");
1405 control.defer(CallCommand::StartPortalShare(kind));
1406 }
1407 if next.as_ref().is_some_and(|pending| {
1408 pending.connected && (pending.offered.is_some() || pending.retargeted)
1409 }) && let Some(pending) = next.take()
1410 {
1411 timeline.record(
1412 "escalation",
1413 "new peer connection connected, old one dropped",
1414 );
1116 1415 deferred_changes.clear();
1117 1416 negotiator.server_escalation_done();
1118 1417 if let Some(mid) = remote_direct_share.take() {
@@ -1137,15 +1436,40 @@ async fn drive(
1137 1436 timeline.record("video lines not attached", error.to_string());
1138 1437 }
1139 1438 if local_video.camera_on() {
1140 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1439 tell_media_descriptions(
1440 &remote,
1441 &media_links,
1442 MediaDescription::camera(true),
1443 &mut media_description_request,
1444 timeline,
1445 );
1141 1446 }
1142 1447 if local_video.sharing() {
1143 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1448 tell_media_descriptions(
1449 &remote,
1450 &media_links,
1451 MediaDescription::share(true),
1452 &mut media_description_request,
1453 timeline,
1454 );
1144 1455 }
1145 1456 }
1146 1457 remote_set = true;
1147 1458 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1148 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1459 let pending = escalate(
1460 &factory,
1461 &grant,
1462 options,
1463 outgoing_track(software_audio.as_ref(), &track),
1464 &remote,
1465 &links,
1466 &media_leg_id,
1467 &media_links,
1468 &mut negotiator,
1469 live,
1470 timeline,
1471 )
1472 .await;
1149 1473 if pending.is_none() {
1150 1474 drop_local_media(&mut local_video, control);
1151 1475 }
@@ -1268,6 +1592,7 @@ async fn drive(
1268 1592 && let Some(pending) = same_peer.take()
1269 1593 {
1270 1594 same_peer_deadline = None;
1595 same_peer_grace_until = None;
1271 1596 let applied = match pending.change {
1272 1597 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1273 1598 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
@@ -1287,7 +1612,7 @@ async fn drive(
1287 1612 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1288 1613 local_video.stop_share();
1289 1614 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1290 control.send(CallUpdate::LocalShare(None));
1615 clear_share(control);
1291 1616 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1292 1617 }
1293 1618 Change::Share(_) => {}
@@ -1348,6 +1673,7 @@ async fn drive(
1348 1673 && let Some(pending) = same_peer.take()
1349 1674 {
1350 1675 same_peer_deadline = None;
1676 same_peer_grace_until = None;
1351 1677 negotiator.same_peer_offer_failed();
1352 1678 rollback_offer(&current.peer).await;
1353 1679 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
@@ -1359,6 +1685,7 @@ async fn drive(
1359 1685 MediaAction::AnswerOnNewPeer => {
1360 1686 if let Some(pending) = same_peer.take() {
1361 1687 same_peer_deadline = None;
1688 same_peer_grace_until = None;
1362 1689 timeline.record("same-peer offer", "superseded by the escalation offer");
1363 1690 rollback_offer(&current.peer).await;
1364 1691 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
@@ -1517,13 +1844,15 @@ async fn drive(
1517 1844 recording_flow.failed();
1518 1845 recording_deadline = None;
1519 1846 control.send(CallUpdate::RecordingPending(false));
1520 control.send(CallUpdate::Notice("The recording service could not join".into()));
1847 control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into()));
1521 1848 }
1522 1849 if caption_flow.wanted() && roster.caption_bot().is_none() {
1523 1850 timeline.record("caption bot failed", "addParticipantFailure");
1524 1851 caption_flow.failed();
1525 1852 caption_deadline = None;
1526 control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));
1853 control.send(CallUpdate::Captions(CaptionState::Failed(
1854 CAPTIONS_JOIN_FAILED_NOTICE.into(),
1855 )));
1527 1856 }
1528 1857 }
1529 1858 Ok(CallEvent::ConversationUpdate(body)) => {
@@ -1593,14 +1922,14 @@ async fn drive(
1593 1922 completed if completed.succeeded() => {
1594 1923 timeline.record("transfer", "completed");
1595 1924 control.send(CallUpdate::TransferResult { succeeded: true });
1596 control.send(CallUpdate::Notice("Call transferred".into()));
1925 control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into()));
1597 1926 advance(state, CallSignal::LocalLeave, control);
1598 1927 break;
1599 1928 }
1600 1929 TransferEvent::Completed { code, sub_code } => {
1601 1930 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1602 1931 control.send(CallUpdate::TransferResult { succeeded: false });
1603 control.send(CallUpdate::Notice("The transfer did not go through".into()));
1932 control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into()));
1604 1933 }
1605 1934 }
1606 1935 }
@@ -1659,6 +1988,7 @@ async fn drive(
1659 1988 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1660 1989 RejectedOffer::SamePeer => {
1661 1990 same_peer_deadline = None;
1991 same_peer_grace_until = None;
1662 1992 if let Some(pending) = same_peer.take() {
1663 1993 rollback_offer(&current.peer).await;
1664 1994 if is_glare_rejection(&body) {
@@ -1878,6 +2208,7 @@ async fn drive(
1878 2208 timeline.record_sdp("local offer", &signaled.sdp);
1879 2209 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1880 2210 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2211 same_peer_grace_until = None;
1881 2212 }
1882 2213 Err(error) => {
1883 2214 timeline.record("camera offer failed", error.to_string());
@@ -1889,7 +2220,7 @@ async fn drive(
1889 2220 control.send(CallUpdate::Camera(true));
1890 2221 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1891 2222 }
1892 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
2223 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
1893 2224 }
1894 2225 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1895 2226 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -1900,6 +2231,7 @@ async fn drive(
1900 2231 timeline.record_sdp("local offer", &signaled.sdp);
1901 2232 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1902 2233 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2234 same_peer_grace_until = None;
1903 2235 }
1904 2236 Err(error) => {
1905 2237 timeline.record("camera offer failed", error.to_string());
@@ -1917,11 +2249,59 @@ async fn drive(
1917 2249 if local_video.camera_previewing()
1918 2250 && let Err(error) = local_video.preview_camera(&camera_choice)
1919 2251 {
1920 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2252 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
1921 2253 } else if local_video.camera_on()
1922 2254 && let Err(error) = local_video.start_camera(&camera_choice)
1923 2255 {
1924 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2256 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2257 }
2258 }
2259 Some(CallCommand::SetVideoQuality(quality)) => {
2260 local_video.set_video_quality(quality);
2261 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2262 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error)));
2263 }
2264 if video.set_video_quality(quality) {
2265 send_receive_change(control, video.reselect(&roster));
2266 }
2267 }
2268 Some(CallCommand::StartPortalShare(kind)) => {
2269 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2270 if !remote_set {
2271 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2272 } else if local_hold {
2273 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2274 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2275 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2276 } else if direct
2277 && !local_video.sharing()
2278 && !local_video.has_share_line()
2279 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2280 {
2281 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2282 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2283 if next.is_none() && negotiator.begin_conference_upgrade() {
2284 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2285 next = pending.or(next);
2286 }
2287 if next.is_some() {
2288 portal_pending = Some(kind);
2289 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2290 } else {
2291 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2292 }
2293 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2294 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2295 }
2296 }
2297 Some(CallCommand::FinishPortalShare { source, generation }) => {
2298 if local_video.accept_portal(generation) {
2299 control.defer(CallCommand::StartShare(source));
2300 }
2301 }
2302 Some(CallCommand::AbandonPortalShare) => {
2303 if local_video.portal_is_open() {
2304 local_video.stop_share();
1925 2305 }
1926 2306 }
1927 2307 Some(CallCommand::StartShare(source)) => {
@@ -1930,10 +2310,10 @@ async fn drive(
1930 2310 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1931 2311 } else if local_hold {
1932 2312 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1933 } else if direct && local_video.sharing() {
2313 } else if direct && local_video.share_sending() {
1934 2314 match local_video.start_share(&source) {
1935 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1936 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2315 Ok(()) => announce_share(control, &source),
2316 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
1937 2317 }
1938 2318 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1939 2319 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -1941,17 +2321,18 @@ async fn drive(
1941 2321 && !local_video.has_share_line()
1942 2322 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
1943 2323 {
1944 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2324 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
1945 2325 } else if direct {
1946 2326 match local_video.start_share(&source) {
1947 2327 Ok(()) => {
1948 control.send(CallUpdate::LocalShare(Some(source.label())));
2328 announce_share(control, &source);
1949 2329 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1950 2330 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1951 2331 Ok((browser_offer, signaled, reply_tags)) => {
1952 2332 timeline.record_sdp("local offer", &signaled.sdp);
1953 2333 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1954 2334 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2335 same_peer_grace_until = None;
1955 2336 }
1956 2337 Err(error) => {
1957 2338 timeline.record("share offer failed", error.to_string());
@@ -1959,7 +2340,7 @@ async fn drive(
1959 2340 }
1960 2341 }
1961 2342 }
1962 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2343 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
1963 2344 }
1964 2345 } else if !video_possible(remote_set, layout, negotiator.path()) {
1965 2346 if next.is_none() && negotiator.begin_conference_upgrade() {
@@ -1975,35 +2356,39 @@ async fn drive(
1975 2356 } else {
1976 2357 match local_video.start_share(&source) {
1977 2358 Ok(()) => {
1978 control.send(CallUpdate::LocalShare(Some(source.label())));
2359 announce_share(control, &source);
1979 2360 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1980 2361 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1981 2362 }
1982 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2363 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
1983 2364 }
1984 2365 }
1985 2366 }
1986 2367 Some(CallCommand::StopShare) => {
1987 2368 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1988 2369 share_pending = None;
1989 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2370 portal_pending = None;
2371 if local_video.portal_is_open() {
2372 local_video.stop_share();
2373 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1990 2374 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1991 2375 } else if direct && local_video.sharing() {
1992 2376 local_video.stop_share();
1993 control.send(CallUpdate::LocalShare(None));
2377 clear_share(control);
1994 2378 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1995 2379 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1996 2380 Ok((browser_offer, signaled, reply_tags)) => {
1997 2381 timeline.record_sdp("local offer", &signaled.sdp);
1998 2382 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1999 2383 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2384 same_peer_grace_until = None;
2000 2385 }
2001 2386 Err(error) => timeline.record("share offer failed", error.to_string()),
2002 2387 }
2003 2388 } else if local_video.sharing() {
2004 2389 local_video.stop_share();
2005 2390 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2006 control.send(CallUpdate::LocalShare(None));
2391 clear_share(control);
2007 2392 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2008 2393 }
2009 2394 }
@@ -2020,7 +2405,7 @@ async fn drive(
2020 2405 Err(error) => {
2021 2406 timeline.record("raise hand failed", error.to_string());
2022 2407 control.send(CallUpdate::OwnHand(None));
2023 control.send(CallUpdate::Notice("Could not raise your hand".into()));
2408 control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into()));
2024 2409 }
2025 2410 },
2026 2411 Some(CallCommand::SetHand(false)) => {
@@ -2031,7 +2416,7 @@ async fn drive(
2031 2416 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2032 2417 {
2033 2418 timeline.record("lower hand failed", error.to_string());
2034 control.send(CallUpdate::Notice("Could not lower your hand".into()));
2419 control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into()));
2035 2420 }
2036 2421 }
2037 2422 Some(CallCommand::LowerHand { mri }) => {
@@ -2040,18 +2425,18 @@ async fn drive(
2040 2425 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2041 2426 {
2042 2427 timeline.record("lower hand failed", error.to_string());
2043 control.send(CallUpdate::Notice("Could not lower that hand".into()));
2428 control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into()));
2044 2429 }
2045 2430 }
2046 2431 Some(CallCommand::LowerAllHands) => {
2047 2432 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2048 2433 timeline.record("lower all hands failed", error.to_string());
2049 control.send(CallUpdate::Notice("Could not lower all hands".into()));
2434 control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into()));
2050 2435 }
2051 2436 }
2052 2437 Some(CallCommand::Admit { mri }) => {
2053 2438 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2054 report_organizer_result(result, "admit", "Could not admit that person", control, timeline);
2439 report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline);
2055 2440 }
2056 2441 Some(CallCommand::AdmitAll) => {
2057 2442 let mut result = Ok(202);
@@ -2061,19 +2446,19 @@ async fn drive(
2061 2446 break;
2062 2447 }
2063 2448 }
2064 report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);
2449 report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline);
2065 2450 }
2066 2451 Some(CallCommand::Deny { mri }) => {
2067 2452 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2068 report_organizer_result(result, "deny", "Could not deny that person", control, timeline);
2453 report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline);
2069 2454 }
2070 2455 Some(CallCommand::RemoveParticipant { mri }) => {
2071 2456 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2072 report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);
2457 report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2073 2458 }
2074 2459 Some(CallCommand::MuteParticipant { mri }) => {
2075 2460 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2076 report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);
2461 report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2077 2462 }
2078 2463 Some(CallCommand::MuteAll) => {
2079 2464 let others: Vec<String> = roster
@@ -2083,7 +2468,7 @@ async fn drive(
2083 2468 .map(|member| member.mri.clone())
2084 2469 .collect();
2085 2470 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2086 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
2471 report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline);
2087 2472 }
2088 2473 Some(CallCommand::SetLock(locked)) => {
2089 2474 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
@@ -2091,11 +2476,11 @@ async fn drive(
2091 2476 capability.locked = locked;
2092 2477 control.send(CallUpdate::Capability(capability));
2093 2478 }
2094 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
2479 report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline);
2095 2480 }
2096 2481 Some(CallCommand::SetRole { mri, role }) => {
2097 2482 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2098 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
2483 report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline);
2099 2484 }
2100 2485 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2101 2486 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
@@ -2109,7 +2494,11 @@ async fn drive(
2109 2494 break;
2110 2495 }
2111 2496 }
2112 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
2497 let notice = if modality == Modality::Mic {
2498 MIC_SETTING_FAILED_NOTICE
2499 } else {
2500 CAMERA_SETTING_FAILED_NOTICE
2501 };
2113 2502 report_organizer_result(result, "attendee modality", notice, control, timeline);
2114 2503 }
2115 2504 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
@@ -2122,12 +2511,12 @@ async fn drive(
2122 2511 capability.attendee_camera_off = camera_off;
2123 2512 control.send(CallUpdate::Capability(capability));
2124 2513 }
2125 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
2514 report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline);
2126 2515 }
2127 2516 Some(CallCommand::Invite { callees, group_thread }) => {
2128 2517 let thread = group_thread.or_else(|| meeting_chat.clone());
2129 2518 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2130 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
2519 report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline);
2131 2520 }
2132 2521 Some(CallCommand::LoadMeetingOptions) => {
2133 2522 let update = match &meeting_target {
@@ -2151,13 +2540,13 @@ async fn drive(
2151 2540 }
2152 2541 Some(CallCommand::Spotlight { mri }) => {
2153 2542 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2154 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
2543 report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline);
2155 2544 }
2156 2545 Some(CallCommand::StopSpotlight { mri }) => {
2157 2546 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2158 2547 if !state_ids.is_empty() {
2159 2548 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2160 report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);
2549 report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline);
2161 2550 }
2162 2551 }
2163 2552 Some(CallCommand::SetCaptions(on)) => {
@@ -2196,7 +2585,7 @@ async fn drive(
2196 2585 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2197 2586 {
2198 2587 timeline.record("caption language failed", error.to_string());
2199 control.send(CallUpdate::Notice("Could not change the spoken language".into()));
2588 control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into()));
2200 2589 }
2201 2590 }
2202 2591 Some(CallCommand::ConsentToRecording) => {
@@ -2207,7 +2596,7 @@ async fn drive(
2207 2596 }
2208 2597 Err(error) => {
2209 2598 timeline.record("recording consent failed", error.to_string());
2210 control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));
2599 control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into()));
2211 2600 }
2212 2601 }
2213 2602 }
@@ -2225,32 +2614,40 @@ async fn drive(
2225 2614 timeline.record_sdp("local offer", &signaled.sdp);
2226 2615 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2227 2616 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2617 same_peer_grace_until = None;
2228 2618 }
2229 2619 Err(error) => {
2230 2620 timeline.record("hold failed", error.to_string());
2231 control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));
2621 control.send(CallUpdate::Notice(if hold {
2622 HOLD_FAILED_NOTICE.into()
2623 } else {
2624 RESUME_FAILED_NOTICE.into()
2625 }));
2232 2626 }
2233 2627 }
2234 2628 }
2235 2629 Some(CallCommand::Transfer { target, replaces }) => {
2236 2630 let Some(url) = media_links.get("transfer").cloned() else {
2237 2631 control.send(CallUpdate::TransferResult { succeeded: false });
2238 control.send(CallUpdate::Notice("This call cannot be transferred".into()));
2632 control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into()));
2239 2633 continue;
2240 2634 };
2241 2635 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2242 2636 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2243 Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),
2637 Ok(()) => control.send(CallUpdate::Notice(notice_with_detail(
2638 TRANSFERRING_NOTICE,
2639 target.display_name,
2640 ))),
2244 2641 Err(error) => {
2245 2642 timeline.record("transfer failed", error.to_string());
2246 2643 control.send(CallUpdate::TransferResult { succeeded: false });
2247 control.send(CallUpdate::Notice("Could not transfer the call".into()));
2644 control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into()));
2248 2645 }
2249 2646 }
2250 2647 }
2251 2648 Some(CallCommand::OpenWhiteboard { title }) => {
2252 2649 let Some(target) = meeting_target.clone() else {
2253 control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));
2650 control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into()));
2254 2651 continue;
2255 2652 };
2256 2653 let session = inner.session.clone();
@@ -2258,7 +2655,7 @@ async fn drive(
2258 2655 tokio::spawn(async move {
2259 2656 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2260 2657 Ok(url) => CallUpdate::WhiteboardUrl(url),
2261 Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),
2658 Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()),
2262 2659 };
2263 2660 let _ = updates.send(update);
2264 2661 });
@@ -2285,7 +2682,7 @@ async fn drive(
2285 2682 Some(CallCommand::SendReaction(reaction)) => {
2286 2683 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2287 2684 timeline.record("reaction failed", error.to_string());
2288 control.send(CallUpdate::Notice("Could not send the reaction".into()));
2685 control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into()));
2289 2686 }
2290 2687 }
2291 2688 Some(CallCommand::EndMeeting) => {
@@ -2336,12 +2733,13 @@ async fn drive(
2336 2733 recording_flow.failed();
2337 2734 timeline.record("recording", "did not start in time");
2338 2735 control.send(CallUpdate::RecordingPending(false));
2339 control.send(CallUpdate::Notice("The recording did not start".into()));
2736 control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into()));
2340 2737 }
2341 2738 if layout == Layout::Conference
2342 2739 && let Some(size) = local_video.camera_size()
2343 2740 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2344 && let Some(body) = send_capabilities.body_for(size)
2741 && let Some(body) =
2742 send_capabilities.body_for(size, local_video.video_quality())
2345 2743 {
2346 2744 let signaling = signaling.clone();
2347 2745 let timeline = timeline.clone();
@@ -2437,12 +2835,13 @@ async fn drive(
2437 2835 timeline.record(
2438 2836 "stats",
2439 2837 format!(
2440 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}",
2838 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}{}",
2441 2839 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2442 2840 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2443 2841 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2444 2842 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2445 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2843 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2844 local_video.camera_capture_summary().unwrap_or_default()
2446 2845 ),
2447 2846 );
2448 2847 }
@@ -2487,6 +2886,7 @@ async fn drive(
2487 2886 control.send(CallUpdate::Camera(false));
2488 2887 }
2489 2888 share_pending = None;
2889 portal_pending = None;
2490 2890 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2491 2891 timeline.record("escalation failed", "no answer for the new peer connection in time");
2492 2892 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
@@ -2517,6 +2917,7 @@ async fn drive(
2517 2917 timeline.record_sdp("local offer", &signaled.sdp);
2518 2918 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2519 2919 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2920 same_peer_grace_until = None;
2520 2921 }
2521 2922 Err(error) => {
2522 2923 timeline.record("offer after glare failed", error.to_string());
@@ -2527,6 +2928,16 @@ async fn drive(
2527 2928 }
2528 2929 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2529 2930 same_peer_deadline = None;
2931 if same_peer.is_some() {
2932 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2933 timeline.record(
2934 "same-peer offer",
2935 "no answer yet, waiting a little longer",
2936 );
2937 }
2938 }
2939 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2940 same_peer_grace_until = None;
2530 2941 if let Some(pending) = same_peer.take() {
2531 2942 timeline.record("same-peer offer", "no answer in time");
2532 2943 negotiator.same_peer_offer_failed();
@@ -2554,6 +2965,10 @@ async fn drive(
2554 2965 }
2555 2966 }
2556 2967 }
2968 if software_audio.is_some() {
2969 timeline.record("software audio", "stopping before tear down");
2970 drop(software_audio);
2971 }
2557 2972 live.callbacks = Some(callbacks);
2558 2973 Ok(())
2559 2974 }
@@ -2574,9 +2989,20 @@ async fn start_escalation(
2574 2989 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2575 2990 let session = open_peer(factory, grant, &options.relay_host, false)?;
2576 2991 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2577 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2992 let body = renegotiation_body(
2993 &remote.participant,
2994 links,
2995 &media.signaled.sdp,
2996 media_leg_id,
2997 &media.modalities,
2998 true,
2999 false,
3000 );
2578 3001 let reply_tags = offer_reply_tags(&body);
2579 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
3002 remote
3003 .signaling
3004 .post_json("POST mediaRenegotiation", url, body)
3005 .await?;
2580 3006 Ok(NextPeer {
2581 3007 session,
2582 3008 offered: Some(media),
@@ -2637,7 +3063,16 @@ async fn answer_on_new_peer(
2637 3063 teams_offer: &str,
2638 3064 ) -> Result<(PeerSession, AnsweredMedia)> {
2639 3065 let session = open_peer(factory, grant, &options.relay_host, false)?;
2640 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
3066 let answered = answer_offer(
3067 &session.peer,
3068 Some(track),
3069 teams_offer,
3070 AnswerVideo::Reject,
3071 None,
3072 false,
3073 None,
3074 )
3075 .await?;
2641 3076 Ok((session, answered))
2642 3077 }
2643 3078
@@ -2651,8 +3086,16 @@ async fn send_media_answer(
2651 3086 let url = reply_links
2652 3087 .get("mediaAnswer")
2653 3088 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
2654 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
2655 remote.signaling.post_json("POST mediaAnswer", url, body).await
3089 let body = escalation_answer_body(
3090 &remote.participant,
3091 links,
3092 &answered.answer_sdp,
3093 media_leg_id,
3094 );
3095 remote
3096 .signaling
3097 .post_json("POST mediaAnswer", url, body)
3098 .await
2656 3099 }
2657 3100
2658 3101 #[allow(clippy::too_many_arguments)]
@@ -2675,7 +3118,9 @@ fn negotiate_video(
2675 3118 }
2676 3119 };
2677 3120 let table = SlotTable::from_streams(&streams);
2678 let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming"));
3121 let link = links
3122 .get("applyChannelParameters")
3123 .or_else(|| links.get("controlVideoStreaming"));
2679 3124 timeline.record(
2680 3125 "video slots",
2681 3126 format!(
@@ -2685,33 +3130,48 @@ fn negotiate_video(
2685 3130 link.is_some()
2686 3131 ),
2687 3132 );
2688 let requester = link
2689 .filter(|_| from_mixer)
2690 .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone()));
3133 let requester = link.filter(|_| from_mixer).map(|url| {
3134 SourceRequester::start(
3135 signaling.clone(),
3136 url.clone(),
3137 video.router().clone(),
3138 control.video.clone(),
3139 timeline.clone(),
3140 )
3141 });
2691 3142 video.negotiated(table, requester);
2692 3143 send_receive_change(control, video.reselect(roster));
2693 3144 }
2694 3145
2695 const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
2696 const ON_HOLD_NOTICE: &str = "Resume the call first";
2697 const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
2698 const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
2699 const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
2700 const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
2701
2702 3146 async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2703 3147 match mode {
2704 VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }],
3148 VideoMode::Pattern => vec![CameraDevice {
3149 key: "pattern".into(),
3150 name: "Test pattern".into(),
3151 }],
2705 3152 VideoMode::Off => Vec::new(),
2706 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(),
3153 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3154 .await
3155 .unwrap_or_default(),
2707 3156 }
2708 3157 }
2709 3158
2710 fn refresh_cameras(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, timeline: Timeline) {
3159 fn refresh_cameras(
3160 updates: mpsc::UnboundedSender<CallUpdate>,
3161 mode: VideoMode,
3162 timeline: Timeline,
3163 ) {
2711 3164 tokio::spawn(async move {
2712 3165 let started = Instant::now();
2713 3166 let cameras = camera_devices(mode).await;
2714 timeline.record("camera list", format!("{} camera(s) in {} ms", cameras.len(), started.elapsed().as_millis()));
3167 timeline.record(
3168 "camera list",
3169 format!(
3170 "{} camera(s) in {} ms",
3171 cameras.len(),
3172 started.elapsed().as_millis()
3173 ),
3174 );
2715 3175 let _ = updates.send(CallUpdate::Cameras(cameras));
2716 3176 });
2717 3177 }
@@ -2720,37 +3180,85 @@ const SHARE_THUMBNAIL_WINDOWS: usize = 12;
2720 3180 const SHARE_THUMBNAIL_WIDTH: u32 = 320;
2721 3181 const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
2722 3182
2723 fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, with_thumbnails: bool) {
3183 fn announce_share(control: &CallControl, source: &ShareSource) {
3184 control.send(CallUpdate::ShareKind(Some(source.kind)));
3185 control.send(CallUpdate::LocalShare(Some(source.label())));
3186 }
3187
3188 fn clear_share(control: &CallControl) {
3189 control.send(CallUpdate::ShareKind(None));
3190 control.send(CallUpdate::LocalShare(None));
3191 }
3192
3193 fn refresh_share_sources(
3194 updates: mpsc::UnboundedSender<CallUpdate>,
3195 mode: VideoMode,
3196 with_thumbnails: bool,
3197 ) {
2724 3198 tokio::spawn(async move {
3199 let picker = current_share_picker();
2725 3200 let sources = match mode {
2726 3201 VideoMode::Pattern => vec![
2727 ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() },
2728 ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() },
3202 ShareSource {
3203 id: 1,
3204 kind: ShareKind::Screen,
3205 title: "Test screen".into(),
3206 },
3207 ShareSource {
3208 id: 2,
3209 kind: ShareKind::Window,
3210 title: "Test window".into(),
3211 },
2729 3212 ],
2730 3213 VideoMode::Off => Vec::new(),
2731 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(),
3214 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3215 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3216 .await
3217 .unwrap_or_default(),
2732 3218 };
3219 let sources = share_sources_for_menu(picker, sources);
2733 3220 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
2734 if !with_thumbnails {
3221 if picker == SharePicker::Portal || !with_thumbnails {
2735 3222 return;
2736 3223 }
2737 3224 let wanted: Vec<ShareSource> = sources
2738 3225 .iter()
2739 3226 .filter(|source| source.kind == ShareKind::Screen)
2740 .chain(sources.iter().filter(|source| source.kind == ShareKind::Window).take(SHARE_THUMBNAIL_WINDOWS))
3227 .chain(
3228 sources
3229 .iter()
3230 .filter(|source| source.kind == ShareKind::Window)
3231 .take(SHARE_THUMBNAIL_WINDOWS),
3232 )
2741 3233 .cloned()
2742 3234 .collect();
2743 3235 for source in wanted {
2744 3236 let picture = match mode {
2745 3237 VideoMode::Platform => {
2746 3238 let wanted = source.clone();
2747 tokio::task::spawn_blocking(move || share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)).await.ok().flatten()
3239 tokio::task::spawn_blocking(move || {
3240 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3241 })
3242 .await
3243 .ok()
3244 .flatten()
2748 3245 }
2749 VideoMode::Pattern => Some(VideoPicture::solid(SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT, 120, 80, 40)),
3246 VideoMode::Pattern => Some(VideoPicture::solid(
3247 SHARE_THUMBNAIL_WIDTH,
3248 SHARE_THUMBNAIL_HEIGHT,
3249 120,
3250 80,
3251 40,
3252 )),
2750 3253 VideoMode::Off => None,
2751 3254 };
2752 3255 if let Some(picture) = picture
2753 && updates.send(CallUpdate::ShareThumbnail { source, picture: Arc::new(picture) }).is_err()
3256 && updates
3257 .send(CallUpdate::ShareThumbnail {
3258 source,
3259 picture: Arc::new(picture),
3260 })
3261 .is_err()
2754 3262 {
2755 3263 return;
2756 3264 }
@@ -2774,8 +3282,14 @@ fn tell_media_descriptions(
2774 3282 let signaling = remote.signaling.clone();
2775 3283 let timeline = timeline.clone();
2776 3284 tokio::spawn(async move {
2777 let sent = format!("{} {} request {request_id}", description.mid, description.direction);
2778 if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await {
3285 let sent = format!(
3286 "{} {} request {request_id}",
3287 description.mid, description.direction
3288 );
3289 if let Err(error) = signaling
3290 .update_media_descriptions(&url, &[description], request_id)
3291 .await
3292 {
2779 3293 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
2780 3294 }
2781 3295 });
@@ -2785,30 +3299,54 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2785 3299 own.is_some_and(|own| own.thread_id == target.thread_id)
2786 3300 }
2787 3301
2788 fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
3302 fn attach_share_line(
3303 peer: &PeerConnection,
3304 factory: &PeerConnectionFactory,
3305 local_video: &mut LocalVideo,
3306 camera_mid: Option<&str>,
3307 ) -> Result<()> {
2789 3308 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2790 3309 if !local_video.has_lines() && camera.is_none() {
2791 3310 return Err(Error::Webrtc("no video line negotiated".into()));
2792 3311 }
2793 3312 let share = add_share_line(peer, factory)?;
2794 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
2795 let _ = share.stop();
2796 })
3313 local_video
3314 .add_share_line(share.clone(), camera)
3315 .inspect_err(|_| {
3316 let _ = share.stop();
3317 })
2797 3318 }
2798 3319
2799 3320 fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2800 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
3321 peer.transceivers()
3322 .into_iter()
3323 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2801 3324 }
2802 3325
2803 fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {
3326 fn start_camera_line(
3327 local_video: &mut LocalVideo,
3328 peer: &PeerConnection,
3329 direct_mid: Option<&str>,
3330 choice: &DeviceChoice,
3331 ) -> Result<()> {
2804 3332 if !local_video.has_lines() {
2805 3333 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
2806 let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
2807 if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {
2808 peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])
2809 .map_err(|error| Error::Webrtc(error.to_string()))?;
3334 let camera = peer_transceiver(peer, mid)
3335 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
3336 if !matches!(
3337 camera.direction(),
3338 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
3339 ) {
3340 peer.add_track(
3341 MediaStreamTrack::Video(local_video.camera_track()),
3342 &[CAMERA_STREAM],
3343 )
3344 .map_err(|error| Error::Webrtc(error.to_string()))?;
2810 3345 }
2811 local_video.set_lines(VideoLines { camera, share: None })?;
3346 local_video.set_lines(VideoLines {
3347 camera,
3348 share: None,
3349 })?;
2812 3350 }
2813 3351 local_video.start_camera(choice)
2814 3352 }
@@ -2836,9 +3374,22 @@ async fn offer_same_peer(
2836 3374 .cloned()
2837 3375 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
2838 3376 if !negotiator.begin_same_peer_offer() {
2839 return Err(Error::Signaling("another media negotiation is running".into()));
3377 return Err(Error::Signaling(
3378 "another media negotiation is running".into(),
3379 ));
2840 3380 }
2841 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
3381 let offered = build_same_peer_offer(
3382 peer,
3383 plan,
3384 layout,
3385 hold,
3386 camera,
3387 share,
3388 camera_mid,
3389 own_share_mid,
3390 direct.then_some(gathered),
3391 )
3392 .await;
2842 3393 let (text, signaled) = match offered {
2843 3394 Ok(offered) => offered,
2844 3395 Err(error) => {
@@ -2846,10 +3397,25 @@ async fn offer_same_peer(
2846 3397 return Err(error);
2847 3398 }
2848 3399 };
2849 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
2850 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
3400 let modalities = offer_modalities(
3401 layout == Layout::OneToOne && camera && !hold,
3402 share && !hold,
3403 );
3404 let body = renegotiation_body(
3405 &remote.participant,
3406 links,
3407 &signaled.sdp,
3408 media_leg_id,
3409 &modalities,
3410 false,
3411 direct,
3412 );
2851 3413 let reply_tags = offer_reply_tags(&body);
2852 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
3414 if let Err(error) = remote
3415 .signaling
3416 .post_json("POST mediaRenegotiation (same peer)", &url, body)
3417 .await
3418 {
2853 3419 negotiator.same_peer_offer_failed();
2854 3420 rollback_offer(peer).await;
2855 3421 return Err(error);
@@ -2858,9 +3424,23 @@ async fn offer_same_peer(
2858 3424 }
2859 3425
2860 3426 #[allow(clippy::too_many_arguments)]
2861 async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
3427 async fn build_same_peer_offer(
3428 peer: &PeerConnection,
3429 plan: &OfferPlan,
3430 layout: Layout,
3431 hold: bool,
3432 camera: bool,
3433 share: bool,
3434 camera_mid: &str,
3435 own_share_mid: Option<String>,
3436 gathered: Option<&Gathered>,
3437 ) -> Result<(String, SignaledOffer)> {
2862 3438 let offer = peer
2863 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
3439 .create_offer(OfferOptions {
3440 offer_to_receive_audio: true,
3441 offer_to_receive_video: true,
3442 ..OfferOptions::default()
3443 })
2864 3444 .await
2865 3445 .map_err(|error| Error::Webrtc(error.to_string()))?;
2866 3446 let offer_text = offer.to_string();
@@ -2870,25 +3450,56 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2870 3450 .and_then(|remote| direction_of(&remote.to_string(), mid))
2871 3451 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2872 3452 });
2873 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
3453 let text = directions_for(
3454 layout,
3455 false,
3456 camera,
3457 share,
3458 camera_mid,
3459 share_mid.as_deref(),
3460 remote_shares,
3461 &offer_text,
3462 );
2874 3463 let description = parse_sdp(&text, SdpType::Offer)?;
2875 3464 peer.set_local_description(description)
2876 3465 .await
2877 3466 .map_err(|error| Error::Webrtc(error.to_string()))?;
2878 3467 let mut numbers = random_u32;
2879 3468 let mut plan = plan.clone();
2880 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
3469 if let Some(mid) = share_mid
3470 .as_ref()
3471 .filter(|mid| !plan.screen_share_mids.contains(mid))
3472 {
2881 3473 plan.screen_share_mids.push(mid.clone());
2882 3474 }
2883 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
3475 let mut signaled = to_teams_offer(
3476 &directions_for(
3477 layout,
3478 hold,
3479 camera,
3480 share,
3481 camera_mid,
3482 share_mid.as_deref(),
3483 remote_shares,
3484 &text,
3485 ),
3486 &plan,
3487 &mut numbers,
3488 )?;
2884 3489 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2885 3490 if gathered.is_some()
2886 3491 && let Some(role) = negotiated_setup(
2887 peer.current_local_description().map(|local| local.to_string()).as_deref(),
2888 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
3492 peer.current_local_description()
3493 .map(|local| local.to_string())
3494 .as_deref(),
3495 peer.current_remote_description()
3496 .map(|remote| remote.to_string())
3497 .as_deref(),
2889 3498 )
2890 3499 {
2891 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
3500 signaled.sdp = signaled
3501 .sdp
3502 .replace("a=setup:actpass", &format!("a=setup:{role}"));
2892 3503 }
2893 3504 Ok((text, signaled))
2894 3505 }
@@ -2897,8 +3508,13 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2897 3508 fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
2898 3509 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
2899 3510 Ok(Ok(description)) => Ok(description),
2900 Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),
2901 Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),
3511 Ok(Err(error)) => Err(Error::Sdp(format!(
3512 "{kind:?} rejected: {}",
3513 error.description
3514 ))),
3515 Err(_) => Err(Error::Sdp(format!(
3516 "{kind:?} rejected, libwebrtc gave no readable reason"
3517 ))),
2902 3518 }
2903 3519 }
2904 3520
@@ -2920,7 +3536,10 @@ fn is_glare_rejection(body: &serde_json::Value) -> bool {
2920 3536
2921 3537 fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2922 3538 let links = &body["mediaNegotiation"]["links"];
2923 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
3539 ["mediaAnswer", "rejection"]
3540 .iter()
3541 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
3542 .collect()
2924 3543 }
2925 3544
2926 3545 #[cfg(test)]
@@ -2930,9 +3549,15 @@ mod reply_tag_tests {
2930 3549 #[test]
2931 3550 fn answers_and_rejections_match_the_offer_by_tag() {
2932 3551 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2933 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
3552 assert!(answers_offer(
3553 "callAgent/c/aaaa1111/call/mediaAnswer/",
3554 &tags
3555 ));
2934 3556 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2935 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
3557 assert!(!answers_offer(
3558 "callAgent/c/cccc3333/call/mediaAnswer/",
3559 &tags
3560 ));
2936 3561 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2937 3562 }
2938 3563
@@ -2941,11 +3566,19 @@ mod reply_tag_tests {
2941 3566 let body = serde_json::json!({"mediaNegotiation": {"links": {
2942 3567 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2943 3568 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2944 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
3569 assert_eq!(
3570 offer_reply_tags(&body),
3571 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
3572 );
2945 3573 }
2946 3574 }
2947 3575
2948 fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3576 fn defer_to_new_peer(
3577 change: Change,
3578 deferred: &mut Vec<Change>,
3579 local_video: &mut LocalVideo,
3580 control: &CallControl,
3581 ) {
2949 3582 match change {
2950 3583 Change::Camera(true) => {
2951 3584 control.send(CallUpdate::Camera(true));
@@ -2957,7 +3590,14 @@ fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &m
2957 3590 }
2958 3591
2959 3592 /// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2960 fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3593 fn settle_failed_escalation(
3594 server: bool,
3595 layout: Layout,
3596 negotiator: &mut MediaNegotiator,
3597 deferred: &mut Vec<Change>,
3598 local_video: &mut LocalVideo,
3599 control: &CallControl,
3600 ) {
2961 3601 if server {
2962 3602 negotiator.server_escalation_failed();
2963 3603 for change in deferred.drain(..) {
@@ -2971,7 +3611,7 @@ fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut Media
2971 3611 fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2972 3612 if local_video.sharing() {
2973 3613 local_video.stop_share();
2974 control.send(CallUpdate::LocalShare(None));
3614 clear_share(control);
2975 3615 }
2976 3616 if local_video.camera_on() {
2977 3617 local_video.stop_camera();
@@ -2988,11 +3628,11 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
2988 3628 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2989 3629 Change::Share(true) => {
2990 3630 local_video.stop_share();
2991 control.send(CallUpdate::LocalShare(None));
2992 control.send(CallUpdate::Notice("Sharing could not start".into()));
3631 clear_share(control);
3632 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, "")));
2993 3633 }
2994 3634 Change::Share(false) => {}
2995 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
3635 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
2996 3636 }
2997 3637 }
2998 3638
@@ -3004,37 +3644,63 @@ fn withhold_media(
3004 3644 local_video: &mut LocalVideo,
3005 3645 control: &CallControl,
3006 3646 ) {
3007 *muted = apply_mute(MuteCommand::Mute, *muted, audio, software_audio, remote, control);
3647 *muted = apply_mute(
3648 MuteCommand::Mute,
3649 *muted,
3650 audio,
3651 software_audio,
3652 remote,
3653 control,
3654 );
3008 3655 if local_video.camera_on() {
3009 3656 local_video.stop_camera();
3010 3657 control.send(CallUpdate::Camera(false));
3011 3658 }
3012 3659 }
3013 3660
3014 async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {
3661 async fn apply_background(
3662 choice: BackgroundChoice,
3663 local_video: &LocalVideo,
3664 control: &CallControl,
3665 timeline: &Timeline,
3666 ) {
3015 3667 match choice {
3016 3668 BackgroundChoice::None => local_video.set_background(false, None),
3017 3669 BackgroundChoice::Blur => local_video.set_background(true, None),
3018 BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3019 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3020 Ok(Err(error)) => {
3021 timeline.record("background image failed", error.to_string());
3022 control.send(CallUpdate::Notice("That background image could not be used".into()));
3670 BackgroundChoice::Image(path) => {
3671 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3672 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3673 Ok(Err(error)) => {
3674 timeline.record("background image failed", error.to_string());
3675 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
3676 }
3677 Err(_) => {}
3023 3678 }
3024 Err(_) => {}
3025 },
3679 }
3026 3680 }
3027 3681 }
3028 3682
3029 async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
3683 async fn save_meeting_options(
3684 session: &session::Session,
3685 target: &MeetingTarget,
3686 writes: &[OptionWrite],
3687 ) -> std::result::Result<meeting_options::MeetingOptions, String> {
3030 3688 for change in writes {
3031 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
3689 meeting_options::write(session, target, change)
3690 .await
3691 .map_err(|error| error.to_string())?;
3032 3692 }
3033 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
3693 meeting_options::fetch(session, target)
3694 .await
3695 .map_err(|error| error.to_string())
3034 3696 }
3035 3697
3036 3698 fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3037 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
3699 let display_name = roster
3700 .members()
3701 .iter()
3702 .find(|member| member.mri == mri)
3703 .map_or("", |member| member.display_name.as_str());
3038 3704 Target { mri, display_name }
3039 3705 }
3040 3706
@@ -3046,17 +3712,29 @@ fn recorder_busy(error: &Error) -> bool {
3046 3712 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3047 3713 }
3048 3714
3049 fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {
3715 fn report_organizer_result(
3716 result: Result<u16>,
3717 label: &str,
3718 notice: &'static str,
3719 control: &CallControl,
3720 timeline: &Timeline,
3721 ) {
3050 3722 if let Err(error) = &result {
3051 3723 timeline.record(format!("{label} failed"), error.to_string());
3052 control.send(CallUpdate::Notice(notice.into()));
3724 control.send(CallUpdate::Notice(notice.to_owned()));
3053 3725 }
3054 control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });
3726 control.send(CallUpdate::Organizer {
3727 action: label.to_owned(),
3728 outcome: result.map_err(|error| error.to_string()),
3729 });
3055 3730 }
3056 3731
3057 3732 fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3058 3733 if entry.display_name.is_empty() {
3059 entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();
3734 entry.display_name = roster
3735 .name_of(&entry.user_id)
3736 .unwrap_or_default()
3737 .to_owned();
3060 3738 }
3061 3739 entry
3062 3740 }
@@ -3095,8 +3773,14 @@ async fn run_bot_steps(
3095 3773 }
3096 3774 };
3097 3775 let (join_failure, start_failure) = match job {
3098 BotJob::Captions => ("The captions service could not join", "Captions could not start"),
3099 BotJob::Recording => ("The recording service could not join", "The recording could not start"),
3776 BotJob::Captions => (
3777 CAPTIONS_JOIN_FAILED_NOTICE,
3778 CAPTIONS_START_FAILED_NOTICE,
3779 ),
3780 BotJob::Recording => (
3781 RECORDING_JOIN_FAILED_NOTICE,
3782 RECORDING_START_FAILED_NOTICE,
3783 ),
3100 3784 };
3101 3785 loop {
3102 3786 match flow.next_for(roster.caption_bot(), is_active) {
@@ -3106,12 +3790,33 @@ async fn run_bot_steps(
3106 3790 continue;
3107 3791 }
3108 3792 let Some(thread) = meeting_chat else {
3109 return fail(flow, "This call has no chat for the captions and the recording");
3793 return fail(
3794 flow,
3795 "This call has no chat for the captions and the recording",
3796 );
3110 3797 };
3111 3798 *bot_pending = true;
3112 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
3799 let added = remote
3800 .signaling
3801 .add_caption_bot(
3802 &remote.conversation,
3803 &remote.participant,
3804 thread,
3805 links,
3806 remote.threadless,
3807 )
3808 .await;
3113 3809 if job == BotJob::Recording {
3114 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
3810 report_organizer_result(
3811 added
3812 .as_ref()
3813 .map(|status| *status)
3814 .map_err(|error| Error::Signaling(error.to_string())),
3815 "recording add bot",
3816 join_failure,
3817 control,
3818 timeline,
3819 );
3115 3820 }
3116 3821 if let Err(error) = added {
3117 3822 timeline.record("bot invitation failed", error.to_string());
@@ -3120,21 +3825,40 @@ async fn run_bot_steps(
3120 3825 }
3121 3826 }
3122 3827 CaptionStep::Start => {
3123 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
3828 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3829 return;
3830 };
3124 3831 match job {
3125 3832 BotJob::Captions => {
3126 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
3833 if let Err(error) = remote
3834 .signaling
3835 .caption_command(&url, BotAction::Start, &remote.participant)
3836 .await
3837 {
3127 3838 timeline.record("caption start failed", error.to_string());
3128 3839 return fail(flow, start_failure);
3129 3840 }
3130 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
3841 if let Err(error) = remote
3842 .signaling
3843 .set_caption_preference(&remote.conversation, &remote.participant, true)
3844 .await
3845 {
3131 3846 timeline.record("caption preference failed", error.to_string());
3132 3847 }
3133 3848 }
3134 3849 BotJob::Recording => {
3135 let started = remote.signaling.recording_command(&url, plan.start(), &remote.participant, &plan.title).await;
3850 let started = remote
3851 .signaling
3852 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
3853 .await;
3136 3854 let failed = started.is_err();
3137 report_organizer_result(started, "recording start", start_failure, control, timeline);
3855 report_organizer_result(
3856 started,
3857 "recording start",
3858 start_failure,
3859 control,
3860 timeline,
3861 );
3138 3862 if failed {
3139 3863 return fail(flow, start_failure);
3140 3864 }
@@ -3142,13 +3866,27 @@ async fn run_bot_steps(
3142 3866 }
3143 3867 }
3144 3868 CaptionStep::Stop => {
3145 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };
3869 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3870 continue;
3871 };
3146 3872 match job {
3147 3873 BotJob::Captions => {
3148 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {
3874 if let Err(error) = remote
3875 .signaling
3876 .caption_command(&url, BotAction::Stop, &remote.participant)
3877 .await
3878 {
3149 3879 timeline.record("caption stop failed", error.to_string());
3150 3880 }
3151 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
3881 if let Err(error) = remote
3882 .signaling
3883 .set_caption_preference(
3884 &remote.conversation,
3885 &remote.participant,
3886 false,
3887 )
3888 .await
3889 {
3152 3890 timeline.record("caption preference failed", error.to_string());
3153 3891 }
3154 3892 }
@@ -3157,18 +3895,29 @@ async fn run_bot_steps(
3157 3895 let updates = control.updates();
3158 3896 let (command, title) = (plan.stop(), plan.title.clone());
3159 3897 tokio::spawn(async move {
3160 let mut stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3898 let mut stopped = remote
3899 .signaling
3900 .recording_command(&url, command, &remote.participant, &title)
3901 .await;
3161 3902 for _ in 0..RECORDING_STOP_RETRIES {
3162 3903 if !stopped.as_ref().is_err_and(recorder_busy) {
3163 3904 break;
3164 3905 }
3165 3906 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3166 stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3907 stopped = remote
3908 .signaling
3909 .recording_command(&url, command, &remote.participant, &title)
3910 .await;
3167 3911 }
3168 3912 if stopped.is_err() {
3169 let _ = updates.send(CallUpdate::Notice("The recording could not be stopped".into()));
3913 let _ = updates.send(CallUpdate::Notice(
3914 RECORDING_STOP_FAILED_NOTICE.into(),
3915 ));
3170 3916 }
3171 let _ = updates.send(CallUpdate::Organizer { action: "recording stop".into(), outcome: stopped.map_err(|error| error.to_string()) });
3917 let _ = updates.send(CallUpdate::Organizer {
3918 action: "recording stop".into(),
3919 outcome: stopped.map_err(|error| error.to_string()),
3920 });
3172 3921 });
3173 3922 }
3174 3923 }
@@ -3188,7 +3937,12 @@ fn send_receive_change(control: &CallControl, change: ReceiveChange) {
3188 3937 }
3189 3938 }
3190 3939
3191 fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
3940 fn record_audio_devices(
3941 timeline: &Timeline,
3942 lists: &devices::DeviceLists,
3943 input: Option<&AppliedDevice>,
3944 output: Option<&AppliedDevice>,
3945 ) {
3192 3946 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3193 3947 applied
3194 3948 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
@@ -3197,7 +3951,11 @@ fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input
3197 3951 };
3198 3952 timeline.record(
3199 3953 "audio devices",
3200 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
3954 format!(
3955 "input={} output={}",
3956 name(&lists.inputs, input),
3957 name(&lists.outputs, output)
3958 ),
3201 3959 );
3202 3960 }
3203 3961
@@ -3211,19 +3969,31 @@ fn follow_device_change(
3211 3969 control: &CallControl,
3212 3970 ) -> bool {
3213 3971 let system_default = devices::system_default_id(flow);
3214 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3215 Reselect::Keep => return false,
3216 Reselect::Select(index) => (index, false),
3217 Reselect::FallBack(index) => (index, true),
3218 };
3972 let (index, fell_back) =
3973 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3974 Reselect::Keep => return false,
3975 Reselect::Select(index) => (index, false),
3976 Reselect::FallBack(index) => (index, true),
3977 };
3219 3978 let selected = select(index);
3220 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
3979 timeline.record(
3980 "device change",
3981 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
3982 );
3221 3983 if selected {
3222 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
3984 *applied = current
3985 .iter()
3986 .find(|device| device.index == index)
3987 .map(|device| AppliedDevice {
3988 index,
3989 key: device.key(),
3990 });
3223 3991 }
3224 3992 if fell_back {
3225 3993 let fallback = current.iter().find(|device| device.index == index);
3226 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
3994 control.send(CallUpdate::Notice(devices::disconnect_notice(
3995 previous, choice, fallback,
3996 )));
3227 3997 }
3228 3998 selected
3229 3999 }
@@ -3250,16 +4020,27 @@ fn apply_mute(
3250 4020 tokio::spawn(async move {
3251 4021 let _ = remote
3252 4022 .signaling
3253 .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted)
4023 .update_endpoint_state(
4024 &remote.conversation,
4025 &remote.participant,
4026 effect.endpoint_is_muted,
4027 )
3254 4028 .await;
3255 4029 });
3256 4030 effect.muted
3257 4031 }
3258 4032
3259 fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {
4033 fn silence_for_hold(
4034 on_hold: bool,
4035 muted: bool,
4036 audio: Option<&AudioSetup>,
4037 software_audio: Option<&SoftwareAudio>,
4038 ) {
3260 4039 let silent = on_hold || muted;
3261 4040 if let Some(audio) = audio {
3262 audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);
4041 audio
4042 .track
4043 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
3263 4044 }
3264 4045 if let Some(software_audio) = software_audio {
3265 4046 software_audio.set_microphone_muted(silent);
@@ -3277,7 +4058,10 @@ fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()>
3277 4058 .map_err(|error| Error::Webrtc(error.to_string()))
3278 4059 }
3279 4060
3280 fn outgoing_track<'a>(software_audio: Option<&'a SoftwareAudio>, device_track: &'a RtcAudioTrack) -> &'a RtcAudioTrack {
4061 fn outgoing_track<'a>(
4062 software_audio: Option<&'a SoftwareAudio>,
4063 device_track: &'a RtcAudioTrack,
4064 ) -> &'a RtcAudioTrack {
3281 4065 pick_track(software_audio.map(|audio| &audio.track), device_track)
3282 4066 }
3283 4067
@@ -3292,12 +4076,22 @@ fn software_wanted(
3292 4076 audio: Option<&AudioSetup>,
3293 4077 ) -> Option<SoftwareAudioPlan> {
3294 4078 let sharing_sound = share_sound_wanted && local_video.sharing();
3295 SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))
4079 SoftwareAudioPlan::wanted(
4080 mic_settings,
4081 sharing_sound,
4082 audio.is_some_and(AudioSetup::uses_devices),
4083 )
3296 4084 }
3297 4085
3298 fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
4086 fn restore_device_track(
4087 factory: &PeerConnectionFactory,
4088 input: &DeviceChoice,
4089 peer: &PeerConnection,
4090 device_track: &RtcAudioTrack,
4091 timeline: &Timeline,
4092 ) {
3299 4093 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3300 if cfg!(windows) && !factory.adm_recording_enabled() {
4094 if !factory.adm_recording_enabled() {
3301 4095 factory.set_adm_recording_enabled(true);
3302 4096 devices::select_input(factory, input);
3303 4097 }
@@ -3325,6 +4119,9 @@ fn sync_software_audio(
3325 4119 if running == wanted && !restart {
3326 4120 return;
3327 4121 }
4122 if running.is_some() {
4123 timeline.record("software audio", "stopping");
4124 }
3328 4125 *software_audio = None;
3329 4126 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3330 4127 let Some(plan) = wanted else {
@@ -3332,15 +4129,26 @@ fn sync_software_audio(
3332 4129 control.send(CallUpdate::ShareSound(false));
3333 4130 return;
3334 4131 };
3335 let started = SoftwareAudio::start(factory, options.audio, options.tone_hz, input, plan, muted, remote_audio)
3336 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4132 let started = SoftwareAudio::start(
4133 factory,
4134 options.audio,
4135 options.tone_hz,
4136 input,
4137 plan,
4138 muted,
4139 remote_audio,
4140 )
4141 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
3337 4142 match started {
3338 4143 Ok(audio) => {
3339 timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));
4144 timeline.record(
4145 "software audio",
4146 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4147 );
3340 4148 if let Some(source) = &audio.microphone_source {
3341 4149 timeline.record("mic capture", source.clone());
3342 4150 }
3343 if cfg!(windows) && audio.microphone_source.is_some() {
4151 if audio.microphone_source.is_some() {
3344 4152 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3345 4153 factory.set_adm_recording_enabled(false);
3346 4154 }
@@ -3366,7 +4174,13 @@ fn sync_software_audio(
3366 4174 }
3367 4175 }
3368 4176
3369 async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
4177 async fn tear_down(
4178 mut live: Live,
4179 inner: &Inner,
4180 timeline: &Timeline,
4181 report: &mut CallReport,
4182 cancelled: bool,
4183 ) {
3370 4184 for peer in &live.peers {
3371 4185 peer.close();
3372 4186 }
@@ -3377,8 +4191,16 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
3377 4191 if !live.skip_leave
3378 4192 && let Some(remote) = &live.remote
3379 4193 {
3380 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
3381 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
4194 let reason = if cancelled {
4195 LeaveReason::Cancel
4196 } else {
4197 LeaveReason::Hangup
4198 };
4199 match remote
4200 .signaling
4201 .leave(&remote.conversation, &remote.participant, reason)
4202 .await
4203 {
3382 4204 Ok(()) => report.left_cleanly = true,
3383 4205 Err(error) => timeline.record("leave failed", error.to_string()),
3384 4206 }
@@ -3422,31 +4244,53 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
3422 4244 let body = decode_body(callback)?;
3423 4245 let (_, event) = classify(&callback.path, body)?;
3424 4246 let detail = match &event {
3425 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
3426 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
4247 CallEvent::Acceptance(acceptance) => format!(
4248 "answer sdp {} bytes, fromMixer={}",
4249 acceptance.sdp.len(),
4250 acceptance.from_mixer
4251 ),
4252 CallEvent::End(end) => format!(
4253 "code={} subCode={} phrase={}",
4254 end.code, end.sub_code, end.phrase
4255 ),
3427 4256 CallEvent::Progress(status) => format!("{status:?}"),
3428 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
3429 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
4257 CallEvent::ConversationEnd(body)
4258 | CallEvent::Rejection(body)
4259 | CallEvent::AddParticipantFailure(body)
4260 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4261 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4262 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
3430 4263 _ => String::new(),
3431 4264 };
3432 4265 timeline.record(format!("Trouter {}", event.name()), detail);
3433 4266 match &event {
3434 4267 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
3435 4268 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
3436 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
4269 CallEvent::MediaRenegotiation(renegotiation) => {
4270 timeline.record_sdp("remote offer", &renegotiation.sdp)
4271 }
3437 4272 _ => {}
3438 4273 }
3439 4274 Ok(event)
3440 4275 }
3441 4276
3442
3443 async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4277 async fn apply_answer(
4278 peer: &PeerConnection,
4279 teams_answer: &str,
4280 signaled: &SignaledOffer,
4281 browser_offer: &str,
4282 ) -> Result<()> {
3444 4283 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3445 4284 set_browser_answer(peer, &answer).await
3446 4285 }
3447 4286
3448 4287 /// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
3449 async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4288 async fn apply_hold_answer(
4289 peer: &PeerConnection,
4290 teams_answer: &str,
4291 signaled: &SignaledOffer,
4292 browser_offer: &str,
4293 ) -> Result<()> {
3450 4294 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3451 4295 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
3452 4296 }
@@ -3471,7 +4315,10 @@ fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
3471 4315 return format!("{prefix}<masked>");
3472 4316 }
3473 4317 }
3474 line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ")
4318 line.split(' ')
4319 .map(mask_address)
4320 .collect::<Vec<_>>()
4321 .join(" ")
3475 4322 })
3476 4323 .collect();
3477 4324 let _ = std::fs::create_dir_all(directory);
@@ -3482,8 +4329,16 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3482 4329 let Some(directory) = &options.sdp_dump_dir else {
3483 4330 return;
3484 4331 };
3485 let mut lines: Vec<String> =
3486 timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();
4332 let mut lines: Vec<String> = timeline
4333 .entries()
4334 .iter()
4335 .map(|entry| {
4336 format!(
4337 "{:>6} ms {} {}",
4338 entry.elapsed_ms, entry.label, entry.detail
4339 )
4340 })
4341 .collect();
3487 4342 lines.push(match failure {
3488 4343 Some(error) => format!("failed: {error}"),
3489 4344 None => "ended without error".to_owned(),
@@ -3493,9 +4348,13 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3493 4348 }
3494 4349
3495 4350 fn mask_address(token: &str) -> String {
3496 let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
3497 let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
3498 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address {
4351 let dotted_quad =
4352 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
4353 let colon_address =
4354 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
4355 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
4356 || colon_address
4357 {
3499 4358 "<addr>".to_owned()
3500 4359 } else {
3501 4360 token.to_owned()
@@ -3516,7 +4375,11 @@ async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, to
3516 4375 }
3517 4376 }
3518 4377
3519 async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) {
4378 async fn poll_broker(
4379 signaling: Arc<Signaling>,
4380 conversation: Conversation,
4381 running: Arc<AtomicBool>,
4382 ) {
3520 4383 let Ok(first) = conversation.link("subscribe") else {
3521 4384 return;
3522 4385 };
@@ -3564,25 +4427,17 @@ struct ShareReceive {
3564 4427 pli_count: u32,
3565 4428 fir_count: u32,
3566 4429 freeze_count: u32,
3567 qp_sum: u64,
3568 bytes_received: u64,
3569 4430 }
3570 4431
3571 4432 impl ShareReceive {
3572 fn average_qp(&self) -> u64 {
3573 self.qp_sum.checked_div(u64::from(self.frames_decoded)).unwrap_or(0)
3574 }
3575
3576 4433 fn summary(&self) -> String {
3577 4434 format!(
3578 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
4435 " share in decoded={} keyframes={} {}x{} fps={:.0} pli={} fir={} freezes={}",
3579 4436 self.frames_decoded,
3580 4437 self.key_frames_decoded,
3581 4438 self.width,
3582 4439 self.height,
3583 4440 self.frames_per_second,
3584 self.average_qp(),
3585 self.bytes_received,
3586 4441 self.pli_count,
3587 4442 self.fir_count,
3588 4443 self.freeze_count
@@ -3606,7 +4461,10 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3606 4461 }
3607 4462 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
3608 4463 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
3609 snapshot.source_levels.push(format!("{}={:.3}", source.source.track_identifier, source.audio.audio_level));
4464 snapshot.source_levels.push(format!(
4465 "{}={:.3}",
4466 source.source.track_identifier, source.audio.audio_level
4467 ));
3610 4468 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
3611 4469 }
3612 4470 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
@@ -3626,24 +4484,32 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3626 4484 pli_count: inbound.inbound.pli_count,
3627 4485 fir_count: inbound.inbound.fir_count,
3628 4486 freeze_count: inbound.inbound.freeze_count,
3629 qp_sum: inbound.inbound.qp_sum,
3630 bytes_received: inbound.inbound.bytes_received,
3631 4487 });
3632 4488 }
3633 4489 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
3634 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
3635 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
4490 snapshot.video.inbound_width = snapshot
4491 .video
4492 .inbound_width
4493 .max(inbound.inbound.frame_width);
4494 snapshot.video.inbound_height = snapshot
4495 .video
4496 .inbound_height
4497 .max(inbound.inbound.frame_height);
3636 4498 }
3637 4499 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
3638 4500 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
3639 snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0);
4501 snapshot.video.remote_round_trip_ms = snapshot
4502 .video
4503 .remote_round_trip_ms
4504 .max(remote.remote_inbound.round_trip_time * 1000.0);
3640 4505 }
3641 4506 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
3642 4507 snapshot.video.outbound_packets += outbound.sent.packets_sent;
3643 4508 if share_mids.contains(&outbound.outbound.mid) {
3644 4509 snapshot.share_outbound_packets += outbound.sent.packets_sent;
3645 4510 }
3646 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
4511 snapshot.video.outbound_frames_encoded +=
4512 u64::from(outbound.outbound.frames_encoded);
3647 4513 snapshot.video_senders.push(format!(
3648 4514 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
3649 4515 outbound.outbound.mid,
@@ -3656,8 +4522,14 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3656 4522 outbound.outbound.quality_limitation_reason,
3657 4523 outbound.outbound.active
3658 4524 ));
3659 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
3660 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
4525 snapshot.video.outbound_width = snapshot
4526 .video
4527 .outbound_width
4528 .max(outbound.outbound.frame_width);
4529 snapshot.video.outbound_height = snapshot
4530 .video
4531 .outbound_height
4532 .max(outbound.outbound.frame_height);
3661 4533 }
3662 4534 RtcStats::Transport(transport) => {
3663 4535 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
@@ -3681,13 +4553,23 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3681 4553 stats
3682 4554 .iter()
3683 4555 .find_map(|entry| match entry {
3684 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate),
3685 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate),
4556 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
4557 Some(&local.local_candidate)
4558 }
4559 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
4560 Some(&remote.remote_candidate)
4561 }
3686 4562 _ => None,
3687 4563 })
3688 4564 .map(|candidate| {
3689 let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default();
3690 let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default();
4565 let kind = candidate
4566 .candidate_type
4567 .map(|kind| format!("{kind:?}"))
4568 .unwrap_or_default();
4569 let relay = candidate
4570 .relay_protocol
4571 .map(|relay| format!(" via {relay:?}"))
4572 .unwrap_or_default();
3691 4573 format!("{kind}/{}{relay}", candidate.protocol)
3692 4574 })
3693 4575 .unwrap_or_else(|| "?".into())
@@ -3704,22 +4586,24 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3704 4586
3705 4587 #[cfg(test)]
3706 4588 mod tests {
3707 #[test]
3708 fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {
3709 assert!(!gathering_settled(false, None));
3710 assert!(!gathering_settled(false, Some(Duration::from_millis(50))));
3711 assert!(gathering_settled(false, Some(RELAY_SETTLE)));
3712 assert!(gathering_settled(true, None));
3713 }
3714
3715 4589 #[tokio::test]
3716 4590 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
3717 4591 let (handle, mut control) = crate::control::call_channel();
3718 4592 handle.commands.send(CallCommand::Hangup).unwrap();
3719 4593 let limit = Duration::from_millis(20);
3720 let cancelled = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4594 let cancelled = setup_step_within(
4595 &mut control,
4596 limit,
4597 std::future::pending::<std::result::Result<(), Error>>(),
4598 )
4599 .await;
3721 4600 assert!(matches!(cancelled, Err(Error::Cancelled)));
3722 let timed_out = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4601 let timed_out = setup_step_within(
4602 &mut control,
4603 limit,
4604 std::future::pending::<std::result::Result<(), Error>>(),
4605 )
4606 .await;
3723 4607 assert!(matches!(timed_out, Err(Error::Signaling(_))));
3724 4608 }
3725 4609
@@ -3734,8 +4618,12 @@ mod tests {
3734 4618
3735 4619 #[test]
3736 4620 fn only_a_conflict_answer_retries_a_recording_stop() {
3737 assert!(recorder_busy(&Error::Signaling("recording command answered HTTP 409 no answer".into())));
3738 assert!(!recorder_busy(&Error::Signaling("recording command answered HTTP 500 no answer".into())));
4621 assert!(recorder_busy(&Error::Signaling(
4622 "recording command answered HTTP 409 no answer".into()
4623 )));
4624 assert!(!recorder_busy(&Error::Signaling(
4625 "recording command answered HTTP 500 no answer".into()
4626 )));
3739 4627 assert!(!recorder_busy(&Error::Cancelled));
3740 4628 }
3741 4629
@@ -3767,14 +4655,21 @@ mod tests {
3767 4655 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
3768 4656
3769 4657 fn directions(sdp: &str) -> Vec<String> {
3770 crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
4658 crate::sdp::parse(sdp)
4659 .unwrap()
4660 .media
4661 .iter()
4662 .map(|line| line.direction().unwrap_or("none").to_owned())
4663 .collect()
3771 4664 }
3772 4665
3773 4666 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
3774 4667 use libwebrtc::audio_source::native::NativeAudioSource;
3775 4668 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3776 4669 let factory = devices::shared_factory();
3777 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4670 let peer = factory
4671 .create_peer_connection(RtcConfiguration::default())
4672 .unwrap();
3778 4673 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3779 4674 let track = factory.create_audio_track("microphone", source);
3780 4675 let offer = create_offer(&peer, &factory, &track, layout, None).await;
@@ -3796,11 +4691,22 @@ mod tests {
3796 4691 use libwebrtc::audio_source::native::NativeAudioSource;
3797 4692 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3798 4693 let factory = devices::shared_factory();
3799 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4694 let peer = factory
4695 .create_peer_connection(RtcConfiguration::default())
4696 .unwrap();
3800 4697 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3801 4698 let track = factory.create_audio_track("microphone", source);
3802 4699 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3803 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
4700 let answered = answer_offer(
4701 &peer,
4702 Some(&track),
4703 offer,
4704 AnswerVideo::Receive,
4705 None,
4706 false,
4707 None,
4708 )
4709 .await;
3804 4710 peer.close();
3805 4711 if let Err(error) = answered {
3806 4712 panic!("{error}");
@@ -3809,51 +4715,144 @@ mod tests {
3809 4715
3810 4716 #[test]
3811 4717 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3812 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3813 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3814 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
4718 assert_eq!(
4719 directions(&directions_for(
4720 Layout::OneToOne,
4721 false,
4722 false,
4723 false,
4724 CAMERA_MID,
4725 Some(ONE_TO_ONE_SHARE_MID),
4726 false,
4727 BROWSER_OFFER
4728 )),
4729 vec!["sendrecv", "inactive", "inactive"]
4730 );
4731 assert_eq!(
4732 directions(&directions_for(
4733 Layout::OneToOne,
4734 false,
4735 true,
4736 false,
4737 CAMERA_MID,
4738 Some(ONE_TO_ONE_SHARE_MID),
4739 false,
4740 BROWSER_OFFER
4741 )),
4742 vec!["sendrecv", "sendrecv", "inactive"]
4743 );
4744 assert_eq!(
4745 directions(&directions_for(
4746 Layout::OneToOne,
4747 false,
4748 false,
4749 true,
4750 CAMERA_MID,
4751 Some(ONE_TO_ONE_SHARE_MID),
4752 false,
4753 BROWSER_OFFER
4754 )),
4755 vec!["sendrecv", "inactive", "sendonly"]
4756 );
3815 4757 }
3816 4758
3817 4759 #[test]
3818 4760 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3819 4761 for layout in [Layout::OneToOne, Layout::Conference] {
3820 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
4762 assert_eq!(
4763 directions(&directions_for(
4764 layout,
4765 true,
4766 true,
4767 false,
4768 CAMERA_MID,
4769 None,
4770 false,
4771 BROWSER_OFFER
4772 )),
4773 vec!["inactive", "inactive", "inactive"]
4774 );
3821 4775 }
3822 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
4776 assert_eq!(
4777 directions_for(
4778 Layout::Conference,
4779 false,
4780 true,
4781 false,
4782 CAMERA_MID,
4783 None,
4784 false,
4785 BROWSER_OFFER
4786 ),
4787 BROWSER_OFFER
4788 );
3823 4789 }
3824 4790
3825 4791 #[test]
3826 4792 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3827 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
4793 let held = directions_for(
4794 Layout::Conference,
4795 true,
4796 false,
4797 false,
4798 CAMERA_MID,
4799 None,
4800 false,
4801 BROWSER_OFFER,
4802 );
3828 4803 let mut numbers = || 7;
3829 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3830 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
4804 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers)
4805 .unwrap()
4806 .sdp;
4807 assert_eq!(
4808 directions(&signaled),
4809 vec!["inactive", "inactive", "inactive"]
4810 );
3831 4811 assert_eq!(signaled.matches("a=candidate:").count(), 1);
3832 4812 }
3833 4813
3834 4814 #[test]
3835 4815 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
3836 let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
3837 assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));
3838 assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));
4816 let target = |thread: &str| MeetingTarget {
4817 thread_id: thread.into(),
4818 tenant_id: "t".into(),
4819 organizer_id: "o".into(),
4820 meeting_data: None,
4821 };
4822 assert!(is_own_meeting(
4823 Some(&target("19:meeting_a@thread.v2")),
4824 &target("19:meeting_a@thread.v2")
4825 ));
4826 assert!(!is_own_meeting(
4827 Some(&target("19:meeting_a@thread.v2")),
4828 &target("19:meeting_b@thread.v2")
4829 ));
3839 4830 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
3840 4831 }
3841 4832
3842 4833 #[test]
3843 4834 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
3844 4835 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
3845 assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);
4836 assert_eq!(
4837 accepted_modalities(true),
4838 vec!["Audio".to_owned(), "Video".to_owned()]
4839 );
3846 4840 }
3847 4841
3848 4842 #[test]
3849 4843 fn specs_map_to_invitation_targets() {
3850 4844 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
3851 4845 let people = CallSpec::People {
3852 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
4846 callees: vec![Callee {
4847 mri: "8:orgid:b".into(),
4848 display_name: "Bea".into(),
4849 }],
3853 4850 thread_id: "19:t@thread.v2".into(),
3854 4851 };
3855 4852 assert!(people.is_people() && !people.is_meeting());
3856 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
4853 assert!(
4854 matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")
4855 );
3857 4856 let meeting = CallSpec::Meeting(MeetingTarget {
3858 4857 thread_id: "19:meeting@thread.v2".into(),
3859 4858 tenant_id: "t".into(),
@@ -1,7 +1,7 @@
1use std::collections::BTreeMap;
1use std::collections::BTreeMap;
2use std::path::PathBuf;
2use std::path::PathBuf;
3use std::sync::Arc;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::Duration;
5use std::time::Duration;
6
6
7use chatsvc::TrouterCallback;
7use chatsvc::TrouterCallback;
@@ -24,51 +24,86 @@ use crate::background::{BackgroundChoice, BackgroundPicture};
24use crate::breakout::{self, RoomWatcher};
24use crate::breakout::{self, RoomWatcher};
25use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
25use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
26use crate::camera::{CameraDevice, list_cameras};
26use crate::camera::{CameraDevice, list_cameras};
27use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
27use crate::captions::{
28use crate::captions::{
28 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
29 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
29 parse_caption_message,
30 parse_caption_message,
30};
31};
31use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
32use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
32use crate::diagnostics::{CallDiagnostics, StatsSample};
33use crate::data_channel::Depacketizer;
33use crate::data_channel::Depacketizer;
34use crate::device_watch::{self, Debounce};
34use crate::device_watch::{self, Debounce};
35use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
35use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
36use crate::diagnostics::{CallDiagnostics, StatsSample};
36use crate::end::EndKind;
37use crate::end::EndKind;
37use crate::engine::{CallEngine, EngineConfig, Inner};
38use crate::engine::{CallEngine, EngineConfig, Inner};
38use crate::error::{Error, Result};
39use crate::error::{Error, Result};
39use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
40use crate::health::{
40use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, offer_sends_video, rewrite_directions, stop_sending_on};
41 CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats,
42};
43use crate::hold::{
44 HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, is_hold, keep_media_running,
45 offer_modalities, offer_sends_video, rewrite_directions, stop_sending_on,
46};
47use crate::meeting_options::{self, OptionWrite};
41use crate::mic_processing::MicSettings;
48use crate::mic_processing::MicSettings;
42use crate::mute::{MuteCommand, MuteEffect};
49use crate::mute::{MuteCommand, MuteEffect};
43use crate::push::CallNotification;
50use crate::notices::{
44use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant};
51 ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,
45use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
52 BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,
46use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
53 CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTIONS_JOIN_FAILED_NOTICE,
47use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
54 CAPTION_LANGUAGE_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE, CHANGE_RUNNING_NOTICE,
55 CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE, DENY_FAILED_NOTICE,
56 HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE,
57 LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE,
58 MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE,
59 MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE,
60 RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE,
61 CAPTIONS_START_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE, RECORDING_NOT_STARTED_NOTICE,
62 RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE,
63 REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE,
64 SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE,
65 STOP_SPOTLIGHT_FAILED_NOTICE, TRANSFER_CALL_FAILED_NOTICE, TRANSFER_FAILED_NOTICE,
66 TRANSFER_NOT_ALLOWED_NOTICE, TRANSFERRING_NOTICE, VIDEO_FAILED_NOTICE,
67 WHITEBOARD_OPEN_FAILED_NOTICE, WHITEBOARDS_MEETINGS_ONLY_NOTICE, notice_with_detail,
68};
48use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
69use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
49use crate::meeting_options::{self, OptionWrite};
70use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
71use crate::push::CallNotification;
50use crate::recording::{Consent, RecordingPlan, RecordingStatus};
72use crate::recording::{Consent, RecordingPlan, RecordingStatus};
73use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
74use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
51use crate::roster::{Roster, direct_roster};
75use crate::roster::{Roster, direct_roster};
52use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
76use crate::screen::{
77 ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources,
78 share_sources_for_menu, share_thumbnail,
79};
80use crate::sdp::{
81 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
82 to_browser_answer, to_teams_answer, to_teams_offer,
83};
84use crate::send_control::{RequestFilter, parse_request};
53use crate::signaling::{
85use crate::signaling::{
54 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
86 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
55 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
87 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
88 escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body,
56};
89};
57use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
90use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
58use crate::state::{CallSignal, CallState};
91use crate::state::{CallSignal, CallState};
59use crate::timeline::{Timeline, TimelineEntry};
92use crate::timeline::{Timeline, TimelineEntry};
60use crate::transfer::{Replacement, TransferEvent, TransferTarget};
93use crate::transfer::{Replacement, TransferEvent, TransferTarget};
94use crate::trouter_events::{
95 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
96};
61use crate::video_frame::{VideoKey, VideoPicture};
97use crate::video_frame::{VideoKey, VideoPicture};
62use crate::video_layout::{
98use crate::video_layout::{
63 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
99 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter,
100 SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines,
101 offer_plan, one_to_one_plan,
64};
102};
65use crate::send_control::{RequestFilter, parse_request};
103use crate::video_receive::{
66use crate::video_send::{LocalVideo, SendSource, VideoMode};
104 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
67use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
68use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
69use crate::trouter_events::{
70 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
71};
105};
106use crate::video_send::{LocalVideo, SendSource, VideoMode};
72use crate::whiteboard;
107use crate::whiteboard;
73
108
74const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
109const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
@@ -92,15 +127,16 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
92const BOT_PREFIX: &str = "28:";
127const BOT_PREFIX: &str = "28:";
93const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
128const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
94const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
129const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
130/// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends.
131const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15);
95const GATHERING_LIMIT: Duration = Duration::from_secs(5);
132const GATHERING_LIMIT: Duration = Duration::from_secs(5);
96const RELAY_SETTLE: Duration = Duration::from_millis(200);
133const GATHERING_QUIET: Duration = Duration::from_millis(500);
97const GATHERING_POLL: Duration = Duration::from_millis(50);
134const GATHERING_POLL: Duration = Duration::from_millis(50);
98const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
135const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
99const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
136const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
100const GLARE_CODE: i64 = 491;
137const GLARE_CODE: i64 = 491;
101const RETARGET_WAIT: Duration = Duration::from_secs(20);
138const RETARGET_WAIT: Duration = Duration::from_secs(20);
102const CAMERA_STREAM: &str = "camera";
139const CAMERA_STREAM: &str = "camera";
103const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
104
140
105#[derive(Debug, Clone)]
141#[derive(Debug, Clone)]
106pub struct CallOptions {
142pub struct CallOptions {
@@ -199,7 +235,10 @@ pub struct CallReport {
199#[derive(Debug, Clone)]
235#[derive(Debug, Clone)]
200pub enum CallSpec {
236pub enum CallSpec {
201 Echo,
237 Echo,
202 People { callees: Vec<Callee>, thread_id: String },
238 People {
239 callees: Vec<Callee>,
240 thread_id: String,
241 },
203 Meeting(MeetingTarget),
242 Meeting(MeetingTarget),
204}
243}
205
244
@@ -247,11 +286,16 @@ pub(crate) enum Plan {
247}
286}
248
287
249fn data_channel_from_env() -> bool {
288fn data_channel_from_env() -> bool {
250 !matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))
289 !matches!(
290 std::env::var(DATA_CHANNEL_ENV).ok().as_deref(),
291 Some("0" | "off")
292 )
251}
293}
252
294
253pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
295pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
254 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
296 let seconds = seconds
297 .unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS)
298 .max(MIN_KEEP_ALIVE_SECONDS);
255 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
299 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
256}
300}
257
301
@@ -286,19 +330,19 @@ struct PeerSession {
286struct Gathered {
330struct Gathered {
287 candidates: Arc<std::sync::Mutex<Vec<String>>>,
331 candidates: Arc<std::sync::Mutex<Vec<String>>>,
288 complete: Arc<AtomicBool>,
332 complete: Arc<AtomicBool>,
289 relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
333 relay_seen: Arc<AtomicBool>,
290 waited_ms: Arc<AtomicU64>,
334 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
291}
292
293/// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
294fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
295 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
296}
335}
297
336
298impl Gathered {
337impl Gathered {
338 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
299 fn settled(&self) -> bool {
339 fn settled(&self) -> bool {
300 let since_udp_relay = self.relay_seen_at.lock().expect("relay time lock").map(|at| at.elapsed());
340 let quiet = self
301 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
341 .last_candidate
342 .lock()
343 .expect("candidate time lock")
344 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
345 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
302 }
346 }
303
347
304 async fn candidates(&self) -> Vec<String> {
348 async fn candidates(&self) -> Vec<String> {
@@ -307,14 +351,8 @@ impl Gathered {
307 tokio::time::sleep(GATHERING_POLL).await;
351 tokio::time::sleep(GATHERING_POLL).await;
308 }
352 }
309 self.complete.store(true, Ordering::SeqCst);
353 self.complete.store(true, Ordering::SeqCst);
310 self.waited_ms.store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
311 self.candidates.lock().expect("candidates lock").clone()
354 self.candidates.lock().expect("candidates lock").clone()
312 }
355 }
313
314 fn summary(&self) -> String {
315 let count = self.candidates.lock().expect("candidates lock").len();
316 format!("{count} candidate(s) after {} ms", self.waited_ms.load(Ordering::SeqCst))
317 }
318}
356}
319
357
320async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
358async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
@@ -439,14 +477,22 @@ pub async fn run_test_call(
439 endpoint_storage_key: "__testCallEpid".into(),
477 endpoint_storage_key: "__testCallEpid".into(),
440 },
478 },
441 };
479 };
442 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
480 let (engine, _events) =
443 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
481 CallEngine::start(session.clone(), poll_session.clone(), config).await?;
482 let report = engine
483 .run(Plan::Outgoing(CallSpec::Echo), options, control)
484 .await;
444 engine.stop().await;
485 engine.stop().await;
445 report
486 report
446}
487}
447
488
448impl CallEngine {
489impl CallEngine {
449 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
490 pub(crate) async fn run(
491 &self,
492 plan: Plan,
493 options: CallOptions,
494 mut control: CallControl,
495 ) -> Result<CallReport> {
450 let inner = self.inner.as_ref();
496 let inner = self.inner.as_ref();
451 let _one_call_at_a_time = if options.concurrent {
497 let _one_call_at_a_time = if options.concurrent {
452 None
498 None
@@ -463,7 +509,14 @@ impl CallEngine {
463 };
509 };
464 let timeline = Timeline::new(options.trace);
510 let timeline = Timeline::new(options.trace);
465 let stay_awake = crate::awake::StayAwake::new();
511 let stay_awake = crate::awake::StayAwake::new();
466 timeline.record("stay awake", if stay_awake.holding() { "system and display kept awake" } else { "not available" });
512 timeline.record(
513 "stay awake",
514 if stay_awake.holding() {
515 "system and display kept awake"
516 } else {
517 "not available"
518 },
519 );
467 let mut report = CallReport::default();
520 let mut report = CallReport::default();
468 let mut state = CallState::Idle;
521 let mut state = CallState::Idle;
469 advance(&mut state, CallSignal::Dial, &control);
522 advance(&mut state, CallSignal::Dial, &control);
@@ -493,14 +546,24 @@ impl CallEngine {
493 }
546 }
494 };
547 };
495 dump_timeline(&options, &timeline, failure.as_ref());
548 dump_timeline(&options, &timeline, failure.as_ref());
496 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
549 let cancelled = live.cancel_leave
550 || matches!(
551 &state,
552 CallState::Ended {
553 reason: crate::state::EndReason::Cancelled
554 }
555 );
497 tear_down(live, inner, &timeline, &mut report, cancelled).await;
556 tear_down(live, inner, &timeline, &mut report, cancelled).await;
498 let recording = recording.lock().await;
557 let recording = recording.lock().await;
499 report.recorded_samples = recording.samples.len();
558 report.recorded_samples = recording.samples.len();
500 report.timeline = timeline.entries();
559 report.timeline = timeline.entries();
501 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
560 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(
561 &report,
562 timeline.sdp_summaries(),
563 ))));
502 if let Some(path) = &options.wav_path {
564 if let Some(path) = &options.wav_path {
503 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
565 write_wav(path, &recording.samples)
566 .map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
504 }
567 }
505 match failure {
568 match failure {
506 Some(error) => Err(error),
569 Some(error) => Err(error),
@@ -509,23 +572,32 @@ impl CallEngine {
509 }
572 }
510}
573}
511
574
512fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {
575fn open_peer(
576 factory: &PeerConnectionFactory,
577 grant: &RelayGrant,
578 relay_host: &str,
579 with_data_channel: bool,
580) -> Result<PeerSession> {
513 let mut configuration = RtcConfiguration::default();
581 let mut configuration = RtcConfiguration::default();
514 configuration.ice_servers = vec![grant.ice_server(relay_host)];
582 configuration.ice_servers = vec![grant.ice_server(relay_host)];
515 let peer = factory
583 let peer = factory
516 .create_peer_connection(configuration)
584 .create_peer_connection(configuration)
517 .map_err(|error| Error::Webrtc(error.to_string()))?;
585 .map_err(|error| Error::Webrtc(error.to_string()))?;
518 let (sender, events) = mpsc::unbounded_channel();
586 let (sender, events) = mpsc::unbounded_channel();
519 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
587 let data_channel = with_data_channel
588 .then(|| open_data_channel(&peer, sender.clone()))
589 .transpose()?;
520 let gathered = Gathered::default();
590 let gathered = Gathered::default();
521 let candidate_sink = gathered.candidates.clone();
591 let candidate_sink = gathered.candidates.clone();
522 let relay_seen_at = gathered.relay_seen_at.clone();
592 let relay_seen = gathered.relay_seen.clone();
593 let last_candidate = gathered.last_candidate.clone();
523 peer.on_ice_candidate(Some(Box::new(move |candidate| {
594 peer.on_ice_candidate(Some(Box::new(move |candidate| {
524 if candidate.sdp_mline_index() == 0 {
595 if candidate.sdp_mline_index() == 0 {
525 let text = candidate.candidate();
596 let text = candidate.candidate();
526 if is_udp_relay(&text) {
597 if is_udp_relay(&text) {
527 relay_seen_at.lock().expect("relay time lock").get_or_insert_with(Instant::now);
598 relay_seen.store(true, Ordering::SeqCst);
528 }
599 }
600 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
529 candidate_sink.lock().expect("candidates lock").push(text);
601 candidate_sink.lock().expect("candidates lock").push(text);
530 }
602 }
531 })));
603 })));
@@ -552,10 +624,18 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
552 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
624 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
553 }
625 }
554 })));
626 })));
555 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
627 Ok(PeerSession {
628 peer,
629 events,
630 _data_channel: data_channel,
631 gathered,
632 })
556}
633}
557
634
558fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
635fn open_data_channel(
636 peer: &PeerConnection,
637 sender: mpsc::UnboundedSender<PeerEvent>,
638) -> Result<DataChannel> {
559 let channel = peer
639 let channel = peer
560 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
640 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
561 .map_err(|error| Error::Webrtc(error.to_string()))?;
641 .map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -565,7 +645,13 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
565 Ok(channel)
645 Ok(channel)
566}
646}
567
647
568fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
648fn one_to_one_directions<'a>(
649 camera: bool,
650 share: bool,
651 camera_mid: &'a str,
652 share_mid: Option<&'a str>,
653 remote_shares: bool,
654) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
569 move |line| match line.kind {
655 move |line| match line.kind {
570 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
656 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
571 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
657 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
@@ -593,15 +679,33 @@ fn share_mid_in(offer_text: &str) -> Option<String> {
593}
679}
594
680
595#[allow(clippy::too_many_arguments)]
681#[allow(clippy::too_many_arguments)]
596fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
682fn directions_for(
683 layout: Layout,
684 hold: bool,
685 camera: bool,
686 share: bool,
687 camera_mid: &str,
688 share_mid: Option<&str>,
689 remote_shares: bool,
690 text: &str,
691) -> String {
597 match (hold, layout) {
692 match (hold, layout) {
598 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
693 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
599 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
694 (false, Layout::OneToOne) => rewrite_directions(
695 text,
696 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
697 ),
600 (false, Layout::Conference) => text.to_owned(),
698 (false, Layout::Conference) => text.to_owned(),
601 }
699 }
602}
700}
603
701
604async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
702async fn create_offer(
703 peer: &PeerConnection,
704 factory: &PeerConnectionFactory,
705 track: &RtcAudioTrack,
706 layout: Layout,
707 gathered: Option<&Gathered>,
708) -> Result<OfferedMedia> {
605 let transceiver_init = RtpTransceiverInit {
709 let transceiver_init = RtpTransceiverInit {
606 direction: RtpTransceiverDirection::SendRecv,
710 direction: RtpTransceiverDirection::SendRecv,
607 stream_ids: vec![MIC_STREAM.into()],
711 stream_ids: vec![MIC_STREAM.into()],
@@ -621,7 +725,16 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
621 })
725 })
622 .await
726 .await
623 .map_err(|error| Error::Webrtc(error.to_string()))?;
727 .map_err(|error| Error::Webrtc(error.to_string()))?;
624 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
728 let browser_offer = directions_for(
729 layout,
730 false,
731 false,
732 false,
733 CAMERA_MID,
734 Some(ONE_TO_ONE_SHARE_MID),
735 false,
736 &offer.to_string(),
737 );
625 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
738 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
626 peer.set_local_description(description)
739 peer.set_local_description(description)
627 .await
740 .await
@@ -629,7 +742,13 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
629 let mut numbers = random_u32;
742 let mut numbers = random_u32;
630 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
743 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
631 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
744 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
632 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
745 Ok(OfferedMedia {
746 browser_offer,
747 signaled,
748 video,
749 plan,
750 modalities: accepted_modalities(false),
751 })
633}
752}
634
753
635struct AnsweredMedia {
754struct AnsweredMedia {
@@ -640,11 +759,20 @@ struct AnsweredMedia {
640}
759}
641
760
642fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
761fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
643 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
762 remote
763 .lines
764 .iter()
765 .find(|line| line.role == LineRole::MainVideo)
766 .and_then(|line| line.browser_mids.first().cloned())
644}
767}
645
768
646fn share_mids(remote: &RemoteOffer) -> Vec<String> {
769fn share_mids(remote: &RemoteOffer) -> Vec<String> {
647 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
770 remote
771 .lines
772 .iter()
773 .filter(|line| line.role == LineRole::ScreenShare)
774 .filter_map(|line| line.browser_mids.first().cloned())
775 .collect()
648}
776}
649
777
650async fn answer_offer(
778async fn answer_offer(
@@ -658,17 +786,32 @@ async fn answer_offer(
658) -> Result<AnsweredMedia> {
786) -> Result<AnsweredMedia> {
659 let remote = from_teams_offer(teams_offer)?;
787 let remote = from_teams_offer(teams_offer)?;
660 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
788 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
661 peer.set_remote_description(description).await.map_err(|error| {
789 peer.set_remote_description(description)
662 let lines: Vec<String> = remote.lines.iter().map(|line| format!("{:?}{:?}", line.role, line.browser_mids)).collect();
790 .await
663 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
791 .map_err(|error| {
664 })?;
792 let lines: Vec<String> = remote
793 .lines
794 .iter()
795 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
796 .collect();
797 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
798 })?;
665 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
799 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
666 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
800 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
801 Vec::new()
802 } else {
803 share_mids(&remote)
804 };
667 for transceiver in peer.transceivers() {
805 for transceiver in peer.transceivers() {
668 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
806 let is_video = matches!(
669 let unused = transceiver
807 transceiver.receiver().track(),
670 .mid()
808 Some(MediaStreamTrack::Video(_))
671 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
809 );
810 let unused = transceiver.mid().is_some_and(|mid| {
811 Some(&mid) != camera_mid.as_ref()
812 && !kept_share_mids.contains(&mid)
813 && Some(&mid) != sending_share_mid.as_ref()
814 });
672 if is_video && unused {
815 if is_video && unused {
673 let _ = transceiver.stop();
816 let _ = transceiver.stop();
674 }
817 }
@@ -686,7 +829,10 @@ async fn answer_offer(
686 .await
829 .await
687 .map_err(|error| Error::Webrtc(error.to_string()))?;
830 .map_err(|error| Error::Webrtc(error.to_string()))?;
688 let mut answer_text = answer.to_string();
831 let mut answer_text = answer.to_string();
689 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
832 for mid in kept_share_mids
833 .iter()
834 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
835 {
690 answer_text = stop_sending_on(&answer_text, mid);
836 answer_text = stop_sending_on(&answer_text, mid);
691 }
837 }
692 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
838 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
@@ -699,7 +845,12 @@ async fn answer_offer(
699 let receiving_share_mid = kept_share_mids
845 let receiving_share_mid = kept_share_mids
700 .into_iter()
846 .into_iter()
701 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
847 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
702 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
848 .find(|mid| {
849 matches!(
850 direction_of(&answer_text, mid).as_deref(),
851 Some("recvonly" | "sendrecv")
852 )
853 });
703 let mut numbers = random_u32;
854 let mut numbers = random_u32;
704 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
855 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
705 Ok(AnsweredMedia {
856 Ok(AnsweredMedia {
@@ -714,7 +865,10 @@ fn new_media_leg_id() -> String {
714 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
865 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
715}
866}
716
867
717async fn setup_step<T, E>(control: &mut CallControl, step: impl std::future::Future<Output = std::result::Result<T, E>>) -> Result<T>
868async fn setup_step<T, E>(
869 control: &mut CallControl,
870 step: impl std::future::Future<Output = std::result::Result<T, E>>,
871) -> Result<T>
718where
872where
719 Error: From<E>,
873 Error: From<E>,
720{
874{
@@ -759,12 +913,16 @@ async fn drive(
759 report: &mut CallReport,
913 report: &mut CallReport,
760) -> Result<()> {
914) -> Result<()> {
761 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
915 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
762 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
916 control.send(CallUpdate::OwnIdentity {
917 mri: own_mri.clone(),
918 });
763 let (spec, incoming) = match plan {
919 let (spec, incoming) = match plan {
764 Plan::Outgoing(spec) => (Some(spec), None),
920 Plan::Outgoing(spec) => (Some(spec), None),
765 Plan::Incoming(incoming) => (None, Some(*incoming)),
921 Plan::Incoming(incoming) => (None, Some(*incoming)),
766 };
922 };
767 let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);
923 let accept_mode = incoming
924 .as_ref()
925 .map_or(AcceptMode::Audio, |incoming| incoming.accept);
768 let (links, participant, mut callbacks, incoming_media) = match incoming {
926 let (links, participant, mut callbacks, incoming_media) = match incoming {
769 Some(IncomingCall {
927 Some(IncomingCall {
770 accept: _,
928 accept: _,
@@ -773,7 +931,12 @@ async fn drive(
773 links,
931 links,
774 participant,
932 participant,
775 callbacks,
933 callbacks,
776 }) => (links, participant, callbacks, Some((notification, attached))),
934 }) => (
935 links,
936 participant,
937 callbacks,
938 Some((notification, attached)),
939 ),
777 None => {
940 None => {
778 let links = inner.callback_links();
941 let links = inner.callback_links();
779 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
942 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
@@ -786,15 +949,26 @@ async fn drive(
786
949
787 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
950 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
788 let thread_id = control
951 let thread_id = control
789 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
952 .until_hangup(find_echo_bot_thread(
953 &inner.session,
954 &inner.identity.object_id,
955 ))
790 .await??;
956 .await??;
791 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
957 timeline.record(
958 "echo bot chat",
959 if thread_id.is_some() { "found" } else { "none" },
960 );
792 thread_id
961 thread_id
793 } else {
962 } else {
794 None
963 None
795 };
964 };
796 let grant = control.until_hangup(inner.relay.grant(&inner.session)).await??;
965 let grant = control
797 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
966 .until_hangup(fetch_relay_grant(&inner.session))
967 .await??;
968 timeline.record(
969 "GET trap/tokens",
970 format!("relay grant, expires in {} s", grant.expires_in_seconds),
971 );
798
972
799 let factory = devices::shared_factory();
973 let factory = devices::shared_factory();
800 let mut input = options.input.clone();
974 let mut input = options.input.clone();
@@ -802,15 +976,34 @@ async fn drive(
802 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
976 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
803 control.send(CallUpdate::ListenOnly(audio.listen_only));
977 control.send(CallUpdate::ListenOnly(audio.listen_only));
804 let mut device_lists = devices::list_devices(&factory);
978 let mut device_lists = devices::list_devices(&factory);
805 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
979 let mut applied_input = devices::applied_device(
806 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
980 &device_lists.inputs,
981 &input,
982 devices::system_default_id(Flow::Capture).as_deref(),
983 );
984 let mut applied_output = devices::applied_device(
985 &device_lists.outputs,
986 &output,
987 devices::system_default_id(Flow::Render).as_deref(),
988 );
807 let (_device_watcher, mut device_changes) = device_watch::watch();
989 let (_device_watcher, mut device_changes) = device_watch::watch();
808 let mut device_debounce = Debounce::default();
990 let mut device_debounce = Debounce::default();
809 timeline.record(
991 timeline.record(
810 "audio setup",
992 "audio setup",
811 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
993 format!(
994 "listen only {}, {} input(s), {} output(s); {}",
995 audio.listen_only,
996 device_lists.inputs.len(),
997 device_lists.outputs.len(),
998 audio.adm_state
999 ),
1000 );
1001 record_audio_devices(
1002 timeline,
1003 &device_lists,
1004 applied_input.as_ref(),
1005 applied_output.as_ref(),
812 );
1006 );
813 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
814 control.send(CallUpdate::Devices(device_lists.clone()));
1007 control.send(CallUpdate::Devices(device_lists.clone()));
815 control.send(CallUpdate::Selected {
1008 control.send(CallUpdate::Selected {
816 input: input.clone(),
1009 input: input.clone(),
@@ -818,7 +1011,13 @@ async fn drive(
818 });
1011 });
819 let track = audio.track.clone();
1012 let track = audio.track.clone();
820 live.audio = Some(audio);
1013 live.audio = Some(audio);
821 let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates());
1014 let mut local_video = LocalVideo::new(
1015 &factory,
1016 options.video,
1017 control.video.clone(),
1018 control.updates(),
1019 );
1020 local_video.attach_timeline(timeline.clone());
822 let mut camera_choice = options.camera.clone();
1021 let mut camera_choice = options.camera.clone();
823 if options.start_camera {
1022 if options.start_camera {
824 match local_video.preview_camera(&camera_choice) {
1023 match local_video.preview_camera(&camera_choice) {
@@ -828,9 +1027,11 @@ async fn drive(
828 }
1027 }
829 let mut media_description_request = 1u32;
1028 let mut media_description_request = 1u32;
830 refresh_cameras(control.updates(), options.video, timeline.clone());
1029 refresh_cameras(control.updates(), options.video, timeline.clone());
1030 control.send(CallUpdate::SharePicker(current_share_picker()));
831 refresh_share_sources(control.updates(), options.video, false);
1031 refresh_share_sources(control.updates(), options.video, false);
832
1032
833 let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
1033 let wants_data_channel =
1034 options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
834 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
1035 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
835 live.peers.push(current.peer.clone());
1036 live.peers.push(current.peer.clone());
836
1037
@@ -854,7 +1055,9 @@ async fn drive(
854 _ => None,
1055 _ => None,
855 };
1056 };
856 let people_thread = match &spec {
1057 let people_thread = match &spec {
857 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
1058 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => {
1059 Some(thread_id.clone())
1060 }
858 _ => incoming_media
1061 _ => incoming_media
859 .as_ref()
1062 .as_ref()
860 .filter(|(notification, _)| !notification.is_multi_party)
1063 .filter(|(notification, _)| !notification.is_multi_party)
@@ -863,7 +1066,9 @@ async fn drive(
863 .thread_id
1066 .thread_id
864 .clone()
1067 .clone()
865 .filter(|thread| *thread != notification.caller.mri)
1068 .filter(|thread| *thread != notification.caller.mri)
866 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
1069 .or_else(|| {
1070 one_to_one_thread(&inner.identity.object_id, &notification.caller.mri)
1071 })
867 }),
1072 }),
868 };
1073 };
869 let mut layout = match &spec {
1074 let mut layout = match &spec {
@@ -871,8 +1076,12 @@ async fn drive(
871 _ => Layout::Conference,
1076 _ => Layout::Conference,
872 };
1077 };
873 let peer_mri = match &spec {
1078 let peer_mri = match &spec {
874 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),
1079 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => {
875 _ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),
1080 Some(callees[0].mri.clone())
1081 }
1082 _ => incoming_media
1083 .as_ref()
1084 .map(|(notification, _)| notification.caller.mri.clone()),
876 };
1085 };
877 let mut layout_plan: OfferPlan;
1086 let mut layout_plan: OfferPlan;
878 let mut direct_video_mid: Option<String> = None;
1087 let mut direct_video_mid: Option<String> = None;
@@ -884,14 +1093,26 @@ async fn drive(
884 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
1093 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
885 let offer_started = Instant::now();
1094 let offer_started = Instant::now();
886 let media = control
1095 let media = control
887 .until_hangup(create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)))
1096 .until_hangup(create_offer(
1097 &current.peer,
1098 &factory,
1099 &track,
1100 layout,
1101 direct_invite.then_some(&current.gathered),
1102 ))
888 .await??;
1103 .await??;
889 timeline.record("offer created", format!("{} ms", offer_started.elapsed().as_millis()));
1104 timeline.record(
1105 "offer created",
1106 format!("{} ms", offer_started.elapsed().as_millis()),
1107 );
890 layout_plan = media.plan.clone();
1108 layout_plan = media.plan.clone();
891 if layout == Layout::OneToOne {
1109 if layout == Layout::OneToOne {
892 direct_video_mid = Some(CAMERA_MID.to_owned());
1110 direct_video_mid = Some(CAMERA_MID.to_owned());
893 }
1111 }
894 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
1112 timeline.record(
1113 "setLocalDescription",
1114 format!("{} m-line(s) signaled", media.signaled.lines.len()),
1115 );
895 timeline.record_sdp("local offer", &media.signaled.sdp);
1116 timeline.record_sdp("local offer", &media.signaled.sdp);
896 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
1117 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
897 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
1118 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
@@ -950,7 +1171,11 @@ async fn drive(
950 threadless: notification.thread_id.is_none(),
1171 threadless: notification.thread_id.is_none(),
951 });
1172 });
952 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
1173 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
953 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
1174 layout = if one_to_one {
1175 Layout::OneToOne
1176 } else {
1177 Layout::Conference
1178 };
954 let camera_track = local_video.camera_track();
1179 let camera_track = local_video.camera_track();
955 let video_answer = match accept_mode {
1180 let video_answer = match accept_mode {
956 _ if !one_to_one => AnswerVideo::Reject,
1181 _ if !one_to_one => AnswerVideo::Reject,
@@ -958,21 +1183,34 @@ async fn drive(
958 _ => AnswerVideo::Receive,
1183 _ => AnswerVideo::Receive,
959 };
1184 };
960 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
1185 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
961 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
1186 let answered = answer_offer(
1187 &current.peer,
1188 Some(&track),
1189 &teams_offer,
1190 video_answer,
1191 None,
1192 false,
1193 one_to_one.then_some(&current.gathered),
1194 )
1195 .await?;
962 layout_plan = answered.remote.plan();
1196 layout_plan = answered.remote.plan();
963 direct_video_mid = answered.camera_mid.clone();
1197 direct_video_mid = answered.camera_mid.clone();
964 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
1198 timeline.record(
965 if one_to_one {
1199 "setRemoteDescription",
966 timeline.record("ice gathered", current.gathered.summary());
1200 format!(
967 }
1201 "offer applied, {} signaled line(s)",
1202 answered.remote.lines.len()
1203 ),
1204 );
968 timeline.record_sdp("remote offer", &teams_offer);
1205 timeline.record_sdp("remote offer", &teams_offer);
969 timeline.record_sdp("local answer", &answered.answer_sdp);
1206 timeline.record_sdp("local answer", &answered.answer_sdp);
970 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
1207 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
971 let acceptance_url = attached
1208 let acceptance_url = attached.links.get("acceptance").ok_or_else(|| {
972 .links
1209 Error::Signaling("attach answer without an acceptance link".into())
973 .get("acceptance")
1210 })?;
974 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
1211 let modalities = accepted_modalities(
975 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
1212 matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(),
1213 );
976 let acknowledged = signaling
1214 let acknowledged = signaling
977 .accept(
1215 .accept(
978 acceptance_url,
1216 acceptance_url,
@@ -991,20 +1229,37 @@ async fn drive(
991 media_links.extend(acknowledged);
1229 media_links.extend(acknowledged);
992 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
1230 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
993 let camera = peer_transceiver(&current.peer, mid);
1231 let camera = peer_transceiver(&current.peer, mid);
994 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
1232 match camera.map(|camera| {
1233 local_video.set_lines(VideoLines {
1234 camera,
1235 share: None,
1236 })
1237 }) {
995 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
1238 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
996 Ok(()) => sending_camera = true,
1239 Ok(()) => sending_camera = true,
997 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1240 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(
1241 CAMERA_START_NOTICE,
1242 error,
1243 ))),
998 },
1244 },
999 Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),
1245 Some(Err(error)) => {
1000 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
1246 timeline.record("video lines not attached", error.to_string())
1247 }
1248 None => timeline.record(
1249 "video lines not attached",
1250 "no transceiver for the camera line",
1251 ),
1001 }
1252 }
1002 }
1253 }
1003 keep_alive_link = media_links.get("callLeg").cloned();
1254 keep_alive_link = media_links.get("callLeg").cloned();
1004 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1255 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1005 conversation
1256 conversation
1006 }
1257 }
1007 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
1258 _ => {
1259 return Err(Error::Callback(
1260 "call plan without an offer or an invitation".into(),
1261 ));
1262 }
1008 };
1263 };
1009 let remote = live.remote.clone().expect("remote call set above");
1264 let remote = live.remote.clone().expect("remote call set above");
1010 live.broker_running.store(true, Ordering::SeqCst);
1265 live.broker_running.store(true, Ordering::SeqCst);
@@ -1016,11 +1271,20 @@ async fn drive(
1016
1271
1017 let initial = MuteEffect::initial(is_meeting);
1272 let initial = MuteEffect::initial(is_meeting);
1018 let mut muted = initial.muted;
1273 let mut muted = initial.muted;
1019 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
1274 live.audio
1275 .as_ref()
1276 .expect("audio set above")
1277 .track
1278 .set_enabled(initial.track_enabled);
1020 if muted {
1279 if muted {
1021 control.send(CallUpdate::Muted(true));
1280 control.send(CallUpdate::Muted(true));
1022 }
1281 }
1023 match setup_step(control, signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted)).await {
1282 match setup_step(
1283 control,
1284 signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted),
1285 )
1286 .await
1287 {
1024 Err(Error::Cancelled) => return Err(Error::Cancelled),
1288 Err(Error::Cancelled) => return Err(Error::Cancelled),
1025 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1289 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1026 Ok(()) => {}
1290 Ok(()) => {}
@@ -1038,7 +1302,13 @@ async fn drive(
1038 && roster.apply_snapshot(snapshot)
1302 && roster.apply_snapshot(snapshot)
1039 {
1303 {
1040 let entries = roster.entries();
1304 let entries = roster.entries();
1041 timeline.record("roster", format!("{} participant(s) from the conversation answer", entries.len()));
1305 timeline.record(
1306 "roster",
1307 format!(
1308 "{} participant(s) from the conversation answer",
1309 entries.len()
1310 ),
1311 );
1042 control.send(CallUpdate::Roster(entries));
1312 control.send(CallUpdate::Roster(entries));
1043 }
1313 }
1044 let mut lobby = false;
1314 let mut lobby = false;
@@ -1063,7 +1333,25 @@ async fn drive(
1063 crate::noise_stage::apply(mic_settings);
1333 crate::noise_stage::apply(mic_settings);
1064 let mut audio_disabled = false;
1334 let mut audio_disabled = false;
1065 let mut remote_audio: Option<RtcAudioTrack> = None;
1335 let mut remote_audio: Option<RtcAudioTrack> = None;
1066 sync_software_audio(&factory, options, &input, muted, None, &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1336 sync_software_audio(
1337 &factory,
1338 options,
1339 &input,
1340 muted,
1341 None,
1342 &current.peer,
1343 &track,
1344 software_wanted(
1345 mic_settings,
1346 share_sound_wanted,
1347 &local_video,
1348 live.audio.as_ref(),
1349 ),
1350 false,
1351 &mut software_audio,
1352 control,
1353 timeline,
1354 );
1067 let mut own_hand: Option<String> = None;
1355 let mut own_hand: Option<String> = None;
1068 let mut depacketizer = Depacketizer::default();
1356 let mut depacketizer = Depacketizer::default();
1069 let mut caption_flow = CaptionFlow::default();
1357 let mut caption_flow = CaptionFlow::default();
@@ -1083,6 +1371,7 @@ async fn drive(
1083 let mut send_requests = RequestFilter::default();
1371 let mut send_requests = RequestFilter::default();
1084 let mut send_capabilities = SendCapabilityReporter::default();
1372 let mut send_capabilities = SendCapabilityReporter::default();
1085 let mut same_peer_deadline: Option<Instant> = None;
1373 let mut same_peer_deadline: Option<Instant> = None;
1374 let mut same_peer_grace_until: Option<Instant> = None;
1086 let mut meeting_chat = conversation.chat_thread.clone();
1375 let mut meeting_chat = conversation.chat_thread.clone();
1087 if let Some(thread) = &meeting_chat {
1376 if let Some(thread) = &meeting_chat {
1088 control.send(CallUpdate::MeetingChat(thread.clone()));
1377 control.send(CallUpdate::MeetingChat(thread.clone()));
@@ -1095,6 +1384,7 @@ async fn drive(
1095 }
1384 }
1096 let mut start_camera_pending = options.start_camera;
1385 let mut start_camera_pending = options.start_camera;
1097 let mut share_pending: Option<ShareSource> = None;
1386 let mut share_pending: Option<ShareSource> = None;
1387 let mut portal_pending: Option<ShareKind> = None;
1098 let mut glare_resend: Option<GlareResend> = None;
1388 let mut glare_resend: Option<GlareResend> = None;
1099 let mut deferred_changes: Vec<Change> = Vec::new();
1389 let mut deferred_changes: Vec<Change> = Vec::new();
1100 let mut remote_direct_share: Option<String> = None;
1390 let mut remote_direct_share: Option<String> = None;
@@ -1109,10 +1399,19 @@ async fn drive(
1109 {
1399 {
1110 control.defer(CallCommand::StartShare(source));
1400 control.defer(CallCommand::StartShare(source));
1111 }
1401 }
1112 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1402 if video_possible(remote_set, layout, negotiator.path())
1113 && let Some(pending) = next.take()
1403 && let Some(kind) = portal_pending.take()
1114 {
1404 {
1115 timeline.record("escalation", "new peer connection connected, old one dropped");
1405 control.defer(CallCommand::StartPortalShare(kind));
1406 }
1407 if next.as_ref().is_some_and(|pending| {
1408 pending.connected && (pending.offered.is_some() || pending.retargeted)
1409 }) && let Some(pending) = next.take()
1410 {
1411 timeline.record(
1412 "escalation",
1413 "new peer connection connected, old one dropped",
1414 );
1116 deferred_changes.clear();
1415 deferred_changes.clear();
1117 negotiator.server_escalation_done();
1416 negotiator.server_escalation_done();
1118 if let Some(mid) = remote_direct_share.take() {
1417 if let Some(mid) = remote_direct_share.take() {
@@ -1137,15 +1436,40 @@ async fn drive(
1137 timeline.record("video lines not attached", error.to_string());
1436 timeline.record("video lines not attached", error.to_string());
1138 }
1437 }
1139 if local_video.camera_on() {
1438 if local_video.camera_on() {
1140 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1439 tell_media_descriptions(
1440 &remote,
1441 &media_links,
1442 MediaDescription::camera(true),
1443 &mut media_description_request,
1444 timeline,
1445 );
1141 }
1446 }
1142 if local_video.sharing() {
1447 if local_video.sharing() {
1143 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1448 tell_media_descriptions(
1449 &remote,
1450 &media_links,
1451 MediaDescription::share(true),
1452 &mut media_description_request,
1453 timeline,
1454 );
1144 }
1455 }
1145 }
1456 }
1146 remote_set = true;
1457 remote_set = true;
1147 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1458 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1148 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1459 let pending = escalate(
1460 &factory,
1461 &grant,
1462 options,
1463 outgoing_track(software_audio.as_ref(), &track),
1464 &remote,
1465 &links,
1466 &media_leg_id,
1467 &media_links,
1468 &mut negotiator,
1469 live,
1470 timeline,
1471 )
1472 .await;
1149 if pending.is_none() {
1473 if pending.is_none() {
1150 drop_local_media(&mut local_video, control);
1474 drop_local_media(&mut local_video, control);
1151 }
1475 }
@@ -1268,6 +1592,7 @@ async fn drive(
1268 && let Some(pending) = same_peer.take()
1592 && let Some(pending) = same_peer.take()
1269 {
1593 {
1270 same_peer_deadline = None;
1594 same_peer_deadline = None;
1595 same_peer_grace_until = None;
1271 let applied = match pending.change {
1596 let applied = match pending.change {
1272 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1597 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1273 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1598 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
@@ -1287,7 +1612,7 @@ async fn drive(
1287 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1612 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1288 local_video.stop_share();
1613 local_video.stop_share();
1289 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1614 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1290 control.send(CallUpdate::LocalShare(None));
1615 clear_share(control);
1291 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1616 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1292 }
1617 }
1293 Change::Share(_) => {}
1618 Change::Share(_) => {}
@@ -1348,6 +1673,7 @@ async fn drive(
1348 && let Some(pending) = same_peer.take()
1673 && let Some(pending) = same_peer.take()
1349 {
1674 {
1350 same_peer_deadline = None;
1675 same_peer_deadline = None;
1676 same_peer_grace_until = None;
1351 negotiator.same_peer_offer_failed();
1677 negotiator.same_peer_offer_failed();
1352 rollback_offer(&current.peer).await;
1678 rollback_offer(&current.peer).await;
1353 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1679 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
@@ -1359,6 +1685,7 @@ async fn drive(
1359 MediaAction::AnswerOnNewPeer => {
1685 MediaAction::AnswerOnNewPeer => {
1360 if let Some(pending) = same_peer.take() {
1686 if let Some(pending) = same_peer.take() {
1361 same_peer_deadline = None;
1687 same_peer_deadline = None;
1688 same_peer_grace_until = None;
1362 timeline.record("same-peer offer", "superseded by the escalation offer");
1689 timeline.record("same-peer offer", "superseded by the escalation offer");
1363 rollback_offer(&current.peer).await;
1690 rollback_offer(&current.peer).await;
1364 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1691 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
@@ -1517,13 +1844,15 @@ async fn drive(
1517 recording_flow.failed();
1844 recording_flow.failed();
1518 recording_deadline = None;
1845 recording_deadline = None;
1519 control.send(CallUpdate::RecordingPending(false));
1846 control.send(CallUpdate::RecordingPending(false));
1520 control.send(CallUpdate::Notice("The recording service could not join".into()));
1847 control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into()));
1521 }
1848 }
1522 if caption_flow.wanted() && roster.caption_bot().is_none() {
1849 if caption_flow.wanted() && roster.caption_bot().is_none() {
1523 timeline.record("caption bot failed", "addParticipantFailure");
1850 timeline.record("caption bot failed", "addParticipantFailure");
1524 caption_flow.failed();
1851 caption_flow.failed();
1525 caption_deadline = None;
1852 caption_deadline = None;
1526 control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));
1853 control.send(CallUpdate::Captions(CaptionState::Failed(
1854 CAPTIONS_JOIN_FAILED_NOTICE.into(),
1855 )));
1527 }
1856 }
1528 }
1857 }
1529 Ok(CallEvent::ConversationUpdate(body)) => {
1858 Ok(CallEvent::ConversationUpdate(body)) => {
@@ -1593,14 +1922,14 @@ async fn drive(
1593 completed if completed.succeeded() => {
1922 completed if completed.succeeded() => {
1594 timeline.record("transfer", "completed");
1923 timeline.record("transfer", "completed");
1595 control.send(CallUpdate::TransferResult { succeeded: true });
1924 control.send(CallUpdate::TransferResult { succeeded: true });
1596 control.send(CallUpdate::Notice("Call transferred".into()));
1925 control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into()));
1597 advance(state, CallSignal::LocalLeave, control);
1926 advance(state, CallSignal::LocalLeave, control);
1598 break;
1927 break;
1599 }
1928 }
1600 TransferEvent::Completed { code, sub_code } => {
1929 TransferEvent::Completed { code, sub_code } => {
1601 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1930 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1602 control.send(CallUpdate::TransferResult { succeeded: false });
1931 control.send(CallUpdate::TransferResult { succeeded: false });
1603 control.send(CallUpdate::Notice("The transfer did not go through".into()));
1932 control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into()));
1604 }
1933 }
1605 }
1934 }
1606 }
1935 }
@@ -1659,6 +1988,7 @@ async fn drive(
1659 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1988 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1660 RejectedOffer::SamePeer => {
1989 RejectedOffer::SamePeer => {
1661 same_peer_deadline = None;
1990 same_peer_deadline = None;
1991 same_peer_grace_until = None;
1662 if let Some(pending) = same_peer.take() {
1992 if let Some(pending) = same_peer.take() {
1663 rollback_offer(&current.peer).await;
1993 rollback_offer(&current.peer).await;
1664 if is_glare_rejection(&body) {
1994 if is_glare_rejection(&body) {
@@ -1878,6 +2208,7 @@ async fn drive(
1878 timeline.record_sdp("local offer", &signaled.sdp);
2208 timeline.record_sdp("local offer", &signaled.sdp);
1879 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2209 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1880 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2210 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2211 same_peer_grace_until = None;
1881 }
2212 }
1882 Err(error) => {
2213 Err(error) => {
1883 timeline.record("camera offer failed", error.to_string());
2214 timeline.record("camera offer failed", error.to_string());
@@ -1889,7 +2220,7 @@ async fn drive(
1889 control.send(CallUpdate::Camera(true));
2220 control.send(CallUpdate::Camera(true));
1890 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2221 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1891 }
2222 }
1892 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
2223 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
1893 }
2224 }
1894 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2225 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1895 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2226 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -1900,6 +2231,7 @@ async fn drive(
1900 timeline.record_sdp("local offer", &signaled.sdp);
2231 timeline.record_sdp("local offer", &signaled.sdp);
1901 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2232 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1902 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2233 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2234 same_peer_grace_until = None;
1903 }
2235 }
1904 Err(error) => {
2236 Err(error) => {
1905 timeline.record("camera offer failed", error.to_string());
2237 timeline.record("camera offer failed", error.to_string());
@@ -1917,11 +2249,59 @@ async fn drive(
1917 if local_video.camera_previewing()
2249 if local_video.camera_previewing()
1918 && let Err(error) = local_video.preview_camera(&camera_choice)
2250 && let Err(error) = local_video.preview_camera(&camera_choice)
1919 {
2251 {
1920 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2252 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
1921 } else if local_video.camera_on()
2253 } else if local_video.camera_on()
1922 && let Err(error) = local_video.start_camera(&camera_choice)
2254 && let Err(error) = local_video.start_camera(&camera_choice)
1923 {
2255 {
1924 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
2256 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2257 }
2258 }
2259 Some(CallCommand::SetVideoQuality(quality)) => {
2260 local_video.set_video_quality(quality);
2261 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2262 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error)));
2263 }
2264 if video.set_video_quality(quality) {
2265 send_receive_change(control, video.reselect(&roster));
2266 }
2267 }
2268 Some(CallCommand::StartPortalShare(kind)) => {
2269 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2270 if !remote_set {
2271 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2272 } else if local_hold {
2273 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2274 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2275 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2276 } else if direct
2277 && !local_video.sharing()
2278 && !local_video.has_share_line()
2279 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2280 {
2281 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2282 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2283 if next.is_none() && negotiator.begin_conference_upgrade() {
2284 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2285 next = pending.or(next);
2286 }
2287 if next.is_some() {
2288 portal_pending = Some(kind);
2289 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2290 } else {
2291 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2292 }
2293 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2294 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2295 }
2296 }
2297 Some(CallCommand::FinishPortalShare { source, generation }) => {
2298 if local_video.accept_portal(generation) {
2299 control.defer(CallCommand::StartShare(source));
2300 }
2301 }
2302 Some(CallCommand::AbandonPortalShare) => {
2303 if local_video.portal_is_open() {
2304 local_video.stop_share();
1925 }
2305 }
1926 }
2306 }
1927 Some(CallCommand::StartShare(source)) => {
2307 Some(CallCommand::StartShare(source)) => {
@@ -1930,10 +2310,10 @@ async fn drive(
1930 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2310 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1931 } else if local_hold {
2311 } else if local_hold {
1932 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2312 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1933 } else if direct && local_video.sharing() {
2313 } else if direct && local_video.share_sending() {
1934 match local_video.start_share(&source) {
2314 match local_video.start_share(&source) {
1935 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
2315 Ok(()) => announce_share(control, &source),
1936 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2316 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
1937 }
2317 }
1938 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2318 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1939 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2319 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
@@ -1941,17 +2321,18 @@ async fn drive(
1941 && !local_video.has_share_line()
2321 && !local_video.has_share_line()
1942 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2322 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
1943 {
2323 {
1944 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
2324 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
1945 } else if direct {
2325 } else if direct {
1946 match local_video.start_share(&source) {
2326 match local_video.start_share(&source) {
1947 Ok(()) => {
2327 Ok(()) => {
1948 control.send(CallUpdate::LocalShare(Some(source.label())));
2328 announce_share(control, &source);
1949 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2329 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1950 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2330 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1951 Ok((browser_offer, signaled, reply_tags)) => {
2331 Ok((browser_offer, signaled, reply_tags)) => {
1952 timeline.record_sdp("local offer", &signaled.sdp);
2332 timeline.record_sdp("local offer", &signaled.sdp);
1953 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2333 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1954 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2334 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2335 same_peer_grace_until = None;
1955 }
2336 }
1956 Err(error) => {
2337 Err(error) => {
1957 timeline.record("share offer failed", error.to_string());
2338 timeline.record("share offer failed", error.to_string());
@@ -1959,7 +2340,7 @@ async fn drive(
1959 }
2340 }
1960 }
2341 }
1961 }
2342 }
1962 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2343 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
1963 }
2344 }
1964 } else if !video_possible(remote_set, layout, negotiator.path()) {
2345 } else if !video_possible(remote_set, layout, negotiator.path()) {
1965 if next.is_none() && negotiator.begin_conference_upgrade() {
2346 if next.is_none() && negotiator.begin_conference_upgrade() {
@@ -1975,35 +2356,39 @@ async fn drive(
1975 } else {
2356 } else {
1976 match local_video.start_share(&source) {
2357 match local_video.start_share(&source) {
1977 Ok(()) => {
2358 Ok(()) => {
1978 control.send(CallUpdate::LocalShare(Some(source.label())));
2359 announce_share(control, &source);
1979 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2360 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1980 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2361 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1981 }
2362 }
1982 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
2363 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
1983 }
2364 }
1984 }
2365 }
1985 }
2366 }
1986 Some(CallCommand::StopShare) => {
2367 Some(CallCommand::StopShare) => {
1987 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2368 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1988 share_pending = None;
2369 share_pending = None;
1989 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2370 portal_pending = None;
2371 if local_video.portal_is_open() {
2372 local_video.stop_share();
2373 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1990 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2374 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1991 } else if direct && local_video.sharing() {
2375 } else if direct && local_video.sharing() {
1992 local_video.stop_share();
2376 local_video.stop_share();
1993 control.send(CallUpdate::LocalShare(None));
2377 clear_share(control);
1994 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2378 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1995 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2379 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1996 Ok((browser_offer, signaled, reply_tags)) => {
2380 Ok((browser_offer, signaled, reply_tags)) => {
1997 timeline.record_sdp("local offer", &signaled.sdp);
2381 timeline.record_sdp("local offer", &signaled.sdp);
1998 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2382 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1999 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2383 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2384 same_peer_grace_until = None;
2000 }
2385 }
2001 Err(error) => timeline.record("share offer failed", error.to_string()),
2386 Err(error) => timeline.record("share offer failed", error.to_string()),
2002 }
2387 }
2003 } else if local_video.sharing() {
2388 } else if local_video.sharing() {
2004 local_video.stop_share();
2389 local_video.stop_share();
2005 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2390 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
2006 control.send(CallUpdate::LocalShare(None));
2391 clear_share(control);
2007 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2392 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2008 }
2393 }
2009 }
2394 }
@@ -2020,7 +2405,7 @@ async fn drive(
2020 Err(error) => {
2405 Err(error) => {
2021 timeline.record("raise hand failed", error.to_string());
2406 timeline.record("raise hand failed", error.to_string());
2022 control.send(CallUpdate::OwnHand(None));
2407 control.send(CallUpdate::OwnHand(None));
2023 control.send(CallUpdate::Notice("Could not raise your hand".into()));
2408 control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into()));
2024 }
2409 }
2025 },
2410 },
2026 Some(CallCommand::SetHand(false)) => {
2411 Some(CallCommand::SetHand(false)) => {
@@ -2031,7 +2416,7 @@ async fn drive(
2031 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2416 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2032 {
2417 {
2033 timeline.record("lower hand failed", error.to_string());
2418 timeline.record("lower hand failed", error.to_string());
2034 control.send(CallUpdate::Notice("Could not lower your hand".into()));
2419 control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into()));
2035 }
2420 }
2036 }
2421 }
2037 Some(CallCommand::LowerHand { mri }) => {
2422 Some(CallCommand::LowerHand { mri }) => {
@@ -2040,18 +2425,18 @@ async fn drive(
2040 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2425 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2041 {
2426 {
2042 timeline.record("lower hand failed", error.to_string());
2427 timeline.record("lower hand failed", error.to_string());
2043 control.send(CallUpdate::Notice("Could not lower that hand".into()));
2428 control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into()));
2044 }
2429 }
2045 }
2430 }
2046 Some(CallCommand::LowerAllHands) => {
2431 Some(CallCommand::LowerAllHands) => {
2047 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2432 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2048 timeline.record("lower all hands failed", error.to_string());
2433 timeline.record("lower all hands failed", error.to_string());
2049 control.send(CallUpdate::Notice("Could not lower all hands".into()));
2434 control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into()));
2050 }
2435 }
2051 }
2436 }
2052 Some(CallCommand::Admit { mri }) => {
2437 Some(CallCommand::Admit { mri }) => {
2053 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2438 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2054 report_organizer_result(result, "admit", "Could not admit that person", control, timeline);
2439 report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline);
2055 }
2440 }
2056 Some(CallCommand::AdmitAll) => {
2441 Some(CallCommand::AdmitAll) => {
2057 let mut result = Ok(202);
2442 let mut result = Ok(202);
@@ -2061,19 +2446,19 @@ async fn drive(
2061 break;
2446 break;
2062 }
2447 }
2063 }
2448 }
2064 report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);
2449 report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline);
2065 }
2450 }
2066 Some(CallCommand::Deny { mri }) => {
2451 Some(CallCommand::Deny { mri }) => {
2067 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2452 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2068 report_organizer_result(result, "deny", "Could not deny that person", control, timeline);
2453 report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline);
2069 }
2454 }
2070 Some(CallCommand::RemoveParticipant { mri }) => {
2455 Some(CallCommand::RemoveParticipant { mri }) => {
2071 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2456 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2072 report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);
2457 report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2073 }
2458 }
2074 Some(CallCommand::MuteParticipant { mri }) => {
2459 Some(CallCommand::MuteParticipant { mri }) => {
2075 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2460 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2076 report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);
2461 report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2077 }
2462 }
2078 Some(CallCommand::MuteAll) => {
2463 Some(CallCommand::MuteAll) => {
2079 let others: Vec<String> = roster
2464 let others: Vec<String> = roster
@@ -2083,7 +2468,7 @@ async fn drive(
2083 .map(|member| member.mri.clone())
2468 .map(|member| member.mri.clone())
2084 .collect();
2469 .collect();
2085 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2470 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2086 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
2471 report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline);
2087 }
2472 }
2088 Some(CallCommand::SetLock(locked)) => {
2473 Some(CallCommand::SetLock(locked)) => {
2089 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
2474 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
@@ -2091,11 +2476,11 @@ async fn drive(
2091 capability.locked = locked;
2476 capability.locked = locked;
2092 control.send(CallUpdate::Capability(capability));
2477 control.send(CallUpdate::Capability(capability));
2093 }
2478 }
2094 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
2479 report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline);
2095 }
2480 }
2096 Some(CallCommand::SetRole { mri, role }) => {
2481 Some(CallCommand::SetRole { mri, role }) => {
2097 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2482 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2098 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
2483 report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline);
2099 }
2484 }
2100 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2485 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2101 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
2486 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
@@ -2109,7 +2494,11 @@ async fn drive(
2109 break;
2494 break;
2110 }
2495 }
2111 }
2496 }
2112 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
2497 let notice = if modality == Modality::Mic {
2498 MIC_SETTING_FAILED_NOTICE
2499 } else {
2500 CAMERA_SETTING_FAILED_NOTICE
2501 };
2113 report_organizer_result(result, "attendee modality", notice, control, timeline);
2502 report_organizer_result(result, "attendee modality", notice, control, timeline);
2114 }
2503 }
2115 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
2504 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
@@ -2122,12 +2511,12 @@ async fn drive(
2122 capability.attendee_camera_off = camera_off;
2511 capability.attendee_camera_off = camera_off;
2123 control.send(CallUpdate::Capability(capability));
2512 control.send(CallUpdate::Capability(capability));
2124 }
2513 }
2125 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
2514 report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline);
2126 }
2515 }
2127 Some(CallCommand::Invite { callees, group_thread }) => {
2516 Some(CallCommand::Invite { callees, group_thread }) => {
2128 let thread = group_thread.or_else(|| meeting_chat.clone());
2517 let thread = group_thread.or_else(|| meeting_chat.clone());
2129 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2518 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2130 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
2519 report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline);
2131 }
2520 }
2132 Some(CallCommand::LoadMeetingOptions) => {
2521 Some(CallCommand::LoadMeetingOptions) => {
2133 let update = match &meeting_target {
2522 let update = match &meeting_target {
@@ -2151,13 +2540,13 @@ async fn drive(
2151 }
2540 }
2152 Some(CallCommand::Spotlight { mri }) => {
2541 Some(CallCommand::Spotlight { mri }) => {
2153 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2542 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2154 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
2543 report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline);
2155 }
2544 }
2156 Some(CallCommand::StopSpotlight { mri }) => {
2545 Some(CallCommand::StopSpotlight { mri }) => {
2157 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2546 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2158 if !state_ids.is_empty() {
2547 if !state_ids.is_empty() {
2159 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2548 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2160 report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);
2549 report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline);
2161 }
2550 }
2162 }
2551 }
2163 Some(CallCommand::SetCaptions(on)) => {
2552 Some(CallCommand::SetCaptions(on)) => {
@@ -2196,7 +2585,7 @@ async fn drive(
2196 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2585 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2197 {
2586 {
2198 timeline.record("caption language failed", error.to_string());
2587 timeline.record("caption language failed", error.to_string());
2199 control.send(CallUpdate::Notice("Could not change the spoken language".into()));
2588 control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into()));
2200 }
2589 }
2201 }
2590 }
2202 Some(CallCommand::ConsentToRecording) => {
2591 Some(CallCommand::ConsentToRecording) => {
@@ -2207,7 +2596,7 @@ async fn drive(
2207 }
2596 }
2208 Err(error) => {
2597 Err(error) => {
2209 timeline.record("recording consent failed", error.to_string());
2598 timeline.record("recording consent failed", error.to_string());
2210 control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));
2599 control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into()));
2211 }
2600 }
2212 }
2601 }
2213 }
2602 }
@@ -2225,32 +2614,40 @@ async fn drive(
2225 timeline.record_sdp("local offer", &signaled.sdp);
2614 timeline.record_sdp("local offer", &signaled.sdp);
2226 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2615 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2227 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2616 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2617 same_peer_grace_until = None;
2228 }
2618 }
2229 Err(error) => {
2619 Err(error) => {
2230 timeline.record("hold failed", error.to_string());
2620 timeline.record("hold failed", error.to_string());
2231 control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));
2621 control.send(CallUpdate::Notice(if hold {
2622 HOLD_FAILED_NOTICE.into()
2623 } else {
2624 RESUME_FAILED_NOTICE.into()
2625 }));
2232 }
2626 }
2233 }
2627 }
2234 }
2628 }
2235 Some(CallCommand::Transfer { target, replaces }) => {
2629 Some(CallCommand::Transfer { target, replaces }) => {
2236 let Some(url) = media_links.get("transfer").cloned() else {
2630 let Some(url) = media_links.get("transfer").cloned() else {
2237 control.send(CallUpdate::TransferResult { succeeded: false });
2631 control.send(CallUpdate::TransferResult { succeeded: false });
2238 control.send(CallUpdate::Notice("This call cannot be transferred".into()));
2632 control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into()));
2239 continue;
2633 continue;
2240 };
2634 };
2241 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2635 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2242 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2636 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2243 Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),
2637 Ok(()) => control.send(CallUpdate::Notice(notice_with_detail(
2638 TRANSFERRING_NOTICE,
2639 target.display_name,
2640 ))),
2244 Err(error) => {
2641 Err(error) => {
2245 timeline.record("transfer failed", error.to_string());
2642 timeline.record("transfer failed", error.to_string());
2246 control.send(CallUpdate::TransferResult { succeeded: false });
2643 control.send(CallUpdate::TransferResult { succeeded: false });
2247 control.send(CallUpdate::Notice("Could not transfer the call".into()));
2644 control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into()));
2248 }
2645 }
2249 }
2646 }
2250 }
2647 }
2251 Some(CallCommand::OpenWhiteboard { title }) => {
2648 Some(CallCommand::OpenWhiteboard { title }) => {
2252 let Some(target) = meeting_target.clone() else {
2649 let Some(target) = meeting_target.clone() else {
2253 control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));
2650 control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into()));
2254 continue;
2651 continue;
2255 };
2652 };
2256 let session = inner.session.clone();
2653 let session = inner.session.clone();
@@ -2258,7 +2655,7 @@ async fn drive(
2258 tokio::spawn(async move {
2655 tokio::spawn(async move {
2259 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2656 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2260 Ok(url) => CallUpdate::WhiteboardUrl(url),
2657 Ok(url) => CallUpdate::WhiteboardUrl(url),
2261 Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),
2658 Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()),
2262 };
2659 };
2263 let _ = updates.send(update);
2660 let _ = updates.send(update);
2264 });
2661 });
@@ -2285,7 +2682,7 @@ async fn drive(
2285 Some(CallCommand::SendReaction(reaction)) => {
2682 Some(CallCommand::SendReaction(reaction)) => {
2286 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2683 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2287 timeline.record("reaction failed", error.to_string());
2684 timeline.record("reaction failed", error.to_string());
2288 control.send(CallUpdate::Notice("Could not send the reaction".into()));
2685 control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into()));
2289 }
2686 }
2290 }
2687 }
2291 Some(CallCommand::EndMeeting) => {
2688 Some(CallCommand::EndMeeting) => {
@@ -2336,12 +2733,13 @@ async fn drive(
2336 recording_flow.failed();
2733 recording_flow.failed();
2337 timeline.record("recording", "did not start in time");
2734 timeline.record("recording", "did not start in time");
2338 control.send(CallUpdate::RecordingPending(false));
2735 control.send(CallUpdate::RecordingPending(false));
2339 control.send(CallUpdate::Notice("The recording did not start".into()));
2736 control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into()));
2340 }
2737 }
2341 if layout == Layout::Conference
2738 if layout == Layout::Conference
2342 && let Some(size) = local_video.camera_size()
2739 && let Some(size) = local_video.camera_size()
2343 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2740 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2344 && let Some(body) = send_capabilities.body_for(size)
2741 && let Some(body) =
2742 send_capabilities.body_for(size, local_video.video_quality())
2345 {
2743 {
2346 let signaling = signaling.clone();
2744 let signaling = signaling.clone();
2347 let timeline = timeline.clone();
2745 let timeline = timeline.clone();
@@ -2437,12 +2835,13 @@ async fn drive(
2437 timeline.record(
2835 timeline.record(
2438 "stats",
2836 "stats",
2439 format!(
2837 format!(
2440 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}",
2838 "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}{}",
2441 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2839 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2442 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2840 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2443 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2841 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2444 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2842 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2445 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2843 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2844 local_video.camera_capture_summary().unwrap_or_default()
2446 ),
2845 ),
2447 );
2846 );
2448 }
2847 }
@@ -2487,6 +2886,7 @@ async fn drive(
2487 control.send(CallUpdate::Camera(false));
2886 control.send(CallUpdate::Camera(false));
2488 }
2887 }
2489 share_pending = None;
2888 share_pending = None;
2889 portal_pending = None;
2490 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2890 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2491 timeline.record("escalation failed", "no answer for the new peer connection in time");
2891 timeline.record("escalation failed", "no answer for the new peer connection in time");
2492 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2892 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
@@ -2517,6 +2917,7 @@ async fn drive(
2517 timeline.record_sdp("local offer", &signaled.sdp);
2917 timeline.record_sdp("local offer", &signaled.sdp);
2518 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2918 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2519 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2919 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2920 same_peer_grace_until = None;
2520 }
2921 }
2521 Err(error) => {
2922 Err(error) => {
2522 timeline.record("offer after glare failed", error.to_string());
2923 timeline.record("offer after glare failed", error.to_string());
@@ -2527,6 +2928,16 @@ async fn drive(
2527 }
2928 }
2528 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2929 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2529 same_peer_deadline = None;
2930 same_peer_deadline = None;
2931 if same_peer.is_some() {
2932 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2933 timeline.record(
2934 "same-peer offer",
2935 "no answer yet, waiting a little longer",
2936 );
2937 }
2938 }
2939 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2940 same_peer_grace_until = None;
2530 if let Some(pending) = same_peer.take() {
2941 if let Some(pending) = same_peer.take() {
2531 timeline.record("same-peer offer", "no answer in time");
2942 timeline.record("same-peer offer", "no answer in time");
2532 negotiator.same_peer_offer_failed();
2943 negotiator.same_peer_offer_failed();
@@ -2554,6 +2965,10 @@ async fn drive(
2554 }
2965 }
2555 }
2966 }
2556 }
2967 }
2968 if software_audio.is_some() {
2969 timeline.record("software audio", "stopping before tear down");
2970 drop(software_audio);
2971 }
2557 live.callbacks = Some(callbacks);
2972 live.callbacks = Some(callbacks);
2558 Ok(())
2973 Ok(())
2559}
2974}
@@ -2574,9 +2989,20 @@ async fn start_escalation(
2574 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2989 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2575 let session = open_peer(factory, grant, &options.relay_host, false)?;
2990 let session = open_peer(factory, grant, &options.relay_host, false)?;
2576 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2991 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2577 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2992 let body = renegotiation_body(
2993 &remote.participant,
2994 links,
2995 &media.signaled.sdp,
2996 media_leg_id,
2997 &media.modalities,
2998 true,
2999 false,
3000 );
2578 let reply_tags = offer_reply_tags(&body);
3001 let reply_tags = offer_reply_tags(&body);
2579 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
3002 remote
3003 .signaling
3004 .post_json("POST mediaRenegotiation", url, body)
3005 .await?;
2580 Ok(NextPeer {
3006 Ok(NextPeer {
2581 session,
3007 session,
2582 offered: Some(media),
3008 offered: Some(media),
@@ -2637,7 +3063,16 @@ async fn answer_on_new_peer(
2637 teams_offer: &str,
3063 teams_offer: &str,
2638) -> Result<(PeerSession, AnsweredMedia)> {
3064) -> Result<(PeerSession, AnsweredMedia)> {
2639 let session = open_peer(factory, grant, &options.relay_host, false)?;
3065 let session = open_peer(factory, grant, &options.relay_host, false)?;
2640 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
3066 let answered = answer_offer(
3067 &session.peer,
3068 Some(track),
3069 teams_offer,
3070 AnswerVideo::Reject,
3071 None,
3072 false,
3073 None,
3074 )
3075 .await?;
2641 Ok((session, answered))
3076 Ok((session, answered))
2642}
3077}
2643
3078
@@ -2651,8 +3086,16 @@ async fn send_media_answer(
2651 let url = reply_links
3086 let url = reply_links
2652 .get("mediaAnswer")
3087 .get("mediaAnswer")
2653 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
3088 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
2654 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
3089 let body = escalation_answer_body(
2655 remote.signaling.post_json("POST mediaAnswer", url, body).await
3090 &remote.participant,
3091 links,
3092 &answered.answer_sdp,
3093 media_leg_id,
3094 );
3095 remote
3096 .signaling
3097 .post_json("POST mediaAnswer", url, body)
3098 .await
2656}
3099}
2657
3100
2658#[allow(clippy::too_many_arguments)]
3101#[allow(clippy::too_many_arguments)]
@@ -2675,7 +3118,9 @@ fn negotiate_video(
2675 }
3118 }
2676 };
3119 };
2677 let table = SlotTable::from_streams(&streams);
3120 let table = SlotTable::from_streams(&streams);
2678 let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming"));
3121 let link = links
3122 .get("applyChannelParameters")
3123 .or_else(|| links.get("controlVideoStreaming"));
2679 timeline.record(
3124 timeline.record(
2680 "video slots",
3125 "video slots",
2681 format!(
3126 format!(
@@ -2685,33 +3130,48 @@ fn negotiate_video(
2685 link.is_some()
3130 link.is_some()
2686 ),
3131 ),
2687 );
3132 );
2688 let requester = link
3133 let requester = link.filter(|_| from_mixer).map(|url| {
2689 .filter(|_| from_mixer)
3134 SourceRequester::start(
2690 .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone()));
3135 signaling.clone(),
3136 url.clone(),
3137 video.router().clone(),
3138 control.video.clone(),
3139 timeline.clone(),
3140 )
3141 });
2691 video.negotiated(table, requester);
3142 video.negotiated(table, requester);
2692 send_receive_change(control, video.reselect(roster));
3143 send_receive_change(control, video.reselect(roster));
2693}
3144}
2694
3145
2695const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
2696const ON_HOLD_NOTICE: &str = "Resume the call first";
2697const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
2698const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
2699const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
2700const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
2701
2702async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3146async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2703 match mode {
3147 match mode {
2704 VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }],
3148 VideoMode::Pattern => vec![CameraDevice {
3149 key: "pattern".into(),
3150 name: "Test pattern".into(),
3151 }],
2705 VideoMode::Off => Vec::new(),
3152 VideoMode::Off => Vec::new(),
2706 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(),
3153 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3154 .await
3155 .unwrap_or_default(),
2707 }
3156 }
2708}
3157}
2709
3158
2710fn refresh_cameras(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, timeline: Timeline) {
3159fn refresh_cameras(
3160 updates: mpsc::UnboundedSender<CallUpdate>,
3161 mode: VideoMode,
3162 timeline: Timeline,
3163) {
2711 tokio::spawn(async move {
3164 tokio::spawn(async move {
2712 let started = Instant::now();
3165 let started = Instant::now();
2713 let cameras = camera_devices(mode).await;
3166 let cameras = camera_devices(mode).await;
2714 timeline.record("camera list", format!("{} camera(s) in {} ms", cameras.len(), started.elapsed().as_millis()));
3167 timeline.record(
3168 "camera list",
3169 format!(
3170 "{} camera(s) in {} ms",
3171 cameras.len(),
3172 started.elapsed().as_millis()
3173 ),
3174 );
2715 let _ = updates.send(CallUpdate::Cameras(cameras));
3175 let _ = updates.send(CallUpdate::Cameras(cameras));
2716 });
3176 });
2717}
3177}
@@ -2720,37 +3180,85 @@ const SHARE_THUMBNAIL_WINDOWS: usize = 12;
2720const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3180const SHARE_THUMBNAIL_WIDTH: u32 = 320;
2721const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3181const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
2722
3182
2723fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, with_thumbnails: bool) {
3183fn announce_share(control: &CallControl, source: &ShareSource) {
3184 control.send(CallUpdate::ShareKind(Some(source.kind)));
3185 control.send(CallUpdate::LocalShare(Some(source.label())));
3186}
3187
3188fn clear_share(control: &CallControl) {
3189 control.send(CallUpdate::ShareKind(None));
3190 control.send(CallUpdate::LocalShare(None));
3191}
3192
3193fn refresh_share_sources(
3194 updates: mpsc::UnboundedSender<CallUpdate>,
3195 mode: VideoMode,
3196 with_thumbnails: bool,
3197) {
2724 tokio::spawn(async move {
3198 tokio::spawn(async move {
3199 let picker = current_share_picker();
2725 let sources = match mode {
3200 let sources = match mode {
2726 VideoMode::Pattern => vec![
3201 VideoMode::Pattern => vec![
2727 ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() },
3202 ShareSource {
2728 ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() },
3203 id: 1,
3204 kind: ShareKind::Screen,
3205 title: "Test screen".into(),
3206 },
3207 ShareSource {
3208 id: 2,
3209 kind: ShareKind::Window,
3210 title: "Test window".into(),
3211 },
2729 ],
3212 ],
2730 VideoMode::Off => Vec::new(),
3213 VideoMode::Off => Vec::new(),
2731 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(),
3214 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3215 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3216 .await
3217 .unwrap_or_default(),
2732 };
3218 };
3219 let sources = share_sources_for_menu(picker, sources);
2733 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3220 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
2734 if !with_thumbnails {
3221 if picker == SharePicker::Portal || !with_thumbnails {
2735 return;
3222 return;
2736 }
3223 }
2737 let wanted: Vec<ShareSource> = sources
3224 let wanted: Vec<ShareSource> = sources
2738 .iter()
3225 .iter()
2739 .filter(|source| source.kind == ShareKind::Screen)
3226 .filter(|source| source.kind == ShareKind::Screen)
2740 .chain(sources.iter().filter(|source| source.kind == ShareKind::Window).take(SHARE_THUMBNAIL_WINDOWS))
3227 .chain(
3228 sources
3229 .iter()
3230 .filter(|source| source.kind == ShareKind::Window)
3231 .take(SHARE_THUMBNAIL_WINDOWS),
3232 )
2741 .cloned()
3233 .cloned()
2742 .collect();
3234 .collect();
2743 for source in wanted {
3235 for source in wanted {
2744 let picture = match mode {
3236 let picture = match mode {
2745 VideoMode::Platform => {
3237 VideoMode::Platform => {
2746 let wanted = source.clone();
3238 let wanted = source.clone();
2747 tokio::task::spawn_blocking(move || share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)).await.ok().flatten()
3239 tokio::task::spawn_blocking(move || {
3240 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3241 })
3242 .await
3243 .ok()
3244 .flatten()
2748 }
3245 }
2749 VideoMode::Pattern => Some(VideoPicture::solid(SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT, 120, 80, 40)),
3246 VideoMode::Pattern => Some(VideoPicture::solid(
3247 SHARE_THUMBNAIL_WIDTH,
3248 SHARE_THUMBNAIL_HEIGHT,
3249 120,
3250 80,
3251 40,
3252 )),
2750 VideoMode::Off => None,
3253 VideoMode::Off => None,
2751 };
3254 };
2752 if let Some(picture) = picture
3255 if let Some(picture) = picture
2753 && updates.send(CallUpdate::ShareThumbnail { source, picture: Arc::new(picture) }).is_err()
3256 && updates
3257 .send(CallUpdate::ShareThumbnail {
3258 source,
3259 picture: Arc::new(picture),
3260 })
3261 .is_err()
2754 {
3262 {
2755 return;
3263 return;
2756 }
3264 }
@@ -2774,8 +3282,14 @@ fn tell_media_descriptions(
2774 let signaling = remote.signaling.clone();
3282 let signaling = remote.signaling.clone();
2775 let timeline = timeline.clone();
3283 let timeline = timeline.clone();
2776 tokio::spawn(async move {
3284 tokio::spawn(async move {
2777 let sent = format!("{} {} request {request_id}", description.mid, description.direction);
3285 let sent = format!(
2778 if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await {
3286 "{} {} request {request_id}",
3287 description.mid, description.direction
3288 );
3289 if let Err(error) = signaling
3290 .update_media_descriptions(&url, &[description], request_id)
3291 .await
3292 {
2779 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
3293 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
2780 }
3294 }
2781 });
3295 });
@@ -2785,30 +3299,54 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2785 own.is_some_and(|own| own.thread_id == target.thread_id)
3299 own.is_some_and(|own| own.thread_id == target.thread_id)
2786}
3300}
2787
3301
2788fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
3302fn attach_share_line(
3303 peer: &PeerConnection,
3304 factory: &PeerConnectionFactory,
3305 local_video: &mut LocalVideo,
3306 camera_mid: Option<&str>,
3307) -> Result<()> {
2789 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
3308 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2790 if !local_video.has_lines() && camera.is_none() {
3309 if !local_video.has_lines() && camera.is_none() {
2791 return Err(Error::Webrtc("no video line negotiated".into()));
3310 return Err(Error::Webrtc("no video line negotiated".into()));
2792 }
3311 }
2793 let share = add_share_line(peer, factory)?;
3312 let share = add_share_line(peer, factory)?;
2794 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
3313 local_video
2795 let _ = share.stop();
3314 .add_share_line(share.clone(), camera)
2796 })
3315 .inspect_err(|_| {
3316 let _ = share.stop();
3317 })
2797}
3318}
2798
3319
2799fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
3320fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2800 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
3321 peer.transceivers()
3322 .into_iter()
3323 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2801}
3324}
2802
3325
2803fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {
3326fn start_camera_line(
3327 local_video: &mut LocalVideo,
3328 peer: &PeerConnection,
3329 direct_mid: Option<&str>,
3330 choice: &DeviceChoice,
3331) -> Result<()> {
2804 if !local_video.has_lines() {
3332 if !local_video.has_lines() {
2805 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
3333 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
2806 let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
3334 let camera = peer_transceiver(peer, mid)
2807 if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {
3335 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
2808 peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])
3336 if !matches!(
2809 .map_err(|error| Error::Webrtc(error.to_string()))?;
3337 camera.direction(),
3338 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
3339 ) {
3340 peer.add_track(
3341 MediaStreamTrack::Video(local_video.camera_track()),
3342 &[CAMERA_STREAM],
3343 )
3344 .map_err(|error| Error::Webrtc(error.to_string()))?;
2810 }
3345 }
2811 local_video.set_lines(VideoLines { camera, share: None })?;
3346 local_video.set_lines(VideoLines {
3347 camera,
3348 share: None,
3349 })?;
2812 }
3350 }
2813 local_video.start_camera(choice)
3351 local_video.start_camera(choice)
2814}
3352}
@@ -2836,9 +3374,22 @@ async fn offer_same_peer(
2836 .cloned()
3374 .cloned()
2837 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
3375 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
2838 if !negotiator.begin_same_peer_offer() {
3376 if !negotiator.begin_same_peer_offer() {
2839 return Err(Error::Signaling("another media negotiation is running".into()));
3377 return Err(Error::Signaling(
3378 "another media negotiation is running".into(),
3379 ));
2840 }
3380 }
2841 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
3381 let offered = build_same_peer_offer(
3382 peer,
3383 plan,
3384 layout,
3385 hold,
3386 camera,
3387 share,
3388 camera_mid,
3389 own_share_mid,
3390 direct.then_some(gathered),
3391 )
3392 .await;
2842 let (text, signaled) = match offered {
3393 let (text, signaled) = match offered {
2843 Ok(offered) => offered,
3394 Ok(offered) => offered,
2844 Err(error) => {
3395 Err(error) => {
@@ -2846,10 +3397,25 @@ async fn offer_same_peer(
2846 return Err(error);
3397 return Err(error);
2847 }
3398 }
2848 };
3399 };
2849 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
3400 let modalities = offer_modalities(
2850 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
3401 layout == Layout::OneToOne && camera && !hold,
3402 share && !hold,
3403 );
3404 let body = renegotiation_body(
3405 &remote.participant,
3406 links,
3407 &signaled.sdp,
3408 media_leg_id,
3409 &modalities,
3410 false,
3411 direct,
3412 );
2851 let reply_tags = offer_reply_tags(&body);
3413 let reply_tags = offer_reply_tags(&body);
2852 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
3414 if let Err(error) = remote
3415 .signaling
3416 .post_json("POST mediaRenegotiation (same peer)", &url, body)
3417 .await
3418 {
2853 negotiator.same_peer_offer_failed();
3419 negotiator.same_peer_offer_failed();
2854 rollback_offer(peer).await;
3420 rollback_offer(peer).await;
2855 return Err(error);
3421 return Err(error);
@@ -2858,9 +3424,23 @@ async fn offer_same_peer(
2858}
3424}
2859
3425
2860#[allow(clippy::too_many_arguments)]
3426#[allow(clippy::too_many_arguments)]
2861async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
3427async fn build_same_peer_offer(
3428 peer: &PeerConnection,
3429 plan: &OfferPlan,
3430 layout: Layout,
3431 hold: bool,
3432 camera: bool,
3433 share: bool,
3434 camera_mid: &str,
3435 own_share_mid: Option<String>,
3436 gathered: Option<&Gathered>,
3437) -> Result<(String, SignaledOffer)> {
2862 let offer = peer
3438 let offer = peer
2863 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
3439 .create_offer(OfferOptions {
3440 offer_to_receive_audio: true,
3441 offer_to_receive_video: true,
3442 ..OfferOptions::default()
3443 })
2864 .await
3444 .await
2865 .map_err(|error| Error::Webrtc(error.to_string()))?;
3445 .map_err(|error| Error::Webrtc(error.to_string()))?;
2866 let offer_text = offer.to_string();
3446 let offer_text = offer.to_string();
@@ -2870,25 +3450,56 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2870 .and_then(|remote| direction_of(&remote.to_string(), mid))
3450 .and_then(|remote| direction_of(&remote.to_string(), mid))
2871 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
3451 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2872 });
3452 });
2873 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
3453 let text = directions_for(
3454 layout,
3455 false,
3456 camera,
3457 share,
3458 camera_mid,
3459 share_mid.as_deref(),
3460 remote_shares,
3461 &offer_text,
3462 );
2874 let description = parse_sdp(&text, SdpType::Offer)?;
3463 let description = parse_sdp(&text, SdpType::Offer)?;
2875 peer.set_local_description(description)
3464 peer.set_local_description(description)
2876 .await
3465 .await
2877 .map_err(|error| Error::Webrtc(error.to_string()))?;
3466 .map_err(|error| Error::Webrtc(error.to_string()))?;
2878 let mut numbers = random_u32;
3467 let mut numbers = random_u32;
2879 let mut plan = plan.clone();
3468 let mut plan = plan.clone();
2880 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
3469 if let Some(mid) = share_mid
3470 .as_ref()
3471 .filter(|mid| !plan.screen_share_mids.contains(mid))
3472 {
2881 plan.screen_share_mids.push(mid.clone());
3473 plan.screen_share_mids.push(mid.clone());
2882 }
3474 }
2883 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
3475 let mut signaled = to_teams_offer(
3476 &directions_for(
3477 layout,
3478 hold,
3479 camera,
3480 share,
3481 camera_mid,
3482 share_mid.as_deref(),
3483 remote_shares,
3484 &text,
3485 ),
3486 &plan,
3487 &mut numbers,
3488 )?;
2884 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
3489 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2885 if gathered.is_some()
3490 if gathered.is_some()
2886 && let Some(role) = negotiated_setup(
3491 && let Some(role) = negotiated_setup(
2887 peer.current_local_description().map(|local| local.to_string()).as_deref(),
3492 peer.current_local_description()
2888 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
3493 .map(|local| local.to_string())
3494 .as_deref(),
3495 peer.current_remote_description()
3496 .map(|remote| remote.to_string())
3497 .as_deref(),
2889 )
3498 )
2890 {
3499 {
2891 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
3500 signaled.sdp = signaled
3501 .sdp
3502 .replace("a=setup:actpass", &format!("a=setup:{role}"));
2892 }
3503 }
2893 Ok((text, signaled))
3504 Ok((text, signaled))
2894}
3505}
@@ -2897,8 +3508,13 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2897fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
3508fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
2898 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
3509 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
2899 Ok(Ok(description)) => Ok(description),
3510 Ok(Ok(description)) => Ok(description),
2900 Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),
3511 Ok(Err(error)) => Err(Error::Sdp(format!(
2901 Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),
3512 "{kind:?} rejected: {}",
3513 error.description
3514 ))),
3515 Err(_) => Err(Error::Sdp(format!(
3516 "{kind:?} rejected, libwebrtc gave no readable reason"
3517 ))),
2902 }
3518 }
2903}
3519}
2904
3520
@@ -2920,7 +3536,10 @@ fn is_glare_rejection(body: &serde_json::Value) -> bool {
2920
3536
2921fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
3537fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2922 let links = &body["mediaNegotiation"]["links"];
3538 let links = &body["mediaNegotiation"]["links"];
2923 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
3539 ["mediaAnswer", "rejection"]
3540 .iter()
3541 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
3542 .collect()
2924}
3543}
2925
3544
2926#[cfg(test)]
3545#[cfg(test)]
@@ -2930,9 +3549,15 @@ mod reply_tag_tests {
2930 #[test]
3549 #[test]
2931 fn answers_and_rejections_match_the_offer_by_tag() {
3550 fn answers_and_rejections_match_the_offer_by_tag() {
2932 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
3551 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2933 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
3552 assert!(answers_offer(
3553 "callAgent/c/aaaa1111/call/mediaAnswer/",
3554 &tags
3555 ));
2934 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
3556 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2935 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
3557 assert!(!answers_offer(
3558 "callAgent/c/cccc3333/call/mediaAnswer/",
3559 &tags
3560 ));
2936 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
3561 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2937 }
3562 }
2938
3563
@@ -2941,11 +3566,19 @@ mod reply_tag_tests {
2941 let body = serde_json::json!({"mediaNegotiation": {"links": {
3566 let body = serde_json::json!({"mediaNegotiation": {"links": {
2942 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
3567 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2943 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
3568 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2944 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
3569 assert_eq!(
3570 offer_reply_tags(&body),
3571 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
3572 );
2945 }
3573 }
2946}
3574}
2947
3575
2948fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3576fn defer_to_new_peer(
3577 change: Change,
3578 deferred: &mut Vec<Change>,
3579 local_video: &mut LocalVideo,
3580 control: &CallControl,
3581) {
2949 match change {
3582 match change {
2950 Change::Camera(true) => {
3583 Change::Camera(true) => {
2951 control.send(CallUpdate::Camera(true));
3584 control.send(CallUpdate::Camera(true));
@@ -2957,7 +3590,14 @@ fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &m
2957}
3590}
2958
3591
2959/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
3592/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2960fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
3593fn settle_failed_escalation(
3594 server: bool,
3595 layout: Layout,
3596 negotiator: &mut MediaNegotiator,
3597 deferred: &mut Vec<Change>,
3598 local_video: &mut LocalVideo,
3599 control: &CallControl,
3600) {
2961 if server {
3601 if server {
2962 negotiator.server_escalation_failed();
3602 negotiator.server_escalation_failed();
2963 for change in deferred.drain(..) {
3603 for change in deferred.drain(..) {
@@ -2971,7 +3611,7 @@ fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut Media
2971fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
3611fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2972 if local_video.sharing() {
3612 if local_video.sharing() {
2973 local_video.stop_share();
3613 local_video.stop_share();
2974 control.send(CallUpdate::LocalShare(None));
3614 clear_share(control);
2975 }
3615 }
2976 if local_video.camera_on() {
3616 if local_video.camera_on() {
2977 local_video.stop_camera();
3617 local_video.stop_camera();
@@ -2988,11 +3628,11 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
2988 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
3628 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2989 Change::Share(true) => {
3629 Change::Share(true) => {
2990 local_video.stop_share();
3630 local_video.stop_share();
2991 control.send(CallUpdate::LocalShare(None));
3631 clear_share(control);
2992 control.send(CallUpdate::Notice("Sharing could not start".into()));
3632 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, "")));
2993 }
3633 }
2994 Change::Share(false) => {}
3634 Change::Share(false) => {}
2995 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
3635 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
2996 }
3636 }
2997}
3637}
2998
3638
@@ -3004,37 +3644,63 @@ fn withhold_media(
3004 local_video: &mut LocalVideo,
3644 local_video: &mut LocalVideo,
3005 control: &CallControl,
3645 control: &CallControl,
3006) {
3646) {
3007 *muted = apply_mute(MuteCommand::Mute, *muted, audio, software_audio, remote, control);
3647 *muted = apply_mute(
3648 MuteCommand::Mute,
3649 *muted,
3650 audio,
3651 software_audio,
3652 remote,
3653 control,
3654 );
3008 if local_video.camera_on() {
3655 if local_video.camera_on() {
3009 local_video.stop_camera();
3656 local_video.stop_camera();
3010 control.send(CallUpdate::Camera(false));
3657 control.send(CallUpdate::Camera(false));
3011 }
3658 }
3012}
3659}
3013
3660
3014async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {
3661async fn apply_background(
3662 choice: BackgroundChoice,
3663 local_video: &LocalVideo,
3664 control: &CallControl,
3665 timeline: &Timeline,
3666) {
3015 match choice {
3667 match choice {
3016 BackgroundChoice::None => local_video.set_background(false, None),
3668 BackgroundChoice::None => local_video.set_background(false, None),
3017 BackgroundChoice::Blur => local_video.set_background(true, None),
3669 BackgroundChoice::Blur => local_video.set_background(true, None),
3018 BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3670 BackgroundChoice::Image(path) => {
3019 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3671 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3020 Ok(Err(error)) => {
3672 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3021 timeline.record("background image failed", error.to_string());
3673 Ok(Err(error)) => {
3022 control.send(CallUpdate::Notice("That background image could not be used".into()));
3674 timeline.record("background image failed", error.to_string());
3675 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
3676 }
3677 Err(_) => {}
3023 }
3678 }
3024 Err(_) => {}
3679 }
3025 },
3026 }
3680 }
3027}
3681}
3028
3682
3029async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
3683async fn save_meeting_options(
3684 session: &session::Session,
3685 target: &MeetingTarget,
3686 writes: &[OptionWrite],
3687) -> std::result::Result<meeting_options::MeetingOptions, String> {
3030 for change in writes {
3688 for change in writes {
3031 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
3689 meeting_options::write(session, target, change)
3690 .await
3691 .map_err(|error| error.to_string())?;
3032 }
3692 }
3033 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
3693 meeting_options::fetch(session, target)
3694 .await
3695 .map_err(|error| error.to_string())
3034}
3696}
3035
3697
3036fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3698fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3037 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
3699 let display_name = roster
3700 .members()
3701 .iter()
3702 .find(|member| member.mri == mri)
3703 .map_or("", |member| member.display_name.as_str());
3038 Target { mri, display_name }
3704 Target { mri, display_name }
3039}
3705}
3040
3706
@@ -3046,17 +3712,29 @@ fn recorder_busy(error: &Error) -> bool {
3046 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3712 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3047}
3713}
3048
3714
3049fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {
3715fn report_organizer_result(
3716 result: Result<u16>,
3717 label: &str,
3718 notice: &'static str,
3719 control: &CallControl,
3720 timeline: &Timeline,
3721) {
3050 if let Err(error) = &result {
3722 if let Err(error) = &result {
3051 timeline.record(format!("{label} failed"), error.to_string());
3723 timeline.record(format!("{label} failed"), error.to_string());
3052 control.send(CallUpdate::Notice(notice.into()));
3724 control.send(CallUpdate::Notice(notice.to_owned()));
3053 }
3725 }
3054 control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });
3726 control.send(CallUpdate::Organizer {
3727 action: label.to_owned(),
3728 outcome: result.map_err(|error| error.to_string()),
3729 });
3055}
3730}
3056
3731
3057fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3732fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3058 if entry.display_name.is_empty() {
3733 if entry.display_name.is_empty() {
3059 entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();
3734 entry.display_name = roster
3735 .name_of(&entry.user_id)
3736 .unwrap_or_default()
3737 .to_owned();
3060 }
3738 }
3061 entry
3739 entry
3062}
3740}
@@ -3095,8 +3773,14 @@ async fn run_bot_steps(
3095 }
3773 }
3096 };
3774 };
3097 let (join_failure, start_failure) = match job {
3775 let (join_failure, start_failure) = match job {
3098 BotJob::Captions => ("The captions service could not join", "Captions could not start"),
3776 BotJob::Captions => (
3099 BotJob::Recording => ("The recording service could not join", "The recording could not start"),
3777 CAPTIONS_JOIN_FAILED_NOTICE,
3778 CAPTIONS_START_FAILED_NOTICE,
3779 ),
3780 BotJob::Recording => (
3781 RECORDING_JOIN_FAILED_NOTICE,
3782 RECORDING_START_FAILED_NOTICE,
3783 ),
3100 };
3784 };
3101 loop {
3785 loop {
3102 match flow.next_for(roster.caption_bot(), is_active) {
3786 match flow.next_for(roster.caption_bot(), is_active) {
@@ -3106,12 +3790,33 @@ async fn run_bot_steps(
3106 continue;
3790 continue;
3107 }
3791 }
3108 let Some(thread) = meeting_chat else {
3792 let Some(thread) = meeting_chat else {
3109 return fail(flow, "This call has no chat for the captions and the recording");
3793 return fail(
3794 flow,
3795 "This call has no chat for the captions and the recording",
3796 );
3110 };
3797 };
3111 *bot_pending = true;
3798 *bot_pending = true;
3112 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
3799 let added = remote
3800 .signaling
3801 .add_caption_bot(
3802 &remote.conversation,
3803 &remote.participant,
3804 thread,
3805 links,
3806 remote.threadless,
3807 )
3808 .await;
3113 if job == BotJob::Recording {
3809 if job == BotJob::Recording {
3114 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
3810 report_organizer_result(
3811 added
3812 .as_ref()
3813 .map(|status| *status)
3814 .map_err(|error| Error::Signaling(error.to_string())),
3815 "recording add bot",
3816 join_failure,
3817 control,
3818 timeline,
3819 );
3115 }
3820 }
3116 if let Err(error) = added {
3821 if let Err(error) = added {
3117 timeline.record("bot invitation failed", error.to_string());
3822 timeline.record("bot invitation failed", error.to_string());
@@ -3120,21 +3825,40 @@ async fn run_bot_steps(
3120 }
3825 }
3121 }
3826 }
3122 CaptionStep::Start => {
3827 CaptionStep::Start => {
3123 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
3828 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3829 return;
3830 };
3124 match job {
3831 match job {
3125 BotJob::Captions => {
3832 BotJob::Captions => {
3126 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
3833 if let Err(error) = remote
3834 .signaling
3835 .caption_command(&url, BotAction::Start, &remote.participant)
3836 .await
3837 {
3127 timeline.record("caption start failed", error.to_string());
3838 timeline.record("caption start failed", error.to_string());
3128 return fail(flow, start_failure);
3839 return fail(flow, start_failure);
3129 }
3840 }
3130 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
3841 if let Err(error) = remote
3842 .signaling
3843 .set_caption_preference(&remote.conversation, &remote.participant, true)
3844 .await
3845 {
3131 timeline.record("caption preference failed", error.to_string());
3846 timeline.record("caption preference failed", error.to_string());
3132 }
3847 }
3133 }
3848 }
3134 BotJob::Recording => {
3849 BotJob::Recording => {
3135 let started = remote.signaling.recording_command(&url, plan.start(), &remote.participant, &plan.title).await;
3850 let started = remote
3851 .signaling
3852 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
3853 .await;
3136 let failed = started.is_err();
3854 let failed = started.is_err();
3137 report_organizer_result(started, "recording start", start_failure, control, timeline);
3855 report_organizer_result(
3856 started,
3857 "recording start",
3858 start_failure,
3859 control,
3860 timeline,
3861 );
3138 if failed {
3862 if failed {
3139 return fail(flow, start_failure);
3863 return fail(flow, start_failure);
3140 }
3864 }
@@ -3142,13 +3866,27 @@ async fn run_bot_steps(
3142 }
3866 }
3143 }
3867 }
3144 CaptionStep::Stop => {
3868 CaptionStep::Stop => {
3145 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };
3869 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3870 continue;
3871 };
3146 match job {
3872 match job {
3147 BotJob::Captions => {
3873 BotJob::Captions => {
3148 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {
3874 if let Err(error) = remote
3875 .signaling
3876 .caption_command(&url, BotAction::Stop, &remote.participant)
3877 .await
3878 {
3149 timeline.record("caption stop failed", error.to_string());
3879 timeline.record("caption stop failed", error.to_string());
3150 }
3880 }
3151 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
3881 if let Err(error) = remote
3882 .signaling
3883 .set_caption_preference(
3884 &remote.conversation,
3885 &remote.participant,
3886 false,
3887 )
3888 .await
3889 {
3152 timeline.record("caption preference failed", error.to_string());
3890 timeline.record("caption preference failed", error.to_string());
3153 }
3891 }
3154 }
3892 }
@@ -3157,18 +3895,29 @@ async fn run_bot_steps(
3157 let updates = control.updates();
3895 let updates = control.updates();
3158 let (command, title) = (plan.stop(), plan.title.clone());
3896 let (command, title) = (plan.stop(), plan.title.clone());
3159 tokio::spawn(async move {
3897 tokio::spawn(async move {
3160 let mut stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3898 let mut stopped = remote
3899 .signaling
3900 .recording_command(&url, command, &remote.participant, &title)
3901 .await;
3161 for _ in 0..RECORDING_STOP_RETRIES {
3902 for _ in 0..RECORDING_STOP_RETRIES {
3162 if !stopped.as_ref().is_err_and(recorder_busy) {
3903 if !stopped.as_ref().is_err_and(recorder_busy) {
3163 break;
3904 break;
3164 }
3905 }
3165 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3906 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3166 stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3907 stopped = remote
3908 .signaling
3909 .recording_command(&url, command, &remote.participant, &title)
3910 .await;
3167 }
3911 }
3168 if stopped.is_err() {
3912 if stopped.is_err() {
3169 let _ = updates.send(CallUpdate::Notice("The recording could not be stopped".into()));
3913 let _ = updates.send(CallUpdate::Notice(
3914 RECORDING_STOP_FAILED_NOTICE.into(),
3915 ));
3170 }
3916 }
3171 let _ = updates.send(CallUpdate::Organizer { action: "recording stop".into(), outcome: stopped.map_err(|error| error.to_string()) });
3917 let _ = updates.send(CallUpdate::Organizer {
3918 action: "recording stop".into(),
3919 outcome: stopped.map_err(|error| error.to_string()),
3920 });
3172 });
3921 });
3173 }
3922 }
3174 }
3923 }
@@ -3188,7 +3937,12 @@ fn send_receive_change(control: &CallControl, change: ReceiveChange) {
3188 }
3937 }
3189}
3938}
3190
3939
3191fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
3940fn record_audio_devices(
3941 timeline: &Timeline,
3942 lists: &devices::DeviceLists,
3943 input: Option<&AppliedDevice>,
3944 output: Option<&AppliedDevice>,
3945) {
3192 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3946 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3193 applied
3947 applied
3194 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
3948 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
@@ -3197,7 +3951,11 @@ fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input
3197 };
3951 };
3198 timeline.record(
3952 timeline.record(
3199 "audio devices",
3953 "audio devices",
3200 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
3954 format!(
3955 "input={} output={}",
3956 name(&lists.inputs, input),
3957 name(&lists.outputs, output)
3958 ),
3201 );
3959 );
3202}
3960}
3203
3961
@@ -3211,19 +3969,31 @@ fn follow_device_change(
3211 control: &CallControl,
3969 control: &CallControl,
3212) -> bool {
3970) -> bool {
3213 let system_default = devices::system_default_id(flow);
3971 let system_default = devices::system_default_id(flow);
3214 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3972 let (index, fell_back) =
3215 Reselect::Keep => return false,
3973 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3216 Reselect::Select(index) => (index, false),
3974 Reselect::Keep => return false,
3217 Reselect::FallBack(index) => (index, true),
3975 Reselect::Select(index) => (index, false),
3218 };
3976 Reselect::FallBack(index) => (index, true),
3977 };
3219 let selected = select(index);
3978 let selected = select(index);
3220 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
3979 timeline.record(
3980 "device change",
3981 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
3982 );
3221 if selected {
3983 if selected {
3222 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
3984 *applied = current
3985 .iter()
3986 .find(|device| device.index == index)
3987 .map(|device| AppliedDevice {
3988 index,
3989 key: device.key(),
3990 });
3223 }
3991 }
3224 if fell_back {
3992 if fell_back {
3225 let fallback = current.iter().find(|device| device.index == index);
3993 let fallback = current.iter().find(|device| device.index == index);
3226 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
3994 control.send(CallUpdate::Notice(devices::disconnect_notice(
3995 previous, choice, fallback,
3996 )));
3227 }
3997 }
3228 selected
3998 selected
3229}
3999}
@@ -3250,16 +4020,27 @@ fn apply_mute(
3250 tokio::spawn(async move {
4020 tokio::spawn(async move {
3251 let _ = remote
4021 let _ = remote
3252 .signaling
4022 .signaling
3253 .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted)
4023 .update_endpoint_state(
4024 &remote.conversation,
4025 &remote.participant,
4026 effect.endpoint_is_muted,
4027 )
3254 .await;
4028 .await;
3255 });
4029 });
3256 effect.muted
4030 effect.muted
3257}
4031}
3258
4032
3259fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {
4033fn silence_for_hold(
4034 on_hold: bool,
4035 muted: bool,
4036 audio: Option<&AudioSetup>,
4037 software_audio: Option<&SoftwareAudio>,
4038) {
3260 let silent = on_hold || muted;
4039 let silent = on_hold || muted;
3261 if let Some(audio) = audio {
4040 if let Some(audio) = audio {
3262 audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);
4041 audio
4042 .track
4043 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
3263 }
4044 }
3264 if let Some(software_audio) = software_audio {
4045 if let Some(software_audio) = software_audio {
3265 software_audio.set_microphone_muted(silent);
4046 software_audio.set_microphone_muted(silent);
@@ -3277,7 +4058,10 @@ fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()>
3277 .map_err(|error| Error::Webrtc(error.to_string()))
4058 .map_err(|error| Error::Webrtc(error.to_string()))
3278}
4059}
3279
4060
3280fn outgoing_track<'a>(software_audio: Option<&'a SoftwareAudio>, device_track: &'a RtcAudioTrack) -> &'a RtcAudioTrack {
4061fn outgoing_track<'a>(
4062 software_audio: Option<&'a SoftwareAudio>,
4063 device_track: &'a RtcAudioTrack,
4064) -> &'a RtcAudioTrack {
3281 pick_track(software_audio.map(|audio| &audio.track), device_track)
4065 pick_track(software_audio.map(|audio| &audio.track), device_track)
3282}
4066}
3283
4067
@@ -3292,12 +4076,22 @@ fn software_wanted(
3292 audio: Option<&AudioSetup>,
4076 audio: Option<&AudioSetup>,
3293) -> Option<SoftwareAudioPlan> {
4077) -> Option<SoftwareAudioPlan> {
3294 let sharing_sound = share_sound_wanted && local_video.sharing();
4078 let sharing_sound = share_sound_wanted && local_video.sharing();
3295 SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))
4079 SoftwareAudioPlan::wanted(
4080 mic_settings,
4081 sharing_sound,
4082 audio.is_some_and(AudioSetup::uses_devices),
4083 )
3296}
4084}
3297
4085
3298fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
4086fn restore_device_track(
4087 factory: &PeerConnectionFactory,
4088 input: &DeviceChoice,
4089 peer: &PeerConnection,
4090 device_track: &RtcAudioTrack,
4091 timeline: &Timeline,
4092) {
3299 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4093 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3300 if cfg!(windows) && !factory.adm_recording_enabled() {
4094 if !factory.adm_recording_enabled() {
3301 factory.set_adm_recording_enabled(true);
4095 factory.set_adm_recording_enabled(true);
3302 devices::select_input(factory, input);
4096 devices::select_input(factory, input);
3303 }
4097 }
@@ -3325,6 +4119,9 @@ fn sync_software_audio(
3325 if running == wanted && !restart {
4119 if running == wanted && !restart {
3326 return;
4120 return;
3327 }
4121 }
4122 if running.is_some() {
4123 timeline.record("software audio", "stopping");
4124 }
3328 *software_audio = None;
4125 *software_audio = None;
3329 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
4126 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3330 let Some(plan) = wanted else {
4127 let Some(plan) = wanted else {
@@ -3332,15 +4129,26 @@ fn sync_software_audio(
3332 control.send(CallUpdate::ShareSound(false));
4129 control.send(CallUpdate::ShareSound(false));
3333 return;
4130 return;
3334 };
4131 };
3335 let started = SoftwareAudio::start(factory, options.audio, options.tone_hz, input, plan, muted, remote_audio)
4132 let started = SoftwareAudio::start(
3336 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4133 factory,
4134 options.audio,
4135 options.tone_hz,
4136 input,
4137 plan,
4138 muted,
4139 remote_audio,
4140 )
4141 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
3337 match started {
4142 match started {
3338 Ok(audio) => {
4143 Ok(audio) => {
3339 timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));
4144 timeline.record(
4145 "software audio",
4146 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4147 );
3340 if let Some(source) = &audio.microphone_source {
4148 if let Some(source) = &audio.microphone_source {
3341 timeline.record("mic capture", source.clone());
4149 timeline.record("mic capture", source.clone());
3342 }
4150 }
3343 if cfg!(windows) && audio.microphone_source.is_some() {
4151 if audio.microphone_source.is_some() {
3344 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4152 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3345 factory.set_adm_recording_enabled(false);
4153 factory.set_adm_recording_enabled(false);
3346 }
4154 }
@@ -3366,7 +4174,13 @@ fn sync_software_audio(
3366 }
4174 }
3367}
4175}
3368
4176
3369async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
4177async fn tear_down(
4178 mut live: Live,
4179 inner: &Inner,
4180 timeline: &Timeline,
4181 report: &mut CallReport,
4182 cancelled: bool,
4183) {
3370 for peer in &live.peers {
4184 for peer in &live.peers {
3371 peer.close();
4185 peer.close();
3372 }
4186 }
@@ -3377,8 +4191,16 @@ async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &
3377 if !live.skip_leave
4191 if !live.skip_leave
3378 && let Some(remote) = &live.remote
4192 && let Some(remote) = &live.remote
3379 {
4193 {
3380 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
4194 let reason = if cancelled {
3381 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
4195 LeaveReason::Cancel
4196 } else {
4197 LeaveReason::Hangup
4198 };
4199 match remote
4200 .signaling
4201 .leave(&remote.conversation, &remote.participant, reason)
4202 .await
4203 {
3382 Ok(()) => report.left_cleanly = true,
4204 Ok(()) => report.left_cleanly = true,
3383 Err(error) => timeline.record("leave failed", error.to_string()),
4205 Err(error) => timeline.record("leave failed", error.to_string()),
3384 }
4206 }
@@ -3422,31 +4244,53 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
3422 let body = decode_body(callback)?;
4244 let body = decode_body(callback)?;
3423 let (_, event) = classify(&callback.path, body)?;
4245 let (_, event) = classify(&callback.path, body)?;
3424 let detail = match &event {
4246 let detail = match &event {
3425 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
4247 CallEvent::Acceptance(acceptance) => format!(
3426 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
4248 "answer sdp {} bytes, fromMixer={}",
4249 acceptance.sdp.len(),
4250 acceptance.from_mixer
4251 ),
4252 CallEvent::End(end) => format!(
4253 "code={} subCode={} phrase={}",
4254 end.code, end.sub_code, end.phrase
4255 ),
3427 CallEvent::Progress(status) => format!("{status:?}"),
4256 CallEvent::Progress(status) => format!("{status:?}"),
3428 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4257 CallEvent::ConversationEnd(body)
3429 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
4258 | CallEvent::Rejection(body)
4259 | CallEvent::AddParticipantFailure(body)
4260 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4261 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4262 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
3430 _ => String::new(),
4263 _ => String::new(),
3431 };
4264 };
3432 timeline.record(format!("Trouter {}", event.name()), detail);
4265 timeline.record(format!("Trouter {}", event.name()), detail);
3433 match &event {
4266 match &event {
3434 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
4267 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
3435 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
4268 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
3436 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
4269 CallEvent::MediaRenegotiation(renegotiation) => {
4270 timeline.record_sdp("remote offer", &renegotiation.sdp)
4271 }
3437 _ => {}
4272 _ => {}
3438 }
4273 }
3439 Ok(event)
4274 Ok(event)
3440}
4275}
3441
4276
3442
4277async fn apply_answer(
3443async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4278 peer: &PeerConnection,
4279 teams_answer: &str,
4280 signaled: &SignaledOffer,
4281 browser_offer: &str,
4282) -> Result<()> {
3444 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
4283 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3445 set_browser_answer(peer, &answer).await
4284 set_browser_answer(peer, &answer).await
3446}
4285}
3447
4286
3448/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
4287/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
3449async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
4288async fn apply_hold_answer(
4289 peer: &PeerConnection,
4290 teams_answer: &str,
4291 signaled: &SignaledOffer,
4292 browser_offer: &str,
4293) -> Result<()> {
3450 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
4294 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3451 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
4295 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
3452}
4296}
@@ -3471,7 +4315,10 @@ fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
3471 return format!("{prefix}<masked>");
4315 return format!("{prefix}<masked>");
3472 }
4316 }
3473 }
4317 }
3474 line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ")
4318 line.split(' ')
4319 .map(mask_address)
4320 .collect::<Vec<_>>()
4321 .join(" ")
3475 })
4322 })
3476 .collect();
4323 .collect();
3477 let _ = std::fs::create_dir_all(directory);
4324 let _ = std::fs::create_dir_all(directory);
@@ -3482,8 +4329,16 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3482 let Some(directory) = &options.sdp_dump_dir else {
4329 let Some(directory) = &options.sdp_dump_dir else {
3483 return;
4330 return;
3484 };
4331 };
3485 let mut lines: Vec<String> =
4332 let mut lines: Vec<String> = timeline
3486 timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();
4333 .entries()
4334 .iter()
4335 .map(|entry| {
4336 format!(
4337 "{:>6} ms {} {}",
4338 entry.elapsed_ms, entry.label, entry.detail
4339 )
4340 })
4341 .collect();
3487 lines.push(match failure {
4342 lines.push(match failure {
3488 Some(error) => format!("failed: {error}"),
4343 Some(error) => format!("failed: {error}"),
3489 None => "ended without error".to_owned(),
4344 None => "ended without error".to_owned(),
@@ -3493,9 +4348,13 @@ fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Er
3493}
4348}
3494
4349
3495fn mask_address(token: &str) -> String {
4350fn mask_address(token: &str) -> String {
3496 let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
4351 let dotted_quad =
3497 let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
4352 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
3498 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address {
4353 let colon_address =
4354 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
4355 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
4356 || colon_address
4357 {
3499 "<addr>".to_owned()
4358 "<addr>".to_owned()
3500 } else {
4359 } else {
3501 token.to_owned()
4360 token.to_owned()
@@ -3516,7 +4375,11 @@ async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, to
3516 }
4375 }
3517}
4376}
3518
4377
3519async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) {
4378async fn poll_broker(
4379 signaling: Arc<Signaling>,
4380 conversation: Conversation,
4381 running: Arc<AtomicBool>,
4382) {
3520 let Ok(first) = conversation.link("subscribe") else {
4383 let Ok(first) = conversation.link("subscribe") else {
3521 return;
4384 return;
3522 };
4385 };
@@ -3564,25 +4427,17 @@ struct ShareReceive {
3564 pli_count: u32,
4427 pli_count: u32,
3565 fir_count: u32,
4428 fir_count: u32,
3566 freeze_count: u32,
4429 freeze_count: u32,
3567 qp_sum: u64,
3568 bytes_received: u64,
3569}
4430}
3570
4431
3571impl ShareReceive {
4432impl ShareReceive {
3572 fn average_qp(&self) -> u64 {
3573 self.qp_sum.checked_div(u64::from(self.frames_decoded)).unwrap_or(0)
3574 }
3575
3576 fn summary(&self) -> String {
4433 fn summary(&self) -> String {
3577 format!(
4434 format!(
3578 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
4435 " share in decoded={} keyframes={} {}x{} fps={:.0} pli={} fir={} freezes={}",
3579 self.frames_decoded,
4436 self.frames_decoded,
3580 self.key_frames_decoded,
4437 self.key_frames_decoded,
3581 self.width,
4438 self.width,
3582 self.height,
4439 self.height,
3583 self.frames_per_second,
4440 self.frames_per_second,
3584 self.average_qp(),
3585 self.bytes_received,
3586 self.pli_count,
4441 self.pli_count,
3587 self.fir_count,
4442 self.fir_count,
3588 self.freeze_count
4443 self.freeze_count
@@ -3606,7 +4461,10 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3606 }
4461 }
3607 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
4462 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
3608 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
4463 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
3609 snapshot.source_levels.push(format!("{}={:.3}", source.source.track_identifier, source.audio.audio_level));
4464 snapshot.source_levels.push(format!(
4465 "{}={:.3}",
4466 source.source.track_identifier, source.audio.audio_level
4467 ));
3610 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
4468 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
3611 }
4469 }
3612 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
4470 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
@@ -3626,24 +4484,32 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3626 pli_count: inbound.inbound.pli_count,
4484 pli_count: inbound.inbound.pli_count,
3627 fir_count: inbound.inbound.fir_count,
4485 fir_count: inbound.inbound.fir_count,
3628 freeze_count: inbound.inbound.freeze_count,
4486 freeze_count: inbound.inbound.freeze_count,
3629 qp_sum: inbound.inbound.qp_sum,
3630 bytes_received: inbound.inbound.bytes_received,
3631 });
4487 });
3632 }
4488 }
3633 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
4489 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
3634 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
4490 snapshot.video.inbound_width = snapshot
3635 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
4491 .video
4492 .inbound_width
4493 .max(inbound.inbound.frame_width);
4494 snapshot.video.inbound_height = snapshot
4495 .video
4496 .inbound_height
4497 .max(inbound.inbound.frame_height);
3636 }
4498 }
3637 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
4499 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
3638 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
4500 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
3639 snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0);
4501 snapshot.video.remote_round_trip_ms = snapshot
4502 .video
4503 .remote_round_trip_ms
4504 .max(remote.remote_inbound.round_trip_time * 1000.0);
3640 }
4505 }
3641 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
4506 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
3642 snapshot.video.outbound_packets += outbound.sent.packets_sent;
4507 snapshot.video.outbound_packets += outbound.sent.packets_sent;
3643 if share_mids.contains(&outbound.outbound.mid) {
4508 if share_mids.contains(&outbound.outbound.mid) {
3644 snapshot.share_outbound_packets += outbound.sent.packets_sent;
4509 snapshot.share_outbound_packets += outbound.sent.packets_sent;
3645 }
4510 }
3646 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
4511 snapshot.video.outbound_frames_encoded +=
4512 u64::from(outbound.outbound.frames_encoded);
3647 snapshot.video_senders.push(format!(
4513 snapshot.video_senders.push(format!(
3648 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
4514 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
3649 outbound.outbound.mid,
4515 outbound.outbound.mid,
@@ -3656,8 +4522,14 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3656 outbound.outbound.quality_limitation_reason,
4522 outbound.outbound.quality_limitation_reason,
3657 outbound.outbound.active
4523 outbound.outbound.active
3658 ));
4524 ));
3659 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
4525 snapshot.video.outbound_width = snapshot
3660 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
4526 .video
4527 .outbound_width
4528 .max(outbound.outbound.frame_width);
4529 snapshot.video.outbound_height = snapshot
4530 .video
4531 .outbound_height
4532 .max(outbound.outbound.frame_height);
3661 }
4533 }
3662 RtcStats::Transport(transport) => {
4534 RtcStats::Transport(transport) => {
3663 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
4535 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
@@ -3681,13 +4553,23 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3681 stats
4553 stats
3682 .iter()
4554 .iter()
3683 .find_map(|entry| match entry {
4555 .find_map(|entry| match entry {
3684 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate),
4556 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
3685 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate),
4557 Some(&local.local_candidate)
4558 }
4559 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
4560 Some(&remote.remote_candidate)
4561 }
3686 _ => None,
4562 _ => None,
3687 })
4563 })
3688 .map(|candidate| {
4564 .map(|candidate| {
3689 let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default();
4565 let kind = candidate
3690 let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default();
4566 .candidate_type
4567 .map(|kind| format!("{kind:?}"))
4568 .unwrap_or_default();
4569 let relay = candidate
4570 .relay_protocol
4571 .map(|relay| format!(" via {relay:?}"))
4572 .unwrap_or_default();
3691 format!("{kind}/{}{relay}", candidate.protocol)
4573 format!("{kind}/{}{relay}", candidate.protocol)
3692 })
4574 })
3693 .unwrap_or_else(|| "?".into())
4575 .unwrap_or_else(|| "?".into())
@@ -3704,22 +4586,24 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
3704
4586
3705#[cfg(test)]
4587#[cfg(test)]
3706mod tests {
4588mod tests {
3707 #[test]
3708 fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {
3709 assert!(!gathering_settled(false, None));
3710 assert!(!gathering_settled(false, Some(Duration::from_millis(50))));
3711 assert!(gathering_settled(false, Some(RELAY_SETTLE)));
3712 assert!(gathering_settled(true, None));
3713 }
3714
3715 #[tokio::test]
4589 #[tokio::test]
3716 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
4590 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
3717 let (handle, mut control) = crate::control::call_channel();
4591 let (handle, mut control) = crate::control::call_channel();
3718 handle.commands.send(CallCommand::Hangup).unwrap();
4592 handle.commands.send(CallCommand::Hangup).unwrap();
3719 let limit = Duration::from_millis(20);
4593 let limit = Duration::from_millis(20);
3720 let cancelled = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4594 let cancelled = setup_step_within(
4595 &mut control,
4596 limit,
4597 std::future::pending::<std::result::Result<(), Error>>(),
4598 )
4599 .await;
3721 assert!(matches!(cancelled, Err(Error::Cancelled)));
4600 assert!(matches!(cancelled, Err(Error::Cancelled)));
3722 let timed_out = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
4601 let timed_out = setup_step_within(
4602 &mut control,
4603 limit,
4604 std::future::pending::<std::result::Result<(), Error>>(),
4605 )
4606 .await;
3723 assert!(matches!(timed_out, Err(Error::Signaling(_))));
4607 assert!(matches!(timed_out, Err(Error::Signaling(_))));
3724 }
4608 }
3725
4609
@@ -3734,8 +4618,12 @@ mod tests {
3734
4618
3735 #[test]
4619 #[test]
3736 fn only_a_conflict_answer_retries_a_recording_stop() {
4620 fn only_a_conflict_answer_retries_a_recording_stop() {
3737 assert!(recorder_busy(&Error::Signaling("recording command answered HTTP 409 no answer".into())));
4621 assert!(recorder_busy(&Error::Signaling(
3738 assert!(!recorder_busy(&Error::Signaling("recording command answered HTTP 500 no answer".into())));
4622 "recording command answered HTTP 409 no answer".into()
4623 )));
4624 assert!(!recorder_busy(&Error::Signaling(
4625 "recording command answered HTTP 500 no answer".into()
4626 )));
3739 assert!(!recorder_busy(&Error::Cancelled));
4627 assert!(!recorder_busy(&Error::Cancelled));
3740 }
4628 }
3741
4629
@@ -3767,14 +4655,21 @@ mod tests {
3767 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
4655 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
3768
4656
3769 fn directions(sdp: &str) -> Vec<String> {
4657 fn directions(sdp: &str) -> Vec<String> {
3770 crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
4658 crate::sdp::parse(sdp)
4659 .unwrap()
4660 .media
4661 .iter()
4662 .map(|line| line.direction().unwrap_or("none").to_owned())
4663 .collect()
3771 }
4664 }
3772
4665
3773 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
4666 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
3774 use libwebrtc::audio_source::native::NativeAudioSource;
4667 use libwebrtc::audio_source::native::NativeAudioSource;
3775 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4668 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3776 let factory = devices::shared_factory();
4669 let factory = devices::shared_factory();
3777 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4670 let peer = factory
4671 .create_peer_connection(RtcConfiguration::default())
4672 .unwrap();
3778 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
4673 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3779 let track = factory.create_audio_track("microphone", source);
4674 let track = factory.create_audio_track("microphone", source);
3780 let offer = create_offer(&peer, &factory, &track, layout, None).await;
4675 let offer = create_offer(&peer, &factory, &track, layout, None).await;
@@ -3796,11 +4691,22 @@ mod tests {
3796 use libwebrtc::audio_source::native::NativeAudioSource;
4691 use libwebrtc::audio_source::native::NativeAudioSource;
3797 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4692 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3798 let factory = devices::shared_factory();
4693 let factory = devices::shared_factory();
3799 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
4694 let peer = factory
4695 .create_peer_connection(RtcConfiguration::default())
4696 .unwrap();
3800 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
4697 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3801 let track = factory.create_audio_track("microphone", source);
4698 let track = factory.create_audio_track("microphone", source);
3802 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
4699 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3803 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
4700 let answered = answer_offer(
4701 &peer,
4702 Some(&track),
4703 offer,
4704 AnswerVideo::Receive,
4705 None,
4706 false,
4707 None,
4708 )
4709 .await;
3804 peer.close();
4710 peer.close();
3805 if let Err(error) = answered {
4711 if let Err(error) = answered {
3806 panic!("{error}");
4712 panic!("{error}");
@@ -3809,51 +4715,144 @@ mod tests {
3809
4715
3810 #[test]
4716 #[test]
3811 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
4717 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3812 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
4718 assert_eq!(
3813 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
4719 directions(&directions_for(
3814 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
4720 Layout::OneToOne,
4721 false,
4722 false,
4723 false,
4724 CAMERA_MID,
4725 Some(ONE_TO_ONE_SHARE_MID),
4726 false,
4727 BROWSER_OFFER
4728 )),
4729 vec!["sendrecv", "inactive", "inactive"]
4730 );
4731 assert_eq!(
4732 directions(&directions_for(
4733 Layout::OneToOne,
4734 false,
4735 true,
4736 false,
4737 CAMERA_MID,
4738 Some(ONE_TO_ONE_SHARE_MID),
4739 false,
4740 BROWSER_OFFER
4741 )),
4742 vec!["sendrecv", "sendrecv", "inactive"]
4743 );
4744 assert_eq!(
4745 directions(&directions_for(
4746 Layout::OneToOne,
4747 false,
4748 false,
4749 true,
4750 CAMERA_MID,
4751 Some(ONE_TO_ONE_SHARE_MID),
4752 false,
4753 BROWSER_OFFER
4754 )),
4755 vec!["sendrecv", "inactive", "sendonly"]
4756 );
3815 }
4757 }
3816
4758
3817 #[test]
4759 #[test]
3818 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
4760 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3819 for layout in [Layout::OneToOne, Layout::Conference] {
4761 for layout in [Layout::OneToOne, Layout::Conference] {
3820 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
4762 assert_eq!(
4763 directions(&directions_for(
4764 layout,
4765 true,
4766 true,
4767 false,
4768 CAMERA_MID,
4769 None,
4770 false,
4771 BROWSER_OFFER
4772 )),
4773 vec!["inactive", "inactive", "inactive"]
4774 );
3821 }
4775 }
3822 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
4776 assert_eq!(
4777 directions_for(
4778 Layout::Conference,
4779 false,
4780 true,
4781 false,
4782 CAMERA_MID,
4783 None,
4784 false,
4785 BROWSER_OFFER
4786 ),
4787 BROWSER_OFFER
4788 );
3823 }
4789 }
3824
4790
3825 #[test]
4791 #[test]
3826 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
4792 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3827 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
4793 let held = directions_for(
4794 Layout::Conference,
4795 true,
4796 false,
4797 false,
4798 CAMERA_MID,
4799 None,
4800 false,
4801 BROWSER_OFFER,
4802 );
3828 let mut numbers = || 7;
4803 let mut numbers = || 7;
3829 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
4804 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers)
3830 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
4805 .unwrap()
4806 .sdp;
4807 assert_eq!(
4808 directions(&signaled),
4809 vec!["inactive", "inactive", "inactive"]
4810 );
3831 assert_eq!(signaled.matches("a=candidate:").count(), 1);
4811 assert_eq!(signaled.matches("a=candidate:").count(), 1);
3832 }
4812 }
3833
4813
3834 #[test]
4814 #[test]
3835 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
4815 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
3836 let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
4816 let target = |thread: &str| MeetingTarget {
3837 assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));
4817 thread_id: thread.into(),
3838 assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));
4818 tenant_id: "t".into(),
4819 organizer_id: "o".into(),
4820 meeting_data: None,
4821 };
4822 assert!(is_own_meeting(
4823 Some(&target("19:meeting_a@thread.v2")),
4824 &target("19:meeting_a@thread.v2")
4825 ));
4826 assert!(!is_own_meeting(
4827 Some(&target("19:meeting_a@thread.v2")),
4828 &target("19:meeting_b@thread.v2")
4829 ));
3839 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
4830 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
3840 }
4831 }
3841
4832
3842 #[test]
4833 #[test]
3843 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
4834 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
3844 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
4835 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
3845 assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);
4836 assert_eq!(
4837 accepted_modalities(true),
4838 vec!["Audio".to_owned(), "Video".to_owned()]
4839 );
3846 }
4840 }
3847
4841
3848 #[test]
4842 #[test]
3849 fn specs_map_to_invitation_targets() {
4843 fn specs_map_to_invitation_targets() {
3850 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
4844 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
3851 let people = CallSpec::People {
4845 let people = CallSpec::People {
3852 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
4846 callees: vec![Callee {
4847 mri: "8:orgid:b".into(),
4848 display_name: "Bea".into(),
4849 }],
3853 thread_id: "19:t@thread.v2".into(),
4850 thread_id: "19:t@thread.v2".into(),
3854 };
4851 };
3855 assert!(people.is_people() && !people.is_meeting());
4852 assert!(people.is_people() && !people.is_meeting());
3856 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
4853 assert!(
4854 matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")
4855 );
3857 let meeting = CallSpec::Meeting(MeetingTarget {
4856 let meeting = CallSpec::Meeting(MeetingTarget {
3858 thread_id: "19:meeting@thread.v2".into(),
4857 thread_id: "19:meeting@thread.v2".into(),
3859 tenant_id: "t".into(),
4858 tenant_id: "t".into(),
crates/calling/src/lib.rs +38 −36
@@ -3,54 +3,52 @@ pub mod audio;
3 3 pub mod audio_io;
4 4 pub mod awake;
5 5 pub mod background;
6 pub mod band_meter;
7 pub mod call;
8 pub mod candidates;
9 pub mod callee_gate;
10 6 pub mod blur;
11 7 pub mod breakout;
8 pub mod call;
9 pub mod callee_gate;
12 10 pub mod camera;
11 pub mod candidates;
13 12 pub mod captions;
14 pub mod composite;
15 13 pub mod capture;
14 pub mod composite;
16 15 pub mod control;
17 16 pub mod data_channel;
18 17 pub mod device_watch;
19 18 pub mod devices;
20 19 pub mod diagnostics;
21 pub mod engine;
22 20 pub mod effects;
23 21 pub mod end;
22 pub mod engine;
24 23 pub mod error;
25 pub mod health;
26 24 pub mod framing;
25 pub mod health;
27 26 pub mod hold;
28 27 pub mod join;
29 28 pub mod latest;
30 29 pub mod level;
30 #[cfg(windows)]
31 mod loopback_windows;
31 32 pub mod luma_effects;
32 33 pub mod mask;
33 pub mod motion;
34 34 pub mod matte;
35 35 #[cfg(windows)]
36 mod loopback_windows;
37 #[cfg(windows)]
38 36 mod mic_windows;
37 pub mod motion;
38 pub mod notices;
39 39 #[cfg(windows)]
40 40 pub use loopback_windows::start_process_capture;
41 41 #[cfg(windows)]
42 42 pub use mic_windows::probe_effects;
43 pub mod gain_stage;
43 44 pub mod meeting;
44 45 pub mod meeting_options;
45 pub mod mic_processing;
46 pub mod mixer;
47 pub mod gain_stage;
48 46 pub mod mic_chain;
49 47 pub mod mic_effects;
50 pub mod noise_stage;
51 pub mod voice_high_pass;
52 pub mod wav_dump;
48 pub mod mic_processing;
49 pub mod mixer;
53 50 pub mod mute;
51 pub mod noise_stage;
54 52 pub mod organizer;
55 53 pub mod outcome;
56 54 pub mod pcm;
@@ -76,42 +74,46 @@ pub mod trouter_events;
76 74 pub mod video_frame;
77 75 pub mod video_layout;
78 76 pub mod video_pattern;
77 pub mod video_quality;
79 78 pub mod video_receive;
80 79 pub mod video_send;
80 pub mod voice_high_pass;
81 pub mod wav_dump;
81 82 pub mod whiteboard;
82 83
83 84 pub use audio_io::AudioMode;
84 85 pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
85 86 pub use breakout::BreakoutMove;
86 pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
87 pub use effects::CameraEffects;
88 pub use hold::HoldState;
89 pub use whiteboard::ContentShare;
90 87 pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
88 pub use camera::{CameraCaptureStats, CameraDevice, camera_entries};
89 pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
91 90 pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
91 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
92 pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
93 pub use effects::CameraEffects;
92 94 pub use end::EndKind;
93 95 pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
94 pub use push::Caller;
95 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
96 pub use reaction::{Reaction, ReactionEvent};
97 pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
96 pub use error::{Error, Result};
97 pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
98 pub use hold::HoldState;
99 pub use level::SpeakingDetector;
98 100 pub use meeting_options::{MeetingOptions, OptionWrite};
101 pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
102 pub use mute::MuteCommand;
99 103 pub use organizer::{MeetingCapability, Modality, RecorderOption, modality_allowed};
104 pub use push::Caller;
105 pub use reaction::{Reaction, ReactionEvent};
100 106 pub use recording::{RecordingKind, StopScope};
101 pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
102 pub use sound_capture::LoopbackKind;
103 107 pub use renegotiation::MediaPath;
108 pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
109 pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
110 pub use screen::{ShareKind, SharePicker, ShareSource};
104 111 pub use signaling::{Callee, MeetingTarget};
105 pub use transfer::Replacement;
106 pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
107 pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
108 pub use error::{Error, Result};
109 pub use level::SpeakingDetector;
110 pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
111 pub use mute::MuteCommand;
112 pub use video_layout::{TileDetail, VideoWant};
112 pub use sound_capture::LoopbackKind;
113 113 pub use state::{CallSignal, CallState, EndReason};
114 pub use camera::{CameraDevice, camera_entries};
115 pub use screen::{ShareKind, ShareSource};
114 pub use transfer::Replacement;
116 115 pub use video_frame::{VideoHub, VideoKey, VideoPicture};
116 pub use video_layout::{TileDetail, VideoWant};
117 pub use video_quality::VideoQuality;
117 118 pub use video_send::VideoMode;
119 pub use whiteboard::ContentShare;
@@ -3,54 +3,52 @@ pub mod audio;
3pub mod audio_io;
3pub mod audio_io;
4pub mod awake;
4pub mod awake;
5pub mod background;
5pub mod background;
6pub mod band_meter;
7pub mod call;
8pub mod candidates;
9pub mod callee_gate;
10pub mod blur;
6pub mod blur;
11pub mod breakout;
7pub mod breakout;
8pub mod call;
9pub mod callee_gate;
12pub mod camera;
10pub mod camera;
11pub mod candidates;
13pub mod captions;
12pub mod captions;
14pub mod composite;
15pub mod capture;
13pub mod capture;
14pub mod composite;
16pub mod control;
15pub mod control;
17pub mod data_channel;
16pub mod data_channel;
18pub mod device_watch;
17pub mod device_watch;
19pub mod devices;
18pub mod devices;
20pub mod diagnostics;
19pub mod diagnostics;
21pub mod engine;
22pub mod effects;
20pub mod effects;
23pub mod end;
21pub mod end;
22pub mod engine;
24pub mod error;
23pub mod error;
25pub mod health;
26pub mod framing;
24pub mod framing;
25pub mod health;
27pub mod hold;
26pub mod hold;
28pub mod join;
27pub mod join;
29pub mod latest;
28pub mod latest;
30pub mod level;
29pub mod level;
30#[cfg(windows)]
31mod loopback_windows;
31pub mod luma_effects;
32pub mod luma_effects;
32pub mod mask;
33pub mod mask;
33pub mod motion;
34pub mod matte;
34pub mod matte;
35#[cfg(windows)]
35#[cfg(windows)]
36mod loopback_windows;
37#[cfg(windows)]
38mod mic_windows;
36mod mic_windows;
37pub mod motion;
38pub mod notices;
39#[cfg(windows)]
39#[cfg(windows)]
40pub use loopback_windows::start_process_capture;
40pub use loopback_windows::start_process_capture;
41#[cfg(windows)]
41#[cfg(windows)]
42pub use mic_windows::probe_effects;
42pub use mic_windows::probe_effects;
43pub mod gain_stage;
43pub mod meeting;
44pub mod meeting;
44pub mod meeting_options;
45pub mod meeting_options;
45pub mod mic_processing;
46pub mod mixer;
47pub mod gain_stage;
48pub mod mic_chain;
46pub mod mic_chain;
49pub mod mic_effects;
47pub mod mic_effects;
50pub mod noise_stage;
48pub mod mic_processing;
51pub mod voice_high_pass;
49pub mod mixer;
52pub mod wav_dump;
53pub mod mute;
50pub mod mute;
51pub mod noise_stage;
54pub mod organizer;
52pub mod organizer;
55pub mod outcome;
53pub mod outcome;
56pub mod pcm;
54pub mod pcm;
@@ -76,42 +74,46 @@ pub mod trouter_events;
76pub mod video_frame;
74pub mod video_frame;
77pub mod video_layout;
75pub mod video_layout;
78pub mod video_pattern;
76pub mod video_pattern;
77pub mod video_quality;
79pub mod video_receive;
78pub mod video_receive;
80pub mod video_send;
79pub mod video_send;
80pub mod voice_high_pass;
81pub mod wav_dump;
81pub mod whiteboard;
82pub mod whiteboard;
82
83
83pub use audio_io::AudioMode;
84pub use audio_io::AudioMode;
84pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
85pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
85pub use breakout::BreakoutMove;
86pub use breakout::BreakoutMove;
86pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
87pub use effects::CameraEffects;
88pub use hold::HoldState;
89pub use whiteboard::ContentShare;
90pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
87pub use call::{AcceptMode, CallOptions, CallReport, CallSpec, run_test_call};
88pub use camera::{CameraCaptureStats, CameraDevice, camera_entries};
89pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
91pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
90pub use control::{CallCommand, CallControl, CallHandle, CallUpdate, Progress, call_channel};
91pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
92pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
93pub use effects::CameraEffects;
92pub use end::EndKind;
94pub use end::EndKind;
93pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
95pub use engine::{CallEngine, EngineConfig, EngineEvent, IncomingRing};
94pub use push::Caller;
96pub use error::{Error, Result};
95pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
97pub use health::{CallHealth, HealthSample, Limitation, NetworkLevel, TransportDetails};
96pub use reaction::{Reaction, ReactionEvent};
98pub use hold::HoldState;
97pub use captions::{CaptionEntry, CaptionState, SPOKEN_LANGUAGES};
99pub use level::SpeakingDetector;
98pub use meeting_options::{MeetingOptions, OptionWrite};
100pub use meeting_options::{MeetingOptions, OptionWrite};
101pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
102pub use mute::MuteCommand;
99pub use organizer::{MeetingCapability, Modality, RecorderOption, modality_allowed};
103pub use organizer::{MeetingCapability, Modality, RecorderOption, modality_allowed};
104pub use push::Caller;
105pub use reaction::{Reaction, ReactionEvent};
100pub use recording::{RecordingKind, StopScope};
106pub use recording::{RecordingKind, StopScope};
101pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
102pub use sound_capture::LoopbackKind;
103pub use renegotiation::MediaPath;
107pub use renegotiation::MediaPath;
108pub use ring::{RING_TIMEOUT, RingEnd, RingSignal, RingState};
109pub use roster::{AttendeeLimits, MeetingRole, PublishedState, RaisedHand, RosterEntry, Spotlight};
110pub use screen::{ShareKind, SharePicker, ShareSource};
104pub use signaling::{Callee, MeetingTarget};
111pub use signaling::{Callee, MeetingTarget};
105pub use transfer::Replacement;
112pub use sound_capture::LoopbackKind;
106pub use diagnostics::{CallDiagnostics, SdpLine, SdpSummary, StatsSample};
107pub use devices::{AudioDevice, DeviceChoice, DeviceEntry, DeviceLists};
108pub use error::{Error, Result};
109pub use level::SpeakingDetector;
110pub use mic_processing::{ApmConfig, MicSettings, NoiseSuppression};
111pub use mute::MuteCommand;
112pub use video_layout::{TileDetail, VideoWant};
113pub use state::{CallSignal, CallState, EndReason};
113pub use state::{CallSignal, CallState, EndReason};
114pub use camera::{CameraDevice, camera_entries};
114pub use transfer::Replacement;
115pub use screen::{ShareKind, ShareSource};
116pub use video_frame::{VideoHub, VideoKey, VideoPicture};
115pub use video_frame::{VideoHub, VideoKey, VideoPicture};
116pub use video_layout::{TileDetail, VideoWant};
117pub use video_quality::VideoQuality;
117pub use video_send::VideoMode;
118pub use video_send::VideoMode;
119pub use whiteboard::ContentShare;
crates/calling/src/notices.rs added +110 −0
@@ -0,0 +1,110 @@
1 //! Call notice payloads: i18n keys (and optional detail after [`NOTICE_DETAIL_SEP`]).
2 pub const NOTICE_DETAIL_SEP: char = '\u{1f}';
3
4 pub const CONSENT_FIRST_NOTICE: &str = "calls.notice.consent_first";
5 pub const ON_HOLD_NOTICE: &str = "calls.notice.on_hold";
6 pub const CHANGE_RUNNING_NOTICE: &str = "calls.notice.change_running";
7 pub const VIDEO_FAILED_NOTICE: &str = "calls.notice.video_failed";
8 pub const SHARE_QUEUED_NOTICE: &str = "calls.notice.share_queued";
9 pub const SHARE_REFUSED_NOTICE: &str = "calls.notice.share_refused";
10 pub const NOT_CONNECTED_FOR_VIDEO: &str = "calls.notice.video_starts_once_connected";
11 pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";
12 pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";
13 pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";
14 pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";
15 pub const CAPTIONS_JOIN_FAILED_NOTICE: &str = "calls.notice.captions_join_failed";
16 pub const CAPTION_LANGUAGE_FAILED_NOTICE: &str = "calls.notice.caption_language_failed";
17 pub const CAMERA_START_NOTICE: &str = "calls.notice.camera_start";
18 pub const CAMERA_RESTART_NOTICE: &str = "calls.notice.camera_restart";
19 pub const SHARING_START_NOTICE: &str = "calls.notice.sharing_start";
20 pub const RAISE_HAND_FAILED_NOTICE: &str = "calls.notice.raise_hand_failed";
21 pub const LOWER_HAND_FAILED_NOTICE: &str = "calls.notice.lower_hand_failed";
22 pub const LOWER_THAT_HAND_FAILED_NOTICE: &str = "calls.notice.lower_that_hand_failed";
23 pub const LOWER_ALL_HANDS_FAILED_NOTICE: &str = "calls.notice.lower_all_hands_failed";
24 pub const CONFIRM_RECORDING_FAILED_NOTICE: &str = "calls.notice.confirm_recording_failed";
25 pub const HOLD_FAILED_NOTICE: &str = "calls.notice.hold_failed";
26 pub const RESUME_FAILED_NOTICE: &str = "calls.notice.resume_failed";
27 pub const TRANSFER_NOT_ALLOWED_NOTICE: &str = "calls.notice.transfer_not_allowed";
28 pub const TRANSFER_CALL_FAILED_NOTICE: &str = "calls.notice.transfer_call_failed";
29 pub const TRANSFERRING_NOTICE: &str = "calls.notice.transferring";
30 pub const WHITEBOARDS_MEETINGS_ONLY_NOTICE: &str = "calls.notice.whiteboards_meetings_only";
31 pub const WHITEBOARD_OPEN_FAILED_NOTICE: &str = "calls.notice.whiteboard_open_failed";
32 pub const REACTION_FAILED_NOTICE: &str = "calls.notice.reaction_failed";
33 pub const RECORDING_NOT_STARTED_NOTICE: &str = "calls.notice.recording_not_started";
34 pub const RECORDING_START_FAILED_NOTICE: &str = "calls.notice.recording_start_failed";
35 pub const CAPTIONS_START_FAILED_NOTICE: &str = "calls.notice.captions_start_failed";
36 pub const HOLD_CHANGE_FAILED_NOTICE: &str = "calls.notice.hold_change_failed";
37 pub const RECORDING_STOP_FAILED_NOTICE: &str = "calls.notice.recording_stop_failed";
38 pub const BACKGROUND_IMAGE_FAILED_NOTICE: &str = "calls.notice.background_image_failed";
39 pub const CAMERA_STOPPED_NOTICE: &str = "calls.notice.camera_stopped";
40 pub const SCREEN_SHARE_STOPPED_NOTICE: &str = "calls.notice.screen_share_stopped";
41 pub const ADMIT_FAILED_NOTICE: &str = "calls.notice.admit_failed";
42 pub const ADMIT_ALL_FAILED_NOTICE: &str = "calls.notice.admit_all_failed";
43 pub const DENY_FAILED_NOTICE: &str = "calls.notice.deny_failed";
44 pub const REMOVE_PARTICIPANT_FAILED_NOTICE: &str = "calls.notice.remove_participant_failed";
45 pub const MUTE_PARTICIPANT_FAILED_NOTICE: &str = "calls.notice.mute_participant_failed";
46 pub const MUTE_ALL_FAILED_NOTICE: &str = "calls.notice.mute_all_failed";
47 pub const MEETING_LOCK_FAILED_NOTICE: &str = "calls.notice.meeting_lock_failed";
48 pub const CHANGE_ROLE_FAILED_NOTICE: &str = "calls.notice.change_role_failed";
49 pub const MIC_SETTING_FAILED_NOTICE: &str = "calls.notice.mic_setting_failed";
50 pub const CAMERA_SETTING_FAILED_NOTICE: &str = "calls.notice.camera_setting_failed";
51 pub const ATTENDEE_SETTINGS_FAILED_NOTICE: &str = "calls.notice.attendee_settings_failed";
52 pub const INVITE_PERSON_FAILED_NOTICE: &str = "calls.notice.invite_person_failed";
53 pub const SPOTLIGHT_FAILED_NOTICE: &str = "calls.notice.spotlight_failed";
54 pub const STOP_SPOTLIGHT_FAILED_NOTICE: &str = "calls.notice.stop_spotlight_failed";
55
56 pub fn notice_with_detail(key: &'static str, detail: impl std::fmt::Display) -> String {
57 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
58 }
59
60 #[cfg(test)]
61 mod tests {
62 use super::*;
63
64 #[test]
65 fn notice_id_fixed_keys_match_catalog_paths() {
66 assert_eq!(CONSENT_FIRST_NOTICE, "calls.notice.consent_first");
67 assert_eq!(ON_HOLD_NOTICE, "calls.notice.on_hold");
68 assert_eq!(CHANGE_RUNNING_NOTICE, "calls.notice.change_running");
69 assert_eq!(VIDEO_FAILED_NOTICE, "calls.notice.video_failed");
70 assert_eq!(SHARE_QUEUED_NOTICE, "calls.notice.share_queued");
71 assert_eq!(SHARE_REFUSED_NOTICE, "calls.notice.share_refused");
72 assert_eq!(
73 NOT_CONNECTED_FOR_VIDEO,
74 "calls.notice.video_starts_once_connected"
75 );
76 assert_eq!(PORTAL_UNAVAILABLE_NOTICE, "calls.notice.portal_unavailable");
77 assert_eq!(CALL_TRANSFERRED_NOTICE, "calls.notice.call_transferred");
78 assert_eq!(TRANSFER_FAILED_NOTICE, "calls.notice.transfer_failed");
79 assert_eq!(
80 RECORDING_JOIN_FAILED_NOTICE,
81 "calls.notice.recording_join_failed"
82 );
83 assert_eq!(
84 CAPTIONS_JOIN_FAILED_NOTICE,
85 "calls.notice.captions_join_failed"
86 );
87 assert_eq!(
88 CAPTION_LANGUAGE_FAILED_NOTICE,
89 "calls.notice.caption_language_failed"
90 );
91 assert_eq!(CAMERA_START_NOTICE, "calls.notice.camera_start");
92 assert_eq!(CAMERA_RESTART_NOTICE, "calls.notice.camera_restart");
93 assert_eq!(SHARING_START_NOTICE, "calls.notice.sharing_start");
94 assert_eq!(RAISE_HAND_FAILED_NOTICE, "calls.notice.raise_hand_failed");
95 assert_eq!(TRANSFERRING_NOTICE, "calls.notice.transferring");
96 assert_eq!(ADMIT_FAILED_NOTICE, "calls.notice.admit_failed");
97 assert_eq!(
98 BACKGROUND_IMAGE_FAILED_NOTICE,
99 "calls.notice.background_image_failed"
100 );
101 }
102
103 #[test]
104 fn notice_id_camera_payload_uses_key_and_detail_sep() {
105 let payload = notice_with_detail(CAMERA_START_NOTICE, "device busy");
106 assert!(payload.starts_with("calls.notice.camera_start"));
107 assert!(payload.contains(NOTICE_DETAIL_SEP));
108 assert!(payload.ends_with("device busy"));
109 }
110 }
@@ -0,0 +1,110 @@
1//! Call notice payloads: i18n keys (and optional detail after [`NOTICE_DETAIL_SEP`]).
2pub const NOTICE_DETAIL_SEP: char = '\u{1f}';
3
4pub const CONSENT_FIRST_NOTICE: &str = "calls.notice.consent_first";
5pub const ON_HOLD_NOTICE: &str = "calls.notice.on_hold";
6pub const CHANGE_RUNNING_NOTICE: &str = "calls.notice.change_running";
7pub const VIDEO_FAILED_NOTICE: &str = "calls.notice.video_failed";
8pub const SHARE_QUEUED_NOTICE: &str = "calls.notice.share_queued";
9pub const SHARE_REFUSED_NOTICE: &str = "calls.notice.share_refused";
10pub const NOT_CONNECTED_FOR_VIDEO: &str = "calls.notice.video_starts_once_connected";
11pub const PORTAL_UNAVAILABLE_NOTICE: &str = "calls.notice.portal_unavailable";
12pub const CALL_TRANSFERRED_NOTICE: &str = "calls.notice.call_transferred";
13pub const TRANSFER_FAILED_NOTICE: &str = "calls.notice.transfer_failed";
14pub const RECORDING_JOIN_FAILED_NOTICE: &str = "calls.notice.recording_join_failed";
15pub const CAPTIONS_JOIN_FAILED_NOTICE: &str = "calls.notice.captions_join_failed";
16pub const CAPTION_LANGUAGE_FAILED_NOTICE: &str = "calls.notice.caption_language_failed";
17pub const CAMERA_START_NOTICE: &str = "calls.notice.camera_start";
18pub const CAMERA_RESTART_NOTICE: &str = "calls.notice.camera_restart";
19pub const SHARING_START_NOTICE: &str = "calls.notice.sharing_start";
20pub const RAISE_HAND_FAILED_NOTICE: &str = "calls.notice.raise_hand_failed";
21pub const LOWER_HAND_FAILED_NOTICE: &str = "calls.notice.lower_hand_failed";
22pub const LOWER_THAT_HAND_FAILED_NOTICE: &str = "calls.notice.lower_that_hand_failed";
23pub const LOWER_ALL_HANDS_FAILED_NOTICE: &str = "calls.notice.lower_all_hands_failed";
24pub const CONFIRM_RECORDING_FAILED_NOTICE: &str = "calls.notice.confirm_recording_failed";
25pub const HOLD_FAILED_NOTICE: &str = "calls.notice.hold_failed";
26pub const RESUME_FAILED_NOTICE: &str = "calls.notice.resume_failed";
27pub const TRANSFER_NOT_ALLOWED_NOTICE: &str = "calls.notice.transfer_not_allowed";
28pub const TRANSFER_CALL_FAILED_NOTICE: &str = "calls.notice.transfer_call_failed";
29pub const TRANSFERRING_NOTICE: &str = "calls.notice.transferring";
30pub const WHITEBOARDS_MEETINGS_ONLY_NOTICE: &str = "calls.notice.whiteboards_meetings_only";
31pub const WHITEBOARD_OPEN_FAILED_NOTICE: &str = "calls.notice.whiteboard_open_failed";
32pub const REACTION_FAILED_NOTICE: &str = "calls.notice.reaction_failed";
33pub const RECORDING_NOT_STARTED_NOTICE: &str = "calls.notice.recording_not_started";
34pub const RECORDING_START_FAILED_NOTICE: &str = "calls.notice.recording_start_failed";
35pub const CAPTIONS_START_FAILED_NOTICE: &str = "calls.notice.captions_start_failed";
36pub const HOLD_CHANGE_FAILED_NOTICE: &str = "calls.notice.hold_change_failed";
37pub const RECORDING_STOP_FAILED_NOTICE: &str = "calls.notice.recording_stop_failed";
38pub const BACKGROUND_IMAGE_FAILED_NOTICE: &str = "calls.notice.background_image_failed";
39pub const CAMERA_STOPPED_NOTICE: &str = "calls.notice.camera_stopped";
40pub const SCREEN_SHARE_STOPPED_NOTICE: &str = "calls.notice.screen_share_stopped";
41pub const ADMIT_FAILED_NOTICE: &str = "calls.notice.admit_failed";
42pub const ADMIT_ALL_FAILED_NOTICE: &str = "calls.notice.admit_all_failed";
43pub const DENY_FAILED_NOTICE: &str = "calls.notice.deny_failed";
44pub const REMOVE_PARTICIPANT_FAILED_NOTICE: &str = "calls.notice.remove_participant_failed";
45pub const MUTE_PARTICIPANT_FAILED_NOTICE: &str = "calls.notice.mute_participant_failed";
46pub const MUTE_ALL_FAILED_NOTICE: &str = "calls.notice.mute_all_failed";
47pub const MEETING_LOCK_FAILED_NOTICE: &str = "calls.notice.meeting_lock_failed";
48pub const CHANGE_ROLE_FAILED_NOTICE: &str = "calls.notice.change_role_failed";
49pub const MIC_SETTING_FAILED_NOTICE: &str = "calls.notice.mic_setting_failed";
50pub const CAMERA_SETTING_FAILED_NOTICE: &str = "calls.notice.camera_setting_failed";
51pub const ATTENDEE_SETTINGS_FAILED_NOTICE: &str = "calls.notice.attendee_settings_failed";
52pub const INVITE_PERSON_FAILED_NOTICE: &str = "calls.notice.invite_person_failed";
53pub const SPOTLIGHT_FAILED_NOTICE: &str = "calls.notice.spotlight_failed";
54pub const STOP_SPOTLIGHT_FAILED_NOTICE: &str = "calls.notice.stop_spotlight_failed";
55
56pub fn notice_with_detail(key: &'static str, detail: impl std::fmt::Display) -> String {
57 format!("{key}{NOTICE_DETAIL_SEP}{detail}")
58}
59
60#[cfg(test)]
61mod tests {
62 use super::*;
63
64 #[test]
65 fn notice_id_fixed_keys_match_catalog_paths() {
66 assert_eq!(CONSENT_FIRST_NOTICE, "calls.notice.consent_first");
67 assert_eq!(ON_HOLD_NOTICE, "calls.notice.on_hold");
68 assert_eq!(CHANGE_RUNNING_NOTICE, "calls.notice.change_running");
69 assert_eq!(VIDEO_FAILED_NOTICE, "calls.notice.video_failed");
70 assert_eq!(SHARE_QUEUED_NOTICE, "calls.notice.share_queued");
71 assert_eq!(SHARE_REFUSED_NOTICE, "calls.notice.share_refused");
72 assert_eq!(
73 NOT_CONNECTED_FOR_VIDEO,
74 "calls.notice.video_starts_once_connected"
75 );
76 assert_eq!(PORTAL_UNAVAILABLE_NOTICE, "calls.notice.portal_unavailable");
77 assert_eq!(CALL_TRANSFERRED_NOTICE, "calls.notice.call_transferred");
78 assert_eq!(TRANSFER_FAILED_NOTICE, "calls.notice.transfer_failed");
79 assert_eq!(
80 RECORDING_JOIN_FAILED_NOTICE,
81 "calls.notice.recording_join_failed"
82 );
83 assert_eq!(
84 CAPTIONS_JOIN_FAILED_NOTICE,
85 "calls.notice.captions_join_failed"
86 );
87 assert_eq!(
88 CAPTION_LANGUAGE_FAILED_NOTICE,
89 "calls.notice.caption_language_failed"
90 );
91 assert_eq!(CAMERA_START_NOTICE, "calls.notice.camera_start");
92 assert_eq!(CAMERA_RESTART_NOTICE, "calls.notice.camera_restart");
93 assert_eq!(SHARING_START_NOTICE, "calls.notice.sharing_start");
94 assert_eq!(RAISE_HAND_FAILED_NOTICE, "calls.notice.raise_hand_failed");
95 assert_eq!(TRANSFERRING_NOTICE, "calls.notice.transferring");
96 assert_eq!(ADMIT_FAILED_NOTICE, "calls.notice.admit_failed");
97 assert_eq!(
98 BACKGROUND_IMAGE_FAILED_NOTICE,
99 "calls.notice.background_image_failed"
100 );
101 }
102
103 #[test]
104 fn notice_id_camera_payload_uses_key_and_detail_sep() {
105 let payload = notice_with_detail(CAMERA_START_NOTICE, "device busy");
106 assert!(payload.starts_with("calls.notice.camera_start"));
107 assert!(payload.contains(NOTICE_DETAIL_SEP));
108 assert!(payload.ends_with("device busy"));
109 }
110}
crates/calling/src/screen.rs +321 −36
@@ -1,15 +1,17 @@
1 use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
1 2 use std::sync::{Arc, Mutex};
2 use std::sync::atomic::{AtomicU32, Ordering};
3 3 use std::time::Duration;
4 4
5 use libwebrtc::desktop_capturer::{CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions};
5 use libwebrtc::desktop_capturer::{
6 CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7 PortalPickerEvent,
8 };
6 9 use libwebrtc::native::yuv_helper::argb_to_i420;
7 10 use libwebrtc::video_frame::I420Buffer;
8 11
9 12 use crate::capture::Capture;
10 use crate::video_frame::VideoPicture;
11 13 use crate::error::{Error, Result};
12
14 use crate::video_frame::VideoPicture;
13 15
14 16 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
15 17 pub enum ShareKind {
@@ -50,7 +52,9 @@ fn capturer(kind: ShareKind) -> Option<DesktopCapturer> {
50 52 }
51 53
52 54 fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
53 let Some(capturer) = capturer(kind) else { return Vec::new() };
55 let Some(capturer) = capturer(kind) else {
56 return Vec::new();
57 };
54 58 capturer
55 59 .get_source_list()
56 60 .into_iter()
@@ -77,22 +81,34 @@ pub fn list_share_sources() -> Vec<ShareSource> {
77 81 const THUMBNAIL_ATTEMPTS: u32 = 5;
78 82 const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
79 83
80 pub fn share_thumbnail(wanted: &ShareSource, max_width: u32, max_height: u32) -> Option<VideoPicture> {
81 let source = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw)?;
84 pub fn share_thumbnail(
85 wanted: &ShareSource,
86 max_width: u32,
87 max_height: u32,
88 ) -> Option<VideoPicture> {
89 let source = sources_of(wanted.kind)
90 .into_iter()
91 .find(|(source, _)| source.id == wanted.id)
92 .map(|(_, raw)| raw)?;
82 93 let mut capturer = capturer(wanted.kind)?;
83 94 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
84 95 let sink = captured.clone();
85 96 capturer.start_capture(Some(source), move |result| {
86 97 let Ok(frame) = result else { return };
87 98 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
88 if let Some(picture) = scaled_bgra(frame.data(), width, height, frame.stride(), max_width, max_height)
89 && let Ok(mut slot) = sink.lock()
99 if let Some(picture) = scaled_bgra(
100 frame.data(),
101 width,
102 height,
103 frame.stride(),
104 max_width,
105 max_height,
106 ) && let Ok(mut slot) = sink.lock()
90 107 {
91 108 *slot = Some(picture);
92 109 }
93 110 });
94 111 for _ in 0..THUMBNAIL_ATTEMPTS {
95 pump_messages();
96 112 capturer.capture_frame();
97 113 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
98 114 return Some(picture);
@@ -102,28 +118,28 @@ pub fn share_thumbnail(wanted: &ShareSource, max_width: u32, max_height: u32) ->
102 118 None
103 119 }
104 120
105 // Windows Graphics Capture hands frames to a DispatcherQueue on this thread; without a pump none arrive.
106 #[cfg(windows)]
107 fn pump_messages() {
108 use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage};
109 let mut message = MSG::default();
110 unsafe {
111 while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() {
112 let _ = TranslateMessage(&message);
113 let _ = DispatchMessageW(&message);
114 }
115 }
116 }
117
118 #[cfg(not(windows))]
119 fn pump_messages() {}
120
121 fn scaled_bgra(bytes: &[u8], width: u32, height: u32, stride: u32, max_width: u32, max_height: u32) -> Option<VideoPicture> {
122 if width == 0 || height == 0 || (stride as usize) < width as usize * 4 || bytes.len() < stride as usize * height as usize {
121 fn scaled_bgra(
122 bytes: &[u8],
123 width: u32,
124 height: u32,
125 stride: u32,
126 max_width: u32,
127 max_height: u32,
128 ) -> Option<VideoPicture> {
129 if width == 0
130 || height == 0
131 || (stride as usize) < width as usize * 4
132 || bytes.len() < stride as usize * height as usize
133 {
123 134 return None;
124 135 }
125 let scale = (max_width as f32 / width as f32).min(max_height as f32 / height as f32).min(1.);
126 let (target_width, target_height) = (((width as f32 * scale) as u32).max(1), ((height as f32 * scale) as u32).max(1));
136 let scale = (max_width as f32 / width as f32)
137 .min(max_height as f32 / height as f32)
138 .min(1.);
139 let (target_width, target_height) = (
140 ((width as f32 * scale) as u32).max(1),
141 ((height as f32 * scale) as u32).max(1),
142 );
127 143 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
128 144 for row in 0..target_height {
129 145 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
@@ -133,14 +149,29 @@ fn scaled_bgra(bytes: &[u8], width: u32, height: u32, stride: u32, max_width: u3
133 149 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
134 150 }
135 151 }
136 Some(VideoPicture { width: target_width, height: target_height, bgra })
152 Some(VideoPicture {
153 width: target_width,
154 height: target_height,
155 bgra,
156 })
137 157 }
138 158
139 159 fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
140 160 let mut buffer = I420Buffer::new(width, height);
141 161 let (stride_y, stride_u, stride_v) = buffer.strides();
142 162 let (plane_y, plane_u, plane_v) = buffer.data_mut();
143 argb_to_i420(bytes, stride, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
163 argb_to_i420(
164 bytes,
165 stride,
166 plane_y,
167 stride_y,
168 plane_u,
169 stride_u,
170 plane_v,
171 stride_v,
172 width as i32,
173 height as i32,
174 );
144 175 buffer
145 176 }
146 177
@@ -150,8 +181,19 @@ pub fn start_screen_capture(
150 181 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
151 182 failed: impl FnOnce(String) + Send + 'static,
152 183 ) -> Result<Capture> {
184 if current_share_picker() == SharePicker::Portal {
185 return start_portal_capture(wanted.kind, fps, deliver, move |follow| {
186 if let PortalFollowUp::Notice(text) = follow {
187 failed(text.to_owned());
188 }
189 });
190 }
153 191 Capture::spawn_thread("screen-capture", move |stop| {
154 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
192 let Some(source) = sources_of(wanted.kind)
193 .into_iter()
194 .find(|(source, _)| source.id == wanted.id)
195 .map(|(_, raw)| raw)
196 else {
155 197 return failed("the shared source is gone".to_owned());
156 198 };
157 199 let Some(mut capturer) = capturer(wanted.kind) else {
@@ -165,7 +207,6 @@ pub fn start_screen_capture(
165 207 }
166 208 });
167 209 while !stop.load(Ordering::SeqCst) {
168 pump_messages();
169 210 capturer.capture_frame();
170 211 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
171 212 }
@@ -173,15 +214,146 @@ pub fn start_screen_capture(
173 214 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
174 215 }
175 216
217 /// Where the share menu gets its sources. Wayland uses the desktop dialog.
218 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
219 pub enum SharePicker {
220 List,
221 Portal,
222 }
223
224 pub fn share_picker_for(wayland_display: Option<&str>) -> SharePicker {
225 match wayland_display {
226 Some(value) if !value.is_empty() => SharePicker::Portal,
227 _ => SharePicker::List,
228 }
229 }
230
231 pub fn current_share_picker() -> SharePicker {
232 share_picker_for(std::env::var("WAYLAND_DISPLAY").ok().as_deref())
233 }
234
235 /// Portal menus must not enumerate or thumbnail sources. That would open the dialog early.
236 pub fn share_sources_for_menu(picker: SharePicker, sources: Vec<ShareSource>) -> Vec<ShareSource> {
237 match picker {
238 SharePicker::Portal => Vec::new(),
239 SharePicker::List => sources,
240 }
241 }
242
243 pub use crate::notices::PORTAL_UNAVAILABLE_NOTICE;
244
245 #[derive(Debug, Clone, PartialEq, Eq)]
246 pub enum PortalFollowUp {
247 Share(ShareSource),
248 Quiet,
249 Notice(&'static str),
250 }
251
252 pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -> PortalFollowUp {
253 match event {
254 PortalPickerEvent::Selected => match source {
255 Some(source) => PortalFollowUp::Share(source),
256 None => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
257 },
258 PortalPickerEvent::Cancelled => PortalFollowUp::Quiet,
259 PortalPickerEvent::Failed => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
260 }
261 }
262
263 pub(crate) fn start_portal_capture(
264 kind: ShareKind,
265 fps: Arc<AtomicU32>,
266 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
267 outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
268 ) -> Result<Capture> {
269 Capture::spawn_thread("portal-share", move |stop| {
270 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
271 let Some(mut capturer) = capturer(kind) else {
272 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
273 return;
274 };
275 let selected = Arc::new(AtomicBool::new(false));
276 let gate = selected.clone();
277 capturer.start_capture(None, move |result| {
278 if !gate.load(Ordering::SeqCst) {
279 return;
280 }
281 let Ok(frame) = result else { return };
282 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
283 if width >= 2 && height >= 2 {
284 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
285 }
286 });
287 if !capturer.has_delegated_picker() {
288 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
289 return;
290 }
291 let (sender, receiver) = std::sync::mpsc::channel();
292 capturer.watch_picker(move |event| {
293 let _ = sender.send(event);
294 });
295 capturer.ensure_picker_visible();
296 let event = loop {
297 if stop.load(Ordering::SeqCst) {
298 return;
299 }
300 match receiver.recv_timeout(Duration::from_millis(40)) {
301 Ok(event) => break event,
302 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
303 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
304 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
305 return;
306 }
307 }
308 };
309 if stop.load(Ordering::SeqCst) {
310 return;
311 }
312 // The portal already bound this stream. Looking the source up again, or
313 // selecting that id, is what used to tear the stream down and report
314 // "the shared source is gone".
315 let source = if event == PortalPickerEvent::Selected {
316 selected.store(true, Ordering::SeqCst);
317 Some(ShareSource {
318 id: 0,
319 kind,
320 title: String::new(),
321 })
322 } else {
323 None
324 };
325 let follow = portal_follow_up(event, source);
326 if !matches!(follow, PortalFollowUp::Share(_)) {
327 outcome(follow);
328 return;
329 }
330 capturer.capture_frame();
331 outcome(follow);
332 while !stop.load(Ordering::SeqCst) {
333 capturer.capture_frame();
334 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
335 }
336 })
337 .map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
338 }
339
176 340 #[cfg(test)]
177 341 mod tests {
178 342 use super::*;
179 343
180 344 #[test]
181 345 fn sources_get_readable_labels() {
182 let screen = ShareSource { id: 1, kind: ShareKind::Screen, title: String::new() };
346 let screen = ShareSource {
347 id: 1,
348 kind: ShareKind::Screen,
349 title: String::new(),
350 };
183 351 assert_eq!(screen.label(), "Entire screen");
184 let window = ShareSource { id: 2, kind: ShareKind::Window, title: " Notes ".into() };
352 let window = ShareSource {
353 id: 2,
354 kind: ShareKind::Window,
355 title: " Notes ".into(),
356 };
185 357 assert_eq!(window.label(), "Notes");
186 358 }
187 359 }
@@ -207,3 +379,116 @@ mod thumbnail_tests {
207 379 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
208 380 }
209 381 }
382
383 #[cfg(test)]
384 mod portal_mode_tests {
385 use super::{ShareKind, SharePicker, ShareSource, share_picker_for, share_sources_for_menu};
386
387 #[test]
388 fn portal_mode_follows_wayland_display_and_skips_the_menu_list() {
389 assert_eq!(share_picker_for(None), SharePicker::List);
390 assert_eq!(share_picker_for(Some("")), SharePicker::List);
391 assert_eq!(share_picker_for(Some("wayland-1")), SharePicker::Portal);
392 let sources = vec![ShareSource {
393 id: 1,
394 kind: ShareKind::Screen,
395 title: "Desk".into(),
396 }];
397 assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty());
398 assert_eq!(
399 share_sources_for_menu(SharePicker::List, sources.clone()),
400 sources
401 );
402 }
403 }
404
405 #[cfg(test)]
406 mod portal_share_tests {
407 use libwebrtc::desktop_capturer::PortalPickerEvent;
408
409 use super::{
410 PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up,
411 };
412
413 #[test]
414 fn portal_share_cancel_is_quiet_and_failure_is_a_notice() {
415 let source = ShareSource {
416 id: 7,
417 kind: ShareKind::Screen,
418 title: "Desk".into(),
419 };
420 assert!(matches!(
421 portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())),
422 PortalFollowUp::Share(chosen) if chosen == source
423 ));
424 assert!(matches!(
425 portal_follow_up(PortalPickerEvent::Selected, None),
426 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
427 ));
428 assert!(matches!(
429 portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())),
430 PortalFollowUp::Quiet
431 ));
432 assert!(matches!(
433 portal_follow_up(PortalPickerEvent::Failed, Some(source)),
434 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
435 ));
436 }
437 }
438
439 #[cfg(all(test, target_os = "linux"))]
440 mod portal_loop_tests {
441 #[test]
442 fn portal_loop_stays_up_across_ensures() {
443 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
444 let id = libwebrtc::desktop_capturer::shared_glib_loop_id();
445 assert_ne!(id, 0);
446 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
447 assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id());
448 }
449 }
450
451 #[cfg(all(test, target_os = "linux"))]
452 mod portal_smoke {
453 use std::sync::Arc;
454 use std::sync::atomic::{AtomicU32, Ordering};
455 use std::time::Duration;
456
457 use super::{PortalFollowUp, ShareKind, start_portal_capture};
458
459 #[test]
460 fn portal_smoke_captures_after_the_dialog() {
461 if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") {
462 return;
463 }
464 let frames = Arc::new(AtomicU32::new(0));
465 let counter = frames.clone();
466 let (sender, receiver) = std::sync::mpsc::channel();
467 let capture = start_portal_capture(
468 ShareKind::Screen,
469 Arc::new(AtomicU32::new(5)),
470 move |_| {
471 counter.fetch_add(1, Ordering::Relaxed);
472 },
473 move |follow| {
474 eprintln!("PORTAL_FOLLOW={follow:?}");
475 let _ = sender.send(follow);
476 },
477 )
478 .expect("portal thread");
479 let follow = receiver
480 .recv_timeout(Duration::from_secs(40))
481 .expect("no portal result in 40s");
482 std::thread::sleep(Duration::from_millis(700));
483 let count = frames.load(Ordering::Relaxed);
484 eprintln!("PORTAL_FRAMES={count}");
485 drop(capture);
486 match follow {
487 PortalFollowUp::Share(_) => {
488 assert!(count > 0, "the dialog confirmed, but no frame arrived")
489 }
490 PortalFollowUp::Quiet => panic!("the dialog was cancelled"),
491 PortalFollowUp::Notice(text) => panic!("portal notice: {text}"),
492 }
493 }
494 }
@@ -1,15 +1,17 @@
1use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
1use std::sync::{Arc, Mutex};
2use std::sync::{Arc, Mutex};
2use std::sync::atomic::{AtomicU32, Ordering};
3use std::time::Duration;
3use std::time::Duration;
4
4
5use libwebrtc::desktop_capturer::{CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions};
5use libwebrtc::desktop_capturer::{
6 CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7 PortalPickerEvent,
8};
6use libwebrtc::native::yuv_helper::argb_to_i420;
9use libwebrtc::native::yuv_helper::argb_to_i420;
7use libwebrtc::video_frame::I420Buffer;
10use libwebrtc::video_frame::I420Buffer;
8
11
9use crate::capture::Capture;
12use crate::capture::Capture;
10use crate::video_frame::VideoPicture;
11use crate::error::{Error, Result};
13use crate::error::{Error, Result};
12
14use crate::video_frame::VideoPicture;
13
15
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ShareKind {
17pub enum ShareKind {
@@ -50,7 +52,9 @@ fn capturer(kind: ShareKind) -> Option<DesktopCapturer> {
50}
52}
51
53
52fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
54fn sources_of(kind: ShareKind) -> Vec<(ShareSource, CaptureSource)> {
53 let Some(capturer) = capturer(kind) else { return Vec::new() };
55 let Some(capturer) = capturer(kind) else {
56 return Vec::new();
57 };
54 capturer
58 capturer
55 .get_source_list()
59 .get_source_list()
56 .into_iter()
60 .into_iter()
@@ -77,22 +81,34 @@ pub fn list_share_sources() -> Vec<ShareSource> {
77const THUMBNAIL_ATTEMPTS: u32 = 5;
81const THUMBNAIL_ATTEMPTS: u32 = 5;
78const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
82const THUMBNAIL_RETRY: Duration = Duration::from_millis(40);
79
83
80pub fn share_thumbnail(wanted: &ShareSource, max_width: u32, max_height: u32) -> Option<VideoPicture> {
84pub fn share_thumbnail(
81 let source = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw)?;
85 wanted: &ShareSource,
86 max_width: u32,
87 max_height: u32,
88) -> Option<VideoPicture> {
89 let source = sources_of(wanted.kind)
90 .into_iter()
91 .find(|(source, _)| source.id == wanted.id)
92 .map(|(_, raw)| raw)?;
82 let mut capturer = capturer(wanted.kind)?;
93 let mut capturer = capturer(wanted.kind)?;
83 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
94 let captured: Arc<Mutex<Option<VideoPicture>>> = Arc::default();
84 let sink = captured.clone();
95 let sink = captured.clone();
85 capturer.start_capture(Some(source), move |result| {
96 capturer.start_capture(Some(source), move |result| {
86 let Ok(frame) = result else { return };
97 let Ok(frame) = result else { return };
87 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
98 let (width, height) = (frame.width().max(0) as u32, frame.height().max(0) as u32);
88 if let Some(picture) = scaled_bgra(frame.data(), width, height, frame.stride(), max_width, max_height)
99 if let Some(picture) = scaled_bgra(
89 && let Ok(mut slot) = sink.lock()
100 frame.data(),
101 width,
102 height,
103 frame.stride(),
104 max_width,
105 max_height,
106 ) && let Ok(mut slot) = sink.lock()
90 {
107 {
91 *slot = Some(picture);
108 *slot = Some(picture);
92 }
109 }
93 });
110 });
94 for _ in 0..THUMBNAIL_ATTEMPTS {
111 for _ in 0..THUMBNAIL_ATTEMPTS {
95 pump_messages();
96 capturer.capture_frame();
112 capturer.capture_frame();
97 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
113 if let Some(picture) = captured.lock().ok().and_then(|mut slot| slot.take()) {
98 return Some(picture);
114 return Some(picture);
@@ -102,28 +118,28 @@ pub fn share_thumbnail(wanted: &ShareSource, max_width: u32, max_height: u32) ->
102 None
118 None
103}
119}
104
120
105// Windows Graphics Capture hands frames to a DispatcherQueue on this thread; without a pump none arrive.
121fn scaled_bgra(
106#[cfg(windows)]
122 bytes: &[u8],
107fn pump_messages() {
123 width: u32,
108 use windows::Win32::UI::WindowsAndMessaging::{DispatchMessageW, MSG, PM_REMOVE, PeekMessageW, TranslateMessage};
124 height: u32,
109 let mut message = MSG::default();
125 stride: u32,
110 unsafe {
126 max_width: u32,
111 while PeekMessageW(&mut message, None, 0, 0, PM_REMOVE).as_bool() {
127 max_height: u32,
112 let _ = TranslateMessage(&message);
128) -> Option<VideoPicture> {
113 let _ = DispatchMessageW(&message);
129 if width == 0
114 }
130 || height == 0
115 }
131 || (stride as usize) < width as usize * 4
116}
132 || bytes.len() < stride as usize * height as usize
117
133 {
118#[cfg(not(windows))]
119fn pump_messages() {}
120
121fn scaled_bgra(bytes: &[u8], width: u32, height: u32, stride: u32, max_width: u32, max_height: u32) -> Option<VideoPicture> {
122 if width == 0 || height == 0 || (stride as usize) < width as usize * 4 || bytes.len() < stride as usize * height as usize {
123 return None;
134 return None;
124 }
135 }
125 let scale = (max_width as f32 / width as f32).min(max_height as f32 / height as f32).min(1.);
136 let scale = (max_width as f32 / width as f32)
126 let (target_width, target_height) = (((width as f32 * scale) as u32).max(1), ((height as f32 * scale) as u32).max(1));
137 .min(max_height as f32 / height as f32)
138 .min(1.);
139 let (target_width, target_height) = (
140 ((width as f32 * scale) as u32).max(1),
141 ((height as f32 * scale) as u32).max(1),
142 );
127 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
143 let mut bgra = Vec::with_capacity(target_width as usize * target_height as usize * 4);
128 for row in 0..target_height {
144 for row in 0..target_height {
129 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
145 let source_row = (row as u64 * height as u64 / target_height as u64) as usize;
@@ -133,14 +149,29 @@ fn scaled_bgra(bytes: &[u8], width: u32, height: u32, stride: u32, max_width: u3
133 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
149 bgra.extend_from_slice(&[bytes[offset], bytes[offset + 1], bytes[offset + 2], u8::MAX]);
134 }
150 }
135 }
151 }
136 Some(VideoPicture { width: target_width, height: target_height, bgra })
152 Some(VideoPicture {
153 width: target_width,
154 height: target_height,
155 bgra,
156 })
137}
157}
138
158
139fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
159fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
140 let mut buffer = I420Buffer::new(width, height);
160 let mut buffer = I420Buffer::new(width, height);
141 let (stride_y, stride_u, stride_v) = buffer.strides();
161 let (stride_y, stride_u, stride_v) = buffer.strides();
142 let (plane_y, plane_u, plane_v) = buffer.data_mut();
162 let (plane_y, plane_u, plane_v) = buffer.data_mut();
143 argb_to_i420(bytes, stride, plane_y, stride_y, plane_u, stride_u, plane_v, stride_v, width as i32, height as i32);
163 argb_to_i420(
164 bytes,
165 stride,
166 plane_y,
167 stride_y,
168 plane_u,
169 stride_u,
170 plane_v,
171 stride_v,
172 width as i32,
173 height as i32,
174 );
144 buffer
175 buffer
145}
176}
146
177
@@ -150,8 +181,19 @@ pub fn start_screen_capture(
150 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
181 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
151 failed: impl FnOnce(String) + Send + 'static,
182 failed: impl FnOnce(String) + Send + 'static,
152) -> Result<Capture> {
183) -> Result<Capture> {
184 if current_share_picker() == SharePicker::Portal {
185 return start_portal_capture(wanted.kind, fps, deliver, move |follow| {
186 if let PortalFollowUp::Notice(text) = follow {
187 failed(text.to_owned());
188 }
189 });
190 }
153 Capture::spawn_thread("screen-capture", move |stop| {
191 Capture::spawn_thread("screen-capture", move |stop| {
154 let Some(source) = sources_of(wanted.kind).into_iter().find(|(source, _)| source.id == wanted.id).map(|(_, raw)| raw) else {
192 let Some(source) = sources_of(wanted.kind)
193 .into_iter()
194 .find(|(source, _)| source.id == wanted.id)
195 .map(|(_, raw)| raw)
196 else {
155 return failed("the shared source is gone".to_owned());
197 return failed("the shared source is gone".to_owned());
156 };
198 };
157 let Some(mut capturer) = capturer(wanted.kind) else {
199 let Some(mut capturer) = capturer(wanted.kind) else {
@@ -165,7 +207,6 @@ pub fn start_screen_capture(
165 }
207 }
166 });
208 });
167 while !stop.load(Ordering::SeqCst) {
209 while !stop.load(Ordering::SeqCst) {
168 pump_messages();
169 capturer.capture_frame();
210 capturer.capture_frame();
170 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
211 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
171 }
212 }
@@ -173,15 +214,146 @@ pub fn start_screen_capture(
173 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
214 .map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
174}
215}
175
216
217/// Where the share menu gets its sources. Wayland uses the desktop dialog.
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum SharePicker {
220 List,
221 Portal,
222}
223
224pub fn share_picker_for(wayland_display: Option<&str>) -> SharePicker {
225 match wayland_display {
226 Some(value) if !value.is_empty() => SharePicker::Portal,
227 _ => SharePicker::List,
228 }
229}
230
231pub fn current_share_picker() -> SharePicker {
232 share_picker_for(std::env::var("WAYLAND_DISPLAY").ok().as_deref())
233}
234
235/// Portal menus must not enumerate or thumbnail sources. That would open the dialog early.
236pub fn share_sources_for_menu(picker: SharePicker, sources: Vec<ShareSource>) -> Vec<ShareSource> {
237 match picker {
238 SharePicker::Portal => Vec::new(),
239 SharePicker::List => sources,
240 }
241}
242
243pub use crate::notices::PORTAL_UNAVAILABLE_NOTICE;
244
245#[derive(Debug, Clone, PartialEq, Eq)]
246pub enum PortalFollowUp {
247 Share(ShareSource),
248 Quiet,
249 Notice(&'static str),
250}
251
252pub fn portal_follow_up(event: PortalPickerEvent, source: Option<ShareSource>) -> PortalFollowUp {
253 match event {
254 PortalPickerEvent::Selected => match source {
255 Some(source) => PortalFollowUp::Share(source),
256 None => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
257 },
258 PortalPickerEvent::Cancelled => PortalFollowUp::Quiet,
259 PortalPickerEvent::Failed => PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE),
260 }
261}
262
263pub(crate) fn start_portal_capture(
264 kind: ShareKind,
265 fps: Arc<AtomicU32>,
266 mut deliver: impl FnMut(I420Buffer) + Send + 'static,
267 outcome: impl FnOnce(PortalFollowUp) + Send + 'static,
268) -> Result<Capture> {
269 Capture::spawn_thread("portal-share", move |stop| {
270 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
271 let Some(mut capturer) = capturer(kind) else {
272 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
273 return;
274 };
275 let selected = Arc::new(AtomicBool::new(false));
276 let gate = selected.clone();
277 capturer.start_capture(None, move |result| {
278 if !gate.load(Ordering::SeqCst) {
279 return;
280 }
281 let Ok(frame) = result else { return };
282 let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
283 if width >= 2 && height >= 2 {
284 deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
285 }
286 });
287 if !capturer.has_delegated_picker() {
288 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
289 return;
290 }
291 let (sender, receiver) = std::sync::mpsc::channel();
292 capturer.watch_picker(move |event| {
293 let _ = sender.send(event);
294 });
295 capturer.ensure_picker_visible();
296 let event = loop {
297 if stop.load(Ordering::SeqCst) {
298 return;
299 }
300 match receiver.recv_timeout(Duration::from_millis(40)) {
301 Ok(event) => break event,
302 Err(std::sync::mpsc::RecvTimeoutError::Timeout) => continue,
303 Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => {
304 outcome(PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE));
305 return;
306 }
307 }
308 };
309 if stop.load(Ordering::SeqCst) {
310 return;
311 }
312 // The portal already bound this stream. Looking the source up again, or
313 // selecting that id, is what used to tear the stream down and report
314 // "the shared source is gone".
315 let source = if event == PortalPickerEvent::Selected {
316 selected.store(true, Ordering::SeqCst);
317 Some(ShareSource {
318 id: 0,
319 kind,
320 title: String::new(),
321 })
322 } else {
323 None
324 };
325 let follow = portal_follow_up(event, source);
326 if !matches!(follow, PortalFollowUp::Share(_)) {
327 outcome(follow);
328 return;
329 }
330 capturer.capture_frame();
331 outcome(follow);
332 while !stop.load(Ordering::SeqCst) {
333 capturer.capture_frame();
334 std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
335 }
336 })
337 .map_err(|error| Error::Webrtc(format!("portal thread: {error}")))
338}
339
176#[cfg(test)]
340#[cfg(test)]
177mod tests {
341mod tests {
178 use super::*;
342 use super::*;
179
343
180 #[test]
344 #[test]
181 fn sources_get_readable_labels() {
345 fn sources_get_readable_labels() {
182 let screen = ShareSource { id: 1, kind: ShareKind::Screen, title: String::new() };
346 let screen = ShareSource {
347 id: 1,
348 kind: ShareKind::Screen,
349 title: String::new(),
350 };
183 assert_eq!(screen.label(), "Entire screen");
351 assert_eq!(screen.label(), "Entire screen");
184 let window = ShareSource { id: 2, kind: ShareKind::Window, title: " Notes ".into() };
352 let window = ShareSource {
353 id: 2,
354 kind: ShareKind::Window,
355 title: " Notes ".into(),
356 };
185 assert_eq!(window.label(), "Notes");
357 assert_eq!(window.label(), "Notes");
186 }
358 }
187}
359}
@@ -207,3 +379,116 @@ mod thumbnail_tests {
207 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
379 assert!(scaled_bgra(&bytes, width, height, 8, 4, 4).is_none());
208 }
380 }
209}
381}
382
383#[cfg(test)]
384mod portal_mode_tests {
385 use super::{ShareKind, SharePicker, ShareSource, share_picker_for, share_sources_for_menu};
386
387 #[test]
388 fn portal_mode_follows_wayland_display_and_skips_the_menu_list() {
389 assert_eq!(share_picker_for(None), SharePicker::List);
390 assert_eq!(share_picker_for(Some("")), SharePicker::List);
391 assert_eq!(share_picker_for(Some("wayland-1")), SharePicker::Portal);
392 let sources = vec![ShareSource {
393 id: 1,
394 kind: ShareKind::Screen,
395 title: "Desk".into(),
396 }];
397 assert!(share_sources_for_menu(SharePicker::Portal, sources.clone()).is_empty());
398 assert_eq!(
399 share_sources_for_menu(SharePicker::List, sources.clone()),
400 sources
401 );
402 }
403}
404
405#[cfg(test)]
406mod portal_share_tests {
407 use libwebrtc::desktop_capturer::PortalPickerEvent;
408
409 use super::{
410 PORTAL_UNAVAILABLE_NOTICE, PortalFollowUp, ShareKind, ShareSource, portal_follow_up,
411 };
412
413 #[test]
414 fn portal_share_cancel_is_quiet_and_failure_is_a_notice() {
415 let source = ShareSource {
416 id: 7,
417 kind: ShareKind::Screen,
418 title: "Desk".into(),
419 };
420 assert!(matches!(
421 portal_follow_up(PortalPickerEvent::Selected, Some(source.clone())),
422 PortalFollowUp::Share(chosen) if chosen == source
423 ));
424 assert!(matches!(
425 portal_follow_up(PortalPickerEvent::Selected, None),
426 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
427 ));
428 assert!(matches!(
429 portal_follow_up(PortalPickerEvent::Cancelled, Some(source.clone())),
430 PortalFollowUp::Quiet
431 ));
432 assert!(matches!(
433 portal_follow_up(PortalPickerEvent::Failed, Some(source)),
434 PortalFollowUp::Notice(PORTAL_UNAVAILABLE_NOTICE)
435 ));
436 }
437}
438
439#[cfg(all(test, target_os = "linux"))]
440mod portal_loop_tests {
441 #[test]
442 fn portal_loop_stays_up_across_ensures() {
443 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
444 let id = libwebrtc::desktop_capturer::shared_glib_loop_id();
445 assert_ne!(id, 0);
446 libwebrtc::desktop_capturer::ensure_shared_glib_loop();
447 assert_eq!(id, libwebrtc::desktop_capturer::shared_glib_loop_id());
448 }
449}
450
451#[cfg(all(test, target_os = "linux"))]
452mod portal_smoke {
453 use std::sync::Arc;
454 use std::sync::atomic::{AtomicU32, Ordering};
455 use std::time::Duration;
456
457 use super::{PortalFollowUp, ShareKind, start_portal_capture};
458
459 #[test]
460 fn portal_smoke_captures_after_the_dialog() {
461 if std::env::var("PORTAL_SMOKE").ok().as_deref() != Some("1") {
462 return;
463 }
464 let frames = Arc::new(AtomicU32::new(0));
465 let counter = frames.clone();
466 let (sender, receiver) = std::sync::mpsc::channel();
467 let capture = start_portal_capture(
468 ShareKind::Screen,
469 Arc::new(AtomicU32::new(5)),
470 move |_| {
471 counter.fetch_add(1, Ordering::Relaxed);
472 },
473 move |follow| {
474 eprintln!("PORTAL_FOLLOW={follow:?}");
475 let _ = sender.send(follow);
476 },
477 )
478 .expect("portal thread");
479 let follow = receiver
480 .recv_timeout(Duration::from_secs(40))
481 .expect("no portal result in 40s");
482 std::thread::sleep(Duration::from_millis(700));
483 let count = frames.load(Ordering::Relaxed);
484 eprintln!("PORTAL_FRAMES={count}");
485 drop(capture);
486 match follow {
487 PortalFollowUp::Share(_) => {
488 assert!(count > 0, "the dialog confirmed, but no frame arrived")
489 }
490 PortalFollowUp::Quiet => panic!("the dialog was cancelled"),
491 PortalFollowUp::Notice(text) => panic!("portal notice: {text}"),
492 }
493 }
494}
crates/calling/src/video_send.rs +353 −58
@@ -4,10 +4,10 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
4 4
5 5 use libwebrtc::media_stream_track::MediaStreamTrack;
6 6 use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
7 8 use libwebrtc::rtp_parameters::DegradationPreference;
8 9 use libwebrtc::rtp_sender::RtpSender;
9 10 use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
10 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
11 11 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
12 12 use libwebrtc::video_source::VideoResolution;
13 13 use libwebrtc::video_source::native::NativeVideoSource;
@@ -16,16 +16,25 @@ use tokio::sync::mpsc::UnboundedSender;
16 16
17 17 use crate::background::BackgroundPicture;
18 18 use crate::blur::BlurSettings;
19 use crate::effects::CameraEffects;
20 use crate::camera::start_camera;
19 use crate::camera::{CameraCaptureStats, start_camera};
20 use crate::video_quality::VideoQuality;
21 21 use crate::capture::Capture;
22 use crate::control::CallUpdate;
22 use crate::control::{CallCommand, CallUpdate};
23 use crate::notices::{CAMERA_STOPPED_NOTICE, SCREEN_SHARE_STOPPED_NOTICE, notice_with_detail};
23 24 use crate::devices::DeviceChoice;
25 use crate::effects::CameraEffects;
24 26 use crate::error::{Error, Result};
25 use crate::screen::{ShareSource, start_screen_capture};
26 use crate::send_control::{EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers};
27 use crate::timeline::Timeline;
28 use crate::screen::{
29 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
30 };
31 use crate::send_control::{
32 EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers,
33 };
27 34 use crate::standout::StandoutOverlay;
28 use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
35 use crate::video_frame::{
36 FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420,
37 };
29 38 use crate::video_layout::VideoLines;
30 39 use crate::video_pattern::{PatternKind, spawn_pattern};
31 40
@@ -69,10 +78,20 @@ pub struct LocalSink {
69 78 impl LocalSink {
70 79 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
71 80 let self_view = hub.map(|(hub, key)| {
72 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
81 let fps = if matches!(key, VideoKey::LocalScreen) {
82 SCREEN_FPS
83 } else {
84 PERSON_FPS
85 };
73 86 (hub, key, FrameGate::new(fps))
74 87 });
75 LocalSink { source, self_view, mirror: None, standout: None, frame_size: None }
88 LocalSink {
89 source,
90 self_view,
91 mirror: None,
92 standout: None,
93 frame_size: None,
94 }
76 95 }
77 96
78 97 pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
@@ -96,16 +115,27 @@ impl LocalSink {
96 115 None => buffer,
97 116 };
98 117 if let Some(frame_size) = &self.frame_size {
99 frame_size.store(pack_size(buffer.width(), buffer.height()), Ordering::Relaxed);
118 frame_size.store(
119 pack_size(buffer.width(), buffer.height()),
120 Ordering::Relaxed,
121 );
100 122 }
101 123 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
102 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
124 frame.timestamp_us = SystemTime::now()
125 .duration_since(UNIX_EPOCH)
126 .map_or(0, |elapsed| elapsed.as_micros() as i64);
103 127 self.source.capture_frame(&frame);
104 let Some((hub, key, gate)) = &mut self.self_view else { return };
128 let Some((hub, key, gate)) = &mut self.self_view else {
129 return;
130 };
105 131 if gate.admit(Instant::now())
106 132 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
107 133 {
108 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
134 if self
135 .mirror
136 .as_ref()
137 .is_some_and(|settings| settings.effects().mirror)
138 {
109 139 picture.flip_horizontally();
110 140 }
111 141 hub.publish(key.clone(), picture);
@@ -142,11 +172,22 @@ struct RequestedLimits {
142 172 }
143 173
144 174 impl Outgoing {
145 fn new(factory: &PeerConnectionFactory, label: &str, kind: PatternKind, screencast: bool) -> Self {
175 fn new(
176 factory: &PeerConnectionFactory,
177 label: &str,
178 kind: PatternKind,
179 screencast: bool,
180 ) -> Self {
146 181 let (width, height) = kind.size();
147 182 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
148 183 let track = factory.create_video_track(label, source.clone());
149 Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), requested: None }
184 Outgoing {
185 source,
186 track,
187 capture: None,
188 frame_size: Arc::new(AtomicU64::new(0)),
189 requested: None,
190 }
150 191 }
151 192 }
152 193
@@ -162,10 +203,24 @@ pub struct LocalVideo {
162 203 motion: bool,
163 204 share_fps: Arc<AtomicU32>,
164 205 camera_preview: bool,
206 quality: VideoQuality,
207 camera_stats: Arc<CameraCaptureStats>,
208 timeline: Option<Timeline>,
209 portal_generation: u64,
210 portal_armed: bool,
211 portal_keep: bool,
212 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
213 /// commands must attach that capturer, not replace it.
214 portal_bound: bool,
165 215 }
166 216
167 217 impl LocalVideo {
168 pub fn new(factory: &PeerConnectionFactory, mode: VideoMode, hub: Arc<VideoHub>, updates: UnboundedSender<CallUpdate>) -> Self {
218 pub fn new(
219 factory: &PeerConnectionFactory,
220 mode: VideoMode,
221 hub: Arc<VideoHub>,
222 updates: UnboundedSender<CallUpdate>,
223 ) -> Self {
169 224 LocalVideo {
170 225 mode,
171 226 hub,
@@ -177,13 +232,44 @@ impl LocalVideo {
177 232 motion: false,
178 233 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
179 234 camera_preview: false,
235 quality: VideoQuality::default(),
236 camera_stats: CameraCaptureStats::new(),
237 timeline: None,
238 portal_generation: 0,
239 portal_armed: false,
240 portal_keep: false,
241 portal_bound: false,
180 242 }
181 243 }
182 244
245 pub fn attach_timeline(&mut self, timeline: Timeline) {
246 self.timeline = Some(timeline);
247 }
248
249 pub fn video_quality(&self) -> VideoQuality {
250 self.quality
251 }
252
253 pub fn set_video_quality(&mut self, quality: VideoQuality) {
254 self.quality = quality;
255 }
256
183 257 pub fn set_motion(&mut self, motion: bool) {
184 258 self.motion = motion;
185 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
186 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
259 self.share_fps.store(
260 if motion {
261 MOTION_SHARE_FPS
262 } else {
263 SCREEN_SHARE_FPS
264 },
265 Ordering::Relaxed,
266 );
267 if let Some(share) = self
268 .lines
269 .as_ref()
270 .and_then(|lines| lines.share.as_ref())
271 .filter(|_| self.sharing())
272 {
187 273 let _ = self.tune_share(&share.sender());
188 274 }
189 275 }
@@ -203,7 +289,9 @@ impl LocalVideo {
203 289 for encoding in &mut parameters.encodings {
204 290 encoding.max_framerate = Some(fps);
205 291 }
206 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
292 sender
293 .set_parameters(parameters)
294 .map_err(|error| Error::Webrtc(error.to_string()))
207 295 }
208 296
209 297 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
@@ -214,19 +302,33 @@ impl LocalVideo {
214 302 }
215 303 }
216 304
217 pub fn apply_send_limit(&mut self, source: SendSource, limits: &[SendLimit]) -> Result<Option<Vec<LayerPlan>>> {
305 pub fn apply_send_limit(
306 &mut self,
307 source: SendSource,
308 limits: &[SendLimit],
309 ) -> Result<Option<Vec<LayerPlan>>> {
218 310 let sending = match source {
219 311 SendSource::Camera => self.camera_on(),
220 312 SendSource::Screen => self.sharing(),
221 313 };
222 let Some(sender) = self.sender_of(source).filter(|_| sending) else { return Ok(None) };
314 let Some(sender) = self.sender_of(source).filter(|_| sending) else {
315 return Ok(None);
316 };
223 317 let outgoing = match source {
224 318 SendSource::Camera => &mut self.camera,
225 319 SendSource::Screen => &mut self.screen,
226 320 };
227 321 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
228 outgoing.requested = Some(RequestedLimits { limits: limits.to_vec(), applied_for: frame });
229 let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();
322 outgoing.requested = Some(RequestedLimits {
323 limits: limits.to_vec(),
324 applied_for: frame,
325 });
326 let rids: Vec<String> = sender
327 .parameters()
328 .encodings
329 .into_iter()
330 .map(|encoding| encoding.rid)
331 .collect();
230 332 if rids.len() > 1 {
231 333 let plans = plan_layers(limits, frame, &rids);
232 334 if plans.iter().any(|plan| plan.keyframe) {
@@ -235,13 +337,20 @@ impl LocalVideo {
235 337 Self::set_layers(&sender, &plans, 1.0)?;
236 338 return Ok(Some(plans));
237 339 }
238 let Some(limit) = limits.first() else { return Ok(None) };
340 let Some(limit) = limits.first() else {
341 return Ok(None);
342 };
239 343 let encoder = encoder_limits(limit, frame);
240 344 if limit.keyframe {
241 345 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
242 346 }
243 347 Self::set_limits(&sender, &encoder, 1.0)?;
244 Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))
348 Ok(Some(vec![LayerPlan {
349 rid: rids.into_iter().next().unwrap_or_default(),
350 active: true,
351 limits: Some(encoder),
352 keyframe: limit.keyframe,
353 }]))
245 354 }
246 355
247 356 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
@@ -253,7 +362,11 @@ impl LocalVideo {
253 362 SendSource::Screen => &self.screen,
254 363 };
255 364 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
256 let Some(requested) = outgoing.requested.as_ref().filter(|requested| frame.is_some() && requested.applied_for != frame) else {
365 let Some(requested) = outgoing
366 .requested
367 .as_ref()
368 .filter(|requested| frame.is_some() && requested.applied_for != frame)
369 else {
257 370 continue;
258 371 };
259 372 let limits = requested.limits.clone();
@@ -265,17 +378,22 @@ impl LocalVideo {
265 378 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
266 379 let mut parameters = sender.parameters();
267 380 for encoding in &mut parameters.encodings {
268 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else { continue };
381 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else {
382 continue;
383 };
269 384 let nudged = nudge != 1.0 && plan.keyframe;
270 385 encoding.active = plan.active;
271 386 let Some(limits) = &plan.limits else { continue };
272 encoding.scale_resolution_down_by = Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
387 encoding.scale_resolution_down_by =
388 Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
273 389 if let Some(framerate) = limits.max_framerate {
274 390 encoding.max_framerate = Some(framerate);
275 391 }
276 392 encoding.max_bitrate = limits.max_bitrate;
277 393 }
278 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
394 sender
395 .set_parameters(parameters)
396 .map_err(|error| Error::Webrtc(error.to_string()))
279 397 }
280 398
281 399 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
@@ -287,7 +405,9 @@ impl LocalVideo {
287 405 }
288 406 encoding.max_bitrate = limits.max_bitrate;
289 407 }
290 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
408 sender
409 .set_parameters(parameters)
410 .map_err(|error| Error::Webrtc(error.to_string()))
291 411 }
292 412
293 413 pub fn camera_size(&self) -> Option<(u32, u32)> {
@@ -312,7 +432,9 @@ impl LocalVideo {
312 432 }
313 433
314 434 pub fn blur_model(&self) -> Option<&'static str> {
315 (self.camera_on() && self.blur.active()).then(|| self.blur.model()).filter(|model| !model.is_empty())
435 (self.camera_on() && self.blur.active())
436 .then(|| self.blur.model())
437 .filter(|model| !model.is_empty())
316 438 }
317 439
318 440 pub fn has_lines(&self) -> bool {
@@ -320,17 +442,31 @@ impl LocalVideo {
320 442 }
321 443
322 444 pub fn share_mid(&self) -> Option<String> {
323 self.lines.as_ref().and_then(|lines| lines.share.as_ref()).and_then(|share| share.mid())
445 self.lines
446 .as_ref()
447 .and_then(|lines| lines.share.as_ref())
448 .and_then(|share| share.mid())
324 449 }
325 450
326 451 pub fn has_share_line(&self) -> bool {
327 self.lines.as_ref().is_some_and(|lines| lines.share.is_some())
452 self.lines
453 .as_ref()
454 .is_some_and(|lines| lines.share.is_some())
328 455 }
329 456
330 pub fn add_share_line(&mut self, share: RtpTransceiver, camera: Option<RtpTransceiver>) -> Result<()> {
457 pub fn add_share_line(
458 &mut self,
459 share: RtpTransceiver,
460 camera: Option<RtpTransceiver>,
461 ) -> Result<()> {
331 462 match (self.lines.as_mut(), camera) {
332 463 (Some(lines), _) => lines.share = Some(share),
333 (None, Some(camera)) => self.lines = Some(VideoLines { camera, share: Some(share) }),
464 (None, Some(camera)) => {
465 self.lines = Some(VideoLines {
466 camera,
467 share: Some(share),
468 })
469 }
334 470 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
335 471 }
336 472 Ok(())
@@ -341,7 +477,12 @@ impl LocalVideo {
341 477 .as_ref()
342 478 .and_then(|lines| lines.share.as_ref())
343 479 .and_then(|share| share.current_direction())
344 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
480 .is_some_and(|direction| {
481 matches!(
482 direction,
483 RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv
484 )
485 })
345 486 }
346 487
347 488 pub fn is_available(&self) -> bool {
@@ -360,6 +501,10 @@ impl LocalVideo {
360 501 self.screen.capture.is_some()
361 502 }
362 503
504 pub fn portal_is_open(&self) -> bool {
505 self.portal_armed
506 }
507
363 508 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
364 509 if self.camera_on() {
365 510 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
@@ -385,19 +530,34 @@ impl LocalVideo {
385 530 for encoding in &mut parameters.encodings {
386 531 encoding.active = active;
387 532 }
388 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
533 sender
534 .set_parameters(parameters)
535 .map_err(|error| Error::Webrtc(error.to_string()))
389 536 }
390 537
391 538 fn camera_sink(&self) -> LocalSink {
392 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
393 .mirrored_by(self.blur.clone())
394 .reporting_size(self.camera.frame_size.clone())
539 LocalSink::new(
540 self.camera.source.clone(),
541 Some((self.hub.clone(), VideoKey::LocalCamera)),
542 )
543 .mirrored_by(self.blur.clone())
544 .reporting_size(self.camera.frame_size.clone())
545 }
546
547 /// Local share frames go to the encoder and to the window in the chat.
548 fn screen_sink(&self) -> LocalSink {
549 LocalSink::new(
550 self.screen.source.clone(),
551 Some((self.hub.clone(), VideoKey::LocalScreen)),
552 )
553 .with_standout(self.blur.clone())
554 .reporting_size(self.screen.frame_size.clone())
395 555 }
396 556
397 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
557 fn report_failure(&self, notice_key: &'static str) -> impl FnOnce(String) + Send + 'static {
398 558 let updates = self.updates.clone();
399 559 move |reason| {
400 let _ = updates.send(CallUpdate::Notice(format!("{what} stopped: {reason}")));
560 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
401 561 }
402 562 }
403 563
@@ -412,7 +572,10 @@ impl LocalVideo {
412 572 }
413 573
414 574 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
415 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
575 let lines = self
576 .lines
577 .as_ref()
578 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
416 579 if !self.is_available() {
417 580 return Err(Error::Webrtc("video is switched off".into()));
418 581 }
@@ -426,14 +589,56 @@ impl LocalVideo {
426 589 Ok(())
427 590 }
428 591
592 pub fn camera_capture_summary(&self) -> Option<String> {
593 self.camera_stats.summary()
594 }
595
429 596 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
430 597 let mut sink = self.camera_sink();
431 598 Ok(match self.mode {
432 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(self.blur.clone()))),
433 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
599 VideoMode::Pattern => Capture::Task(spawn_pattern(
600 sink,
601 PatternKind::Camera,
602 Some(self.blur.clone()),
603 )),
604 _ => {
605 let timeline = self.timeline.clone();
606 start_camera(
607 choice,
608 self.quality,
609 self.blur.clone(),
610 self.camera_stats.clone(),
611 move |label| {
612 if let Some(timeline) = timeline {
613 timeline.record("camera capture", label);
614 } else {
615 eprintln!("calls: camera capture {label}");
616 }
617 },
618 move |buffer| sink.push(buffer),
619 self.report_failure(CAMERA_STOPPED_NOTICE),
620 )?
621 }
434 622 })
435 623 }
436 624
625 /// Restart capture with the current quality if the camera is already running.
626 pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> {
627 if self.camera.capture.is_none() {
628 return Ok(());
629 }
630 let preview = self.camera_preview;
631 self.camera.capture = None;
632 self.camera.capture = Some(self.capture_camera(choice)?);
633 self.camera_preview = preview;
634 if !preview {
635 if let Some(lines) = self.lines.as_ref() {
636 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
637 }
638 }
639 Ok(())
640 }
641
437 642 pub fn stop_camera(&mut self) {
438 643 self.camera_preview = false;
439 644 self.camera.capture = None;
@@ -444,28 +649,110 @@ impl LocalVideo {
444 649 self.hub.forget(&VideoKey::LocalCamera);
445 650 }
446 651
447 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
448 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
449 let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
652 pub fn accept_portal(&mut self, generation: u64) -> bool {
653 if self.portal_armed && self.portal_generation == generation {
654 self.portal_armed = false;
655 self.portal_keep = true;
656 self.portal_bound = true;
657 true
658 } else {
659 false
660 }
661 }
662
663 pub fn open_portal(
664 &mut self,
665 kind: ShareKind,
666 commands: UnboundedSender<CallCommand>,
667 ) -> Result<()> {
450 668 if !self.is_available() {
451 669 return Err(Error::Webrtc("video is switched off".into()));
452 670 }
671 if self.mode == VideoMode::Pattern {
672 let source = ShareSource {
673 id: if kind == ShareKind::Screen { 1 } else { 2 },
674 kind,
675 title: if kind == ShareKind::Screen {
676 "Test screen"
677 } else {
678 "Test window"
679 }
680 .into(),
681 };
682 let _ = commands.send(CallCommand::StartShare(source));
683 return Ok(());
684 }
685 self.portal_generation = self.portal_generation.wrapping_add(1);
686 let generation = self.portal_generation;
687 self.portal_armed = false;
688 self.portal_keep = false;
689 self.portal_bound = false;
453 690 self.screen.capture = None;
454 let mut sink = LocalSink::new(self.screen.source.clone(), None)
455 .with_standout(self.blur.clone())
456 .reporting_size(self.screen.frame_size.clone());
457 let capture = match self.mode {
458 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
459 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
460 };
691 let mut sink = self.screen_sink();
692 let updates = self.updates.clone();
693 let capture = start_portal_capture(
694 kind,
695 self.share_fps.clone(),
696 move |buffer| sink.push(buffer),
697 move |follow| match follow {
698 PortalFollowUp::Share(source) => {
699 let _ = commands.send(CallCommand::FinishPortalShare { source, generation });
700 }
701 PortalFollowUp::Quiet => {
702 let _ = commands.send(CallCommand::AbandonPortalShare);
703 }
704 PortalFollowUp::Notice(text) => {
705 let _ = updates.send(CallUpdate::Notice(text.to_owned()));
706 let _ = commands.send(CallCommand::AbandonPortalShare);
707 }
708 },
709 )?;
710 self.portal_armed = true;
711 self.screen.capture = Some(capture);
712 Ok(())
713 }
714
715 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
716 let lines = self
717 .lines
718 .as_ref()
719 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
720 let share = lines
721 .share
722 .as_ref()
723 .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
724 if !self.is_available() {
725 return Err(Error::Webrtc("video is switched off".into()));
726 }
727 let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound;
728 if !keep {
729 self.portal_armed = false;
730 self.portal_generation = self.portal_generation.wrapping_add(1);
731 self.screen.capture = None;
732 let mut sink = self.screen_sink();
733 let capture = match self.mode {
734 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
735 _ => start_screen_capture(
736 source.clone(),
737 self.share_fps.clone(),
738 move |buffer| sink.push(buffer),
739 self.report_failure(SCREEN_SHARE_STOPPED_NOTICE),
740 )?,
741 };
742 self.screen.capture = Some(capture);
743 }
461 744 Self::begin_sending(&share.sender(), &self.screen.track)?;
462 745 let _ = self.tune_share(&share.sender());
463 self.screen.capture = Some(capture);
464 746 Ok(())
465 747 }
466 748
467 749 pub fn stop_share(&mut self) {
750 self.portal_generation = self.portal_generation.wrapping_add(1);
751 self.portal_armed = false;
752 self.portal_keep = false;
753 self.portal_bound = false;
468 754 self.screen.capture = None;
755 self.hub.forget(&VideoKey::LocalScreen);
469 756 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
470 757 let _ = Self::set_active(&share.sender(), false);
471 758 }
@@ -485,10 +772,18 @@ mod tests {
485 772 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
486 773 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
487 774 let factory = crate::devices::shared_factory();
488 let mut video = LocalVideo::new(&factory, VideoMode::Pattern, VideoHub::new(sender.clone()), sender);
775 let mut video = LocalVideo::new(
776 &factory,
777 VideoMode::Pattern,
778 VideoHub::new(sender.clone()),
779 sender,
780 );
489 781 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
490 782 assert!(video.camera_previewing() && !video.camera_on());
491 assert!(video.start_camera(&DeviceChoice::SystemDefault).is_err(), "sending needs a negotiated line");
783 assert!(
784 video.start_camera(&DeviceChoice::SystemDefault).is_err(),
785 "sending needs a negotiated line"
786 );
492 787 assert!(video.camera_previewing());
493 788 video.stop_camera();
494 789 assert!(!video.camera_previewing() && !video.camera_on());
@@ -4,10 +4,10 @@ use std::time::{Instant, SystemTime, UNIX_EPOCH};
4
4
5use libwebrtc::media_stream_track::MediaStreamTrack;
5use libwebrtc::media_stream_track::MediaStreamTrack;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
7use libwebrtc::rtp_parameters::DegradationPreference;
8use libwebrtc::rtp_parameters::DegradationPreference;
8use libwebrtc::rtp_sender::RtpSender;
9use libwebrtc::rtp_sender::RtpSender;
9use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
10use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
10use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
11use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
11use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
12use libwebrtc::video_source::VideoResolution;
12use libwebrtc::video_source::VideoResolution;
13use libwebrtc::video_source::native::NativeVideoSource;
13use libwebrtc::video_source::native::NativeVideoSource;
@@ -16,16 +16,25 @@ use tokio::sync::mpsc::UnboundedSender;
16
16
17use crate::background::BackgroundPicture;
17use crate::background::BackgroundPicture;
18use crate::blur::BlurSettings;
18use crate::blur::BlurSettings;
19use crate::effects::CameraEffects;
19use crate::camera::{CameraCaptureStats, start_camera};
20use crate::camera::start_camera;
20use crate::video_quality::VideoQuality;
21use crate::capture::Capture;
21use crate::capture::Capture;
22use crate::control::CallUpdate;
22use crate::control::{CallCommand, CallUpdate};
23use crate::notices::{CAMERA_STOPPED_NOTICE, SCREEN_SHARE_STOPPED_NOTICE, notice_with_detail};
23use crate::devices::DeviceChoice;
24use crate::devices::DeviceChoice;
25use crate::effects::CameraEffects;
24use crate::error::{Error, Result};
26use crate::error::{Error, Result};
25use crate::screen::{ShareSource, start_screen_capture};
27use crate::timeline::Timeline;
26use crate::send_control::{EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers};
28use crate::screen::{
29 PortalFollowUp, ShareKind, ShareSource, start_portal_capture, start_screen_capture,
30};
31use crate::send_control::{
32 EncoderLimits, KEYFRAME_NUDGE, LayerPlan, SendLimit, encoder_limits, plan_layers,
33};
27use crate::standout::StandoutOverlay;
34use crate::standout::StandoutOverlay;
28use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
35use crate::video_frame::{
36 FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420,
37};
29use crate::video_layout::VideoLines;
38use crate::video_layout::VideoLines;
30use crate::video_pattern::{PatternKind, spawn_pattern};
39use crate::video_pattern::{PatternKind, spawn_pattern};
31
40
@@ -69,10 +78,20 @@ pub struct LocalSink {
69impl LocalSink {
78impl LocalSink {
70 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
79 pub fn new(source: NativeVideoSource, hub: Option<(Arc<VideoHub>, VideoKey)>) -> Self {
71 let self_view = hub.map(|(hub, key)| {
80 let self_view = hub.map(|(hub, key)| {
72 let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
81 let fps = if matches!(key, VideoKey::LocalScreen) {
82 SCREEN_FPS
83 } else {
84 PERSON_FPS
85 };
73 (hub, key, FrameGate::new(fps))
86 (hub, key, FrameGate::new(fps))
74 });
87 });
75 LocalSink { source, self_view, mirror: None, standout: None, frame_size: None }
88 LocalSink {
89 source,
90 self_view,
91 mirror: None,
92 standout: None,
93 frame_size: None,
94 }
76 }
95 }
77
96
78 pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
97 pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
@@ -96,16 +115,27 @@ impl LocalSink {
96 None => buffer,
115 None => buffer,
97 };
116 };
98 if let Some(frame_size) = &self.frame_size {
117 if let Some(frame_size) = &self.frame_size {
99 frame_size.store(pack_size(buffer.width(), buffer.height()), Ordering::Relaxed);
118 frame_size.store(
119 pack_size(buffer.width(), buffer.height()),
120 Ordering::Relaxed,
121 );
100 }
122 }
101 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
123 let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
102 frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
124 frame.timestamp_us = SystemTime::now()
125 .duration_since(UNIX_EPOCH)
126 .map_or(0, |elapsed| elapsed.as_micros() as i64);
103 self.source.capture_frame(&frame);
127 self.source.capture_frame(&frame);
104 let Some((hub, key, gate)) = &mut self.self_view else { return };
128 let Some((hub, key, gate)) = &mut self.self_view else {
129 return;
130 };
105 if gate.admit(Instant::now())
131 if gate.admit(Instant::now())
106 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
132 && let Some(mut picture) = picture_from_i420(frame.buffer, key.max_width())
107 {
133 {
108 if self.mirror.as_ref().is_some_and(|settings| settings.effects().mirror) {
134 if self
135 .mirror
136 .as_ref()
137 .is_some_and(|settings| settings.effects().mirror)
138 {
109 picture.flip_horizontally();
139 picture.flip_horizontally();
110 }
140 }
111 hub.publish(key.clone(), picture);
141 hub.publish(key.clone(), picture);
@@ -142,11 +172,22 @@ struct RequestedLimits {
142}
172}
143
173
144impl Outgoing {
174impl Outgoing {
145 fn new(factory: &PeerConnectionFactory, label: &str, kind: PatternKind, screencast: bool) -> Self {
175 fn new(
176 factory: &PeerConnectionFactory,
177 label: &str,
178 kind: PatternKind,
179 screencast: bool,
180 ) -> Self {
146 let (width, height) = kind.size();
181 let (width, height) = kind.size();
147 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
182 let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
148 let track = factory.create_video_track(label, source.clone());
183 let track = factory.create_video_track(label, source.clone());
149 Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), requested: None }
184 Outgoing {
185 source,
186 track,
187 capture: None,
188 frame_size: Arc::new(AtomicU64::new(0)),
189 requested: None,
190 }
150 }
191 }
151}
192}
152
193
@@ -162,10 +203,24 @@ pub struct LocalVideo {
162 motion: bool,
203 motion: bool,
163 share_fps: Arc<AtomicU32>,
204 share_fps: Arc<AtomicU32>,
164 camera_preview: bool,
205 camera_preview: bool,
206 quality: VideoQuality,
207 camera_stats: Arc<CameraCaptureStats>,
208 timeline: Option<Timeline>,
209 portal_generation: u64,
210 portal_armed: bool,
211 portal_keep: bool,
212 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
213 /// commands must attach that capturer, not replace it.
214 portal_bound: bool,
165}
215}
166
216
167impl LocalVideo {
217impl LocalVideo {
168 pub fn new(factory: &PeerConnectionFactory, mode: VideoMode, hub: Arc<VideoHub>, updates: UnboundedSender<CallUpdate>) -> Self {
218 pub fn new(
219 factory: &PeerConnectionFactory,
220 mode: VideoMode,
221 hub: Arc<VideoHub>,
222 updates: UnboundedSender<CallUpdate>,
223 ) -> Self {
169 LocalVideo {
224 LocalVideo {
170 mode,
225 mode,
171 hub,
226 hub,
@@ -177,13 +232,44 @@ impl LocalVideo {
177 motion: false,
232 motion: false,
178 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
233 share_fps: Arc::new(AtomicU32::new(SCREEN_SHARE_FPS)),
179 camera_preview: false,
234 camera_preview: false,
235 quality: VideoQuality::default(),
236 camera_stats: CameraCaptureStats::new(),
237 timeline: None,
238 portal_generation: 0,
239 portal_armed: false,
240 portal_keep: false,
241 portal_bound: false,
180 }
242 }
181 }
243 }
182
244
245 pub fn attach_timeline(&mut self, timeline: Timeline) {
246 self.timeline = Some(timeline);
247 }
248
249 pub fn video_quality(&self) -> VideoQuality {
250 self.quality
251 }
252
253 pub fn set_video_quality(&mut self, quality: VideoQuality) {
254 self.quality = quality;
255 }
256
183 pub fn set_motion(&mut self, motion: bool) {
257 pub fn set_motion(&mut self, motion: bool) {
184 self.motion = motion;
258 self.motion = motion;
185 self.share_fps.store(if motion { MOTION_SHARE_FPS } else { SCREEN_SHARE_FPS }, Ordering::Relaxed);
259 self.share_fps.store(
186 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()).filter(|_| self.sharing()) {
260 if motion {
261 MOTION_SHARE_FPS
262 } else {
263 SCREEN_SHARE_FPS
264 },
265 Ordering::Relaxed,
266 );
267 if let Some(share) = self
268 .lines
269 .as_ref()
270 .and_then(|lines| lines.share.as_ref())
271 .filter(|_| self.sharing())
272 {
187 let _ = self.tune_share(&share.sender());
273 let _ = self.tune_share(&share.sender());
188 }
274 }
189 }
275 }
@@ -203,7 +289,9 @@ impl LocalVideo {
203 for encoding in &mut parameters.encodings {
289 for encoding in &mut parameters.encodings {
204 encoding.max_framerate = Some(fps);
290 encoding.max_framerate = Some(fps);
205 }
291 }
206 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
292 sender
293 .set_parameters(parameters)
294 .map_err(|error| Error::Webrtc(error.to_string()))
207 }
295 }
208
296
209 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
297 fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
@@ -214,19 +302,33 @@ impl LocalVideo {
214 }
302 }
215 }
303 }
216
304
217 pub fn apply_send_limit(&mut self, source: SendSource, limits: &[SendLimit]) -> Result<Option<Vec<LayerPlan>>> {
305 pub fn apply_send_limit(
306 &mut self,
307 source: SendSource,
308 limits: &[SendLimit],
309 ) -> Result<Option<Vec<LayerPlan>>> {
218 let sending = match source {
310 let sending = match source {
219 SendSource::Camera => self.camera_on(),
311 SendSource::Camera => self.camera_on(),
220 SendSource::Screen => self.sharing(),
312 SendSource::Screen => self.sharing(),
221 };
313 };
222 let Some(sender) = self.sender_of(source).filter(|_| sending) else { return Ok(None) };
314 let Some(sender) = self.sender_of(source).filter(|_| sending) else {
315 return Ok(None);
316 };
223 let outgoing = match source {
317 let outgoing = match source {
224 SendSource::Camera => &mut self.camera,
318 SendSource::Camera => &mut self.camera,
225 SendSource::Screen => &mut self.screen,
319 SendSource::Screen => &mut self.screen,
226 };
320 };
227 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
321 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
228 outgoing.requested = Some(RequestedLimits { limits: limits.to_vec(), applied_for: frame });
322 outgoing.requested = Some(RequestedLimits {
229 let rids: Vec<String> = sender.parameters().encodings.into_iter().map(|encoding| encoding.rid).collect();
323 limits: limits.to_vec(),
324 applied_for: frame,
325 });
326 let rids: Vec<String> = sender
327 .parameters()
328 .encodings
329 .into_iter()
330 .map(|encoding| encoding.rid)
331 .collect();
230 if rids.len() > 1 {
332 if rids.len() > 1 {
231 let plans = plan_layers(limits, frame, &rids);
333 let plans = plan_layers(limits, frame, &rids);
232 if plans.iter().any(|plan| plan.keyframe) {
334 if plans.iter().any(|plan| plan.keyframe) {
@@ -235,13 +337,20 @@ impl LocalVideo {
235 Self::set_layers(&sender, &plans, 1.0)?;
337 Self::set_layers(&sender, &plans, 1.0)?;
236 return Ok(Some(plans));
338 return Ok(Some(plans));
237 }
339 }
238 let Some(limit) = limits.first() else { return Ok(None) };
340 let Some(limit) = limits.first() else {
341 return Ok(None);
342 };
239 let encoder = encoder_limits(limit, frame);
343 let encoder = encoder_limits(limit, frame);
240 if limit.keyframe {
344 if limit.keyframe {
241 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
345 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
242 }
346 }
243 Self::set_limits(&sender, &encoder, 1.0)?;
347 Self::set_limits(&sender, &encoder, 1.0)?;
244 Ok(Some(vec![LayerPlan { rid: rids.into_iter().next().unwrap_or_default(), active: true, limits: Some(encoder), keyframe: limit.keyframe }]))
348 Ok(Some(vec![LayerPlan {
349 rid: rids.into_iter().next().unwrap_or_default(),
350 active: true,
351 limits: Some(encoder),
352 keyframe: limit.keyframe,
353 }]))
245 }
354 }
246
355
247 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
356 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
@@ -253,7 +362,11 @@ impl LocalVideo {
253 SendSource::Screen => &self.screen,
362 SendSource::Screen => &self.screen,
254 };
363 };
255 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
364 let frame = unpack_size(outgoing.frame_size.load(Ordering::Relaxed));
256 let Some(requested) = outgoing.requested.as_ref().filter(|requested| frame.is_some() && requested.applied_for != frame) else {
365 let Some(requested) = outgoing
366 .requested
367 .as_ref()
368 .filter(|requested| frame.is_some() && requested.applied_for != frame)
369 else {
257 continue;
370 continue;
258 };
371 };
259 let limits = requested.limits.clone();
372 let limits = requested.limits.clone();
@@ -265,17 +378,22 @@ impl LocalVideo {
265 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
378 fn set_layers(sender: &RtpSender, plans: &[LayerPlan], nudge: f64) -> Result<()> {
266 let mut parameters = sender.parameters();
379 let mut parameters = sender.parameters();
267 for encoding in &mut parameters.encodings {
380 for encoding in &mut parameters.encodings {
268 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else { continue };
381 let Some(plan) = plans.iter().find(|plan| plan.rid == encoding.rid) else {
382 continue;
383 };
269 let nudged = nudge != 1.0 && plan.keyframe;
384 let nudged = nudge != 1.0 && plan.keyframe;
270 encoding.active = plan.active;
385 encoding.active = plan.active;
271 let Some(limits) = &plan.limits else { continue };
386 let Some(limits) = &plan.limits else { continue };
272 encoding.scale_resolution_down_by = Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
387 encoding.scale_resolution_down_by =
388 Some(limits.scale_down_by * if nudged { nudge } else { 1.0 });
273 if let Some(framerate) = limits.max_framerate {
389 if let Some(framerate) = limits.max_framerate {
274 encoding.max_framerate = Some(framerate);
390 encoding.max_framerate = Some(framerate);
275 }
391 }
276 encoding.max_bitrate = limits.max_bitrate;
392 encoding.max_bitrate = limits.max_bitrate;
277 }
393 }
278 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
394 sender
395 .set_parameters(parameters)
396 .map_err(|error| Error::Webrtc(error.to_string()))
279 }
397 }
280
398
281 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
399 fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
@@ -287,7 +405,9 @@ impl LocalVideo {
287 }
405 }
288 encoding.max_bitrate = limits.max_bitrate;
406 encoding.max_bitrate = limits.max_bitrate;
289 }
407 }
290 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
408 sender
409 .set_parameters(parameters)
410 .map_err(|error| Error::Webrtc(error.to_string()))
291 }
411 }
292
412
293 pub fn camera_size(&self) -> Option<(u32, u32)> {
413 pub fn camera_size(&self) -> Option<(u32, u32)> {
@@ -312,7 +432,9 @@ impl LocalVideo {
312 }
432 }
313
433
314 pub fn blur_model(&self) -> Option<&'static str> {
434 pub fn blur_model(&self) -> Option<&'static str> {
315 (self.camera_on() && self.blur.active()).then(|| self.blur.model()).filter(|model| !model.is_empty())
435 (self.camera_on() && self.blur.active())
436 .then(|| self.blur.model())
437 .filter(|model| !model.is_empty())
316 }
438 }
317
439
318 pub fn has_lines(&self) -> bool {
440 pub fn has_lines(&self) -> bool {
@@ -320,17 +442,31 @@ impl LocalVideo {
320 }
442 }
321
443
322 pub fn share_mid(&self) -> Option<String> {
444 pub fn share_mid(&self) -> Option<String> {
323 self.lines.as_ref().and_then(|lines| lines.share.as_ref()).and_then(|share| share.mid())
445 self.lines
446 .as_ref()
447 .and_then(|lines| lines.share.as_ref())
448 .and_then(|share| share.mid())
324 }
449 }
325
450
326 pub fn has_share_line(&self) -> bool {
451 pub fn has_share_line(&self) -> bool {
327 self.lines.as_ref().is_some_and(|lines| lines.share.is_some())
452 self.lines
453 .as_ref()
454 .is_some_and(|lines| lines.share.is_some())
328 }
455 }
329
456
330 pub fn add_share_line(&mut self, share: RtpTransceiver, camera: Option<RtpTransceiver>) -> Result<()> {
457 pub fn add_share_line(
458 &mut self,
459 share: RtpTransceiver,
460 camera: Option<RtpTransceiver>,
461 ) -> Result<()> {
331 match (self.lines.as_mut(), camera) {
462 match (self.lines.as_mut(), camera) {
332 (Some(lines), _) => lines.share = Some(share),
463 (Some(lines), _) => lines.share = Some(share),
333 (None, Some(camera)) => self.lines = Some(VideoLines { camera, share: Some(share) }),
464 (None, Some(camera)) => {
465 self.lines = Some(VideoLines {
466 camera,
467 share: Some(share),
468 })
469 }
334 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
470 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
335 }
471 }
336 Ok(())
472 Ok(())
@@ -341,7 +477,12 @@ impl LocalVideo {
341 .as_ref()
477 .as_ref()
342 .and_then(|lines| lines.share.as_ref())
478 .and_then(|lines| lines.share.as_ref())
343 .and_then(|share| share.current_direction())
479 .and_then(|share| share.current_direction())
344 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
480 .is_some_and(|direction| {
481 matches!(
482 direction,
483 RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv
484 )
485 })
345 }
486 }
346
487
347 pub fn is_available(&self) -> bool {
488 pub fn is_available(&self) -> bool {
@@ -360,6 +501,10 @@ impl LocalVideo {
360 self.screen.capture.is_some()
501 self.screen.capture.is_some()
361 }
502 }
362
503
504 pub fn portal_is_open(&self) -> bool {
505 self.portal_armed
506 }
507
363 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
508 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
364 if self.camera_on() {
509 if self.camera_on() {
365 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
510 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
@@ -385,19 +530,34 @@ impl LocalVideo {
385 for encoding in &mut parameters.encodings {
530 for encoding in &mut parameters.encodings {
386 encoding.active = active;
531 encoding.active = active;
387 }
532 }
388 sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
533 sender
534 .set_parameters(parameters)
535 .map_err(|error| Error::Webrtc(error.to_string()))
389 }
536 }
390
537
391 fn camera_sink(&self) -> LocalSink {
538 fn camera_sink(&self) -> LocalSink {
392 LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
539 LocalSink::new(
393 .mirrored_by(self.blur.clone())
540 self.camera.source.clone(),
394 .reporting_size(self.camera.frame_size.clone())
541 Some((self.hub.clone(), VideoKey::LocalCamera)),
542 )
543 .mirrored_by(self.blur.clone())
544 .reporting_size(self.camera.frame_size.clone())
545 }
546
547 /// Local share frames go to the encoder and to the window in the chat.
548 fn screen_sink(&self) -> LocalSink {
549 LocalSink::new(
550 self.screen.source.clone(),
551 Some((self.hub.clone(), VideoKey::LocalScreen)),
552 )
553 .with_standout(self.blur.clone())
554 .reporting_size(self.screen.frame_size.clone())
395 }
555 }
396
556
397 fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
557 fn report_failure(&self, notice_key: &'static str) -> impl FnOnce(String) + Send + 'static {
398 let updates = self.updates.clone();
558 let updates = self.updates.clone();
399 move |reason| {
559 move |reason| {
400 let _ = updates.send(CallUpdate::Notice(format!("{what} stopped: {reason}")));
560 let _ = updates.send(CallUpdate::Notice(notice_with_detail(notice_key, reason)));
401 }
561 }
402 }
562 }
403
563
@@ -412,7 +572,10 @@ impl LocalVideo {
412 }
572 }
413
573
414 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
574 pub fn start_camera(&mut self, choice: &DeviceChoice) -> Result<()> {
415 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
575 let lines = self
576 .lines
577 .as_ref()
578 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
416 if !self.is_available() {
579 if !self.is_available() {
417 return Err(Error::Webrtc("video is switched off".into()));
580 return Err(Error::Webrtc("video is switched off".into()));
418 }
581 }
@@ -426,14 +589,56 @@ impl LocalVideo {
426 Ok(())
589 Ok(())
427 }
590 }
428
591
592 pub fn camera_capture_summary(&self) -> Option<String> {
593 self.camera_stats.summary()
594 }
595
429 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
596 fn capture_camera(&self, choice: &DeviceChoice) -> Result<Capture> {
430 let mut sink = self.camera_sink();
597 let mut sink = self.camera_sink();
431 Ok(match self.mode {
598 Ok(match self.mode {
432 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Camera, Some(self.blur.clone()))),
599 VideoMode::Pattern => Capture::Task(spawn_pattern(
433 _ => start_camera(choice, self.blur.clone(), move |buffer| sink.push(buffer), self.report_failure("Camera"))?,
600 sink,
601 PatternKind::Camera,
602 Some(self.blur.clone()),
603 )),
604 _ => {
605 let timeline = self.timeline.clone();
606 start_camera(
607 choice,
608 self.quality,
609 self.blur.clone(),
610 self.camera_stats.clone(),
611 move |label| {
612 if let Some(timeline) = timeline {
613 timeline.record("camera capture", label);
614 } else {
615 eprintln!("calls: camera capture {label}");
616 }
617 },
618 move |buffer| sink.push(buffer),
619 self.report_failure(CAMERA_STOPPED_NOTICE),
620 )?
621 }
434 })
622 })
435 }
623 }
436
624
625 /// Restart capture with the current quality if the camera is already running.
626 pub fn refresh_camera_capture(&mut self, choice: &DeviceChoice) -> Result<()> {
627 if self.camera.capture.is_none() {
628 return Ok(());
629 }
630 let preview = self.camera_preview;
631 self.camera.capture = None;
632 self.camera.capture = Some(self.capture_camera(choice)?);
633 self.camera_preview = preview;
634 if !preview {
635 if let Some(lines) = self.lines.as_ref() {
636 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
637 }
638 }
639 Ok(())
640 }
641
437 pub fn stop_camera(&mut self) {
642 pub fn stop_camera(&mut self) {
438 self.camera_preview = false;
643 self.camera_preview = false;
439 self.camera.capture = None;
644 self.camera.capture = None;
@@ -444,28 +649,110 @@ impl LocalVideo {
444 self.hub.forget(&VideoKey::LocalCamera);
649 self.hub.forget(&VideoKey::LocalCamera);
445 }
650 }
446
651
447 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
652 pub fn accept_portal(&mut self, generation: u64) -> bool {
448 let lines = self.lines.as_ref().ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
653 if self.portal_armed && self.portal_generation == generation {
449 let share = lines.share.as_ref().ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
654 self.portal_armed = false;
655 self.portal_keep = true;
656 self.portal_bound = true;
657 true
658 } else {
659 false
660 }
661 }
662
663 pub fn open_portal(
664 &mut self,
665 kind: ShareKind,
666 commands: UnboundedSender<CallCommand>,
667 ) -> Result<()> {
450 if !self.is_available() {
668 if !self.is_available() {
451 return Err(Error::Webrtc("video is switched off".into()));
669 return Err(Error::Webrtc("video is switched off".into()));
452 }
670 }
671 if self.mode == VideoMode::Pattern {
672 let source = ShareSource {
673 id: if kind == ShareKind::Screen { 1 } else { 2 },
674 kind,
675 title: if kind == ShareKind::Screen {
676 "Test screen"
677 } else {
678 "Test window"
679 }
680 .into(),
681 };
682 let _ = commands.send(CallCommand::StartShare(source));
683 return Ok(());
684 }
685 self.portal_generation = self.portal_generation.wrapping_add(1);
686 let generation = self.portal_generation;
687 self.portal_armed = false;
688 self.portal_keep = false;
689 self.portal_bound = false;
453 self.screen.capture = None;
690 self.screen.capture = None;
454 let mut sink = LocalSink::new(self.screen.source.clone(), None)
691 let mut sink = self.screen_sink();
455 .with_standout(self.blur.clone())
692 let updates = self.updates.clone();
456 .reporting_size(self.screen.frame_size.clone());
693 let capture = start_portal_capture(
457 let capture = match self.mode {
694 kind,
458 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
695 self.share_fps.clone(),
459 _ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
696 move |buffer| sink.push(buffer),
460 };
697 move |follow| match follow {
698 PortalFollowUp::Share(source) => {
699 let _ = commands.send(CallCommand::FinishPortalShare { source, generation });
700 }
701 PortalFollowUp::Quiet => {
702 let _ = commands.send(CallCommand::AbandonPortalShare);
703 }
704 PortalFollowUp::Notice(text) => {
705 let _ = updates.send(CallUpdate::Notice(text.to_owned()));
706 let _ = commands.send(CallCommand::AbandonPortalShare);
707 }
708 },
709 )?;
710 self.portal_armed = true;
711 self.screen.capture = Some(capture);
712 Ok(())
713 }
714
715 pub fn start_share(&mut self, source: &ShareSource) -> Result<()> {
716 let lines = self
717 .lines
718 .as_ref()
719 .ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
720 let share = lines
721 .share
722 .as_ref()
723 .ok_or_else(|| Error::Webrtc("sharing needs a meeting".into()))?;
724 if !self.is_available() {
725 return Err(Error::Webrtc("video is switched off".into()));
726 }
727 let keep = std::mem::take(&mut self.portal_keep) || self.portal_bound;
728 if !keep {
729 self.portal_armed = false;
730 self.portal_generation = self.portal_generation.wrapping_add(1);
731 self.screen.capture = None;
732 let mut sink = self.screen_sink();
733 let capture = match self.mode {
734 VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
735 _ => start_screen_capture(
736 source.clone(),
737 self.share_fps.clone(),
738 move |buffer| sink.push(buffer),
739 self.report_failure(SCREEN_SHARE_STOPPED_NOTICE),
740 )?,
741 };
742 self.screen.capture = Some(capture);
743 }
461 Self::begin_sending(&share.sender(), &self.screen.track)?;
744 Self::begin_sending(&share.sender(), &self.screen.track)?;
462 let _ = self.tune_share(&share.sender());
745 let _ = self.tune_share(&share.sender());
463 self.screen.capture = Some(capture);
464 Ok(())
746 Ok(())
465 }
747 }
466
748
467 pub fn stop_share(&mut self) {
749 pub fn stop_share(&mut self) {
750 self.portal_generation = self.portal_generation.wrapping_add(1);
751 self.portal_armed = false;
752 self.portal_keep = false;
753 self.portal_bound = false;
468 self.screen.capture = None;
754 self.screen.capture = None;
755 self.hub.forget(&VideoKey::LocalScreen);
469 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
756 if let Some(share) = self.lines.as_ref().and_then(|lines| lines.share.as_ref()) {
470 let _ = Self::set_active(&share.sender(), false);
757 let _ = Self::set_active(&share.sender(), false);
471 }
758 }
@@ -485,10 +772,18 @@ mod tests {
485 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
772 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
486 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
773 let (sender, _receiver) = tokio::sync::mpsc::unbounded_channel();
487 let factory = crate::devices::shared_factory();
774 let factory = crate::devices::shared_factory();
488 let mut video = LocalVideo::new(&factory, VideoMode::Pattern, VideoHub::new(sender.clone()), sender);
775 let mut video = LocalVideo::new(
776 &factory,
777 VideoMode::Pattern,
778 VideoHub::new(sender.clone()),
779 sender,
780 );
489 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
781 video.preview_camera(&DeviceChoice::SystemDefault).unwrap();
490 assert!(video.camera_previewing() && !video.camera_on());
782 assert!(video.camera_previewing() && !video.camera_on());
491 assert!(video.start_camera(&DeviceChoice::SystemDefault).is_err(), "sending needs a negotiated line");
783 assert!(
784 video.start_camera(&DeviceChoice::SystemDefault).is_err(),
785 "sending needs a negotiated line"
786 );
492 assert!(video.camera_previewing());
787 assert!(video.camera_previewing());
493 video.stop_camera();
788 video.stop_camera();
494 assert!(!video.camera_previewing() && !video.camera_on());
789 assert!(!video.camera_previewing() && !video.camera_on());
openspec/changes/archive/2026-11-12-ui-locale-de-en/.openspec.yaml added +2 −0
@@ -0,0 +1,2 @@
1 schema: spec-driven
2 created: 2026-11-12
@@ -0,0 +1,2 @@
1schema: spec-driven
2created: 2026-11-12
openspec/changes/archive/2026-11-12-ui-locale-de-en/design.md added +87 −0
@@ -0,0 +1,87 @@
1 # Design
2
3 ## Context
4
5 Siehe `proposal.md` für den Anlass. Die App-UI in `crates/app` (Views, Settings, Notify/Tray) und Nutzerhinweise in `crates/calling` (u. a. `CallUpdate::Notice` mit englischen Literalen) sind hardcodiert Englisch. Message-Translation und Caption-Sprachen existieren separat und bleiben unberührt.
6
7 `vendor/gpui-component` nutzt bereits `rust_i18n` (`locales/ui.yml`, `set_locale` / `locale` in `vendor/gpui-component/src/lib.rs`). Appearance-Persistenz liegt in `crates/app-base/src/appearance.rs` (Store-Meta). Notification-Settings analog in `crates/app-state/src/notify/settings.rs`.
8
9 ## Goals / Non-Goals
10
11 **Goals:**
12
13 - App-eigener Locale-Katalog `en` + `de` (Deutschland-Orthografie im Produktkatalog) mit Fallback `en`.
14 - Ableitung erster Start aus OS-Locale (`de*` → `de`, sonst `en`), Override persistiert, Live-Umschalten über Laufzeit-Lookup.
15 - Stabile Hinweis-IDs aus Calling/App-State; Anzeigetext erst an der UI-Grenze.
16 - Phasenweise Abdeckung bis Endzustand C (volle produktseitige UI), ohne halb leere Labels dank Fallback.
17
18 **Non-Goals:**
19
20 - `de-CH`-Katalog, weitere Sprachen in diesem Change.
21 - Server-Content, Wire-Protokoll, Captions spoken language, Message-Translation.
22 - Upstream-Riesen-PR; Lieferung auf Forgejo-`origin`. Vendor-Locale-YAML der Komponenten-Bibliothek nicht mit App-Strings mischen.
23
24 ## Decisions
25
26 ### `rust-i18n` für die App, eigener Katalog
27
28 Dieselbe Bibliothek wie `gpui-component`, eigener Katalog (z. B. unter `crates/app` oder kleinem Locale-Modul), Fallback `en`. Beim Start und bei Preference-Änderung: App-Locale setzen und `gpui_kit`/`gpui-component` `set_locale` mitziehen, damit Widget-Strings (DatePicker, Dialog-Defaults) nicht Englisch bleiben während die App Deutsch zeigt.
29
30 Alternative verworfen: Mozilla Fluent / gettext — zusätzlicher Stack ohne Nutzen, solange der Vendor schon `rust-i18n` hat.
31
32 ### Preference: Auto vs fest
33
34 Gespeicherter Wert: `auto` | `en` | `de`. Default ohne Meta-Eintrag = `auto` (entspricht Spec «keine gespeicherte Einstellung»). Persistenz analog Appearance (Store-Meta). UI-Einstellung unter Appearance oder General; Anzeige der effektiven Sprache bei `auto` klar kennzeichnen.
35
36 Effektive Locale:
37
38 ```
39 meta fehlt / auto --> OS beginnt mit "de"? --> de : en
40 meta en|de --> genau dieser Wert
41 ```
42
43 OS-Locale: Plattform-übliche Abfrage (Linux `LANG`/`LC_ALL`/`LC_MESSAGES`, Windows/macOS über vorhandene System-APIs im Repo bzw. schlanke Ergänzung). Nur Prefix `de` zählt; `de_CH`, `de_DE`, `de-AT` → Deutsch (Produkttexte dennoch Deutschland-Orthografie).
44
45 ### Strings beim Render, nicht als `'static` Bootstrap
46
47 Sichtbare Labels über Lookup zur Render-Zeit (`t!` oder Wrapper), damit Locale-Wechsel ohne Neustart wirkt. Const-`&'static str` die einmal bei Init gebacken werden, nur wo unvermeidbar und dann nach Locale-Wechsel invalidieren/neu binden (Tray-Menü neu syncen).
48
49 ### Call-Notices: IDs statt englischer Sätze
50
51 `CallUpdate::Notice(String)` trägt heute fertigen Englisch-Text. Für Lokalisierung:
52
53 ```
54 calling / app-state UI (crates/app)
55 ------------------ ---------------
56 NoticeId + optionale Args --> t!("call.notice....", args)
57 format!("Camera...: {error}") --> Key + error als Arg (error intern Englisch ok)
58 ```
59
60 Stabile IDs für bekannte Notices (`ShareRefused`, `OnHold`, …). Dynamische Fehler: Template-Key + Argument. Tests in `calling` prüfen IDs/Enums, nicht übersetzte Sätze. UI-Tests können Locale setzen und DE/EN-Text asserten.
61
62 Alternative verworfen: `t!` direkt in `calling` — zieht Locale-Katalog in ein Nicht-UI-Crate und koppelt Unit-Tests an Übersetzungen.
63
64 ### Lieferphasen (ein Change, Endzustand C)
65
66 1. Gerüst: Katalog, Preference, OS-Default, Settings-Steuerung, `set_locale`, Fallback.
67 2. Chrome: Rail, Settings-Nav/Texte, häufige Dialoge (Cancel/Save/…).
68 3. Kernflächen: Chat, Calls, Calendar, Composer, Shortcuts-Beschriftungen.
69 4. Notices/Tray/Agents/Fenster-Titel/Rest-Fehlertexte; Calling auf Notice-IDs.
70
71 Jede Phase darf mit Fallback `en` shippen; Spec «gesamte UI» ist erfüllt, wenn Phase 4 fertig und Verify grün ist.
72
73 ### OpenSpec vs Produktorthografie
74
75 OpenSpec-Artefakte und Agent-Texte: Schweizer Schreibweise (kein Eszett). Produktkatalog `de`: Deutschland-Deutsch inklusive Eszett. Kein Widerspruch — unterschiedliche Textsorten.
76
77 ## Risks / Trade-offs
78
79 - [Riesen-Diff / Layout-Tests mit englischen Strings] → Phasen; Tests locale setzen oder auf Keys/Rollen prüfen; `layout_guard` und sichtbare String-Asserts gezielt anpassen.
80 - [Tray/OS-Menüs cachen Labels] → nach Locale-Wechsel `sync_tray` und vergleichbare Rebuilds.
81 - [Längere DE-Strings sprengen Layout] → kritische Buttons in DE prüfen; wo nötig kürzere Formulierungen, nicht Schrift skalieren.
82 - [Notice-ID-Migration lässt Rest-Literale] → Inventar der `CallUpdate::Notice`-Pfade; CI oder Test «keine neuen englischen Notice-Literale» optional später.
83 - [gpui-component ohne `de` in `locales/ui.yml`] → fehlende Widget-Keys fallen auf `en`; bei Bedarf `de`-Zeilen im Vendor nachziehen oder akzeptieren bis Folge-Change.
84
85 ## Migration Plan
86
87 Kein Server-State. Bestehende Installationen ohne Meta-Key verhalten sich wie `auto` (OS). Rollback: Preference entfernen / auf `en` setzen; Code-Revert auf dem Fork-Branch. Lieferung nur nach Forgejo-`origin`.
@@ -0,0 +1,87 @@
1# Design
2
3## Context
4
5Siehe `proposal.md` für den Anlass. Die App-UI in `crates/app` (Views, Settings, Notify/Tray) und Nutzerhinweise in `crates/calling` (u. a. `CallUpdate::Notice` mit englischen Literalen) sind hardcodiert Englisch. Message-Translation und Caption-Sprachen existieren separat und bleiben unberührt.
6
7`vendor/gpui-component` nutzt bereits `rust_i18n` (`locales/ui.yml`, `set_locale` / `locale` in `vendor/gpui-component/src/lib.rs`). Appearance-Persistenz liegt in `crates/app-base/src/appearance.rs` (Store-Meta). Notification-Settings analog in `crates/app-state/src/notify/settings.rs`.
8
9## Goals / Non-Goals
10
11**Goals:**
12
13- App-eigener Locale-Katalog `en` + `de` (Deutschland-Orthografie im Produktkatalog) mit Fallback `en`.
14- Ableitung erster Start aus OS-Locale (`de*` → `de`, sonst `en`), Override persistiert, Live-Umschalten über Laufzeit-Lookup.
15- Stabile Hinweis-IDs aus Calling/App-State; Anzeigetext erst an der UI-Grenze.
16- Phasenweise Abdeckung bis Endzustand C (volle produktseitige UI), ohne halb leere Labels dank Fallback.
17
18**Non-Goals:**
19
20- `de-CH`-Katalog, weitere Sprachen in diesem Change.
21- Server-Content, Wire-Protokoll, Captions spoken language, Message-Translation.
22- Upstream-Riesen-PR; Lieferung auf Forgejo-`origin`. Vendor-Locale-YAML der Komponenten-Bibliothek nicht mit App-Strings mischen.
23
24## Decisions
25
26### `rust-i18n` für die App, eigener Katalog
27
28Dieselbe Bibliothek wie `gpui-component`, eigener Katalog (z. B. unter `crates/app` oder kleinem Locale-Modul), Fallback `en`. Beim Start und bei Preference-Änderung: App-Locale setzen und `gpui_kit`/`gpui-component` `set_locale` mitziehen, damit Widget-Strings (DatePicker, Dialog-Defaults) nicht Englisch bleiben während die App Deutsch zeigt.
29
30Alternative verworfen: Mozilla Fluent / gettext — zusätzlicher Stack ohne Nutzen, solange der Vendor schon `rust-i18n` hat.
31
32### Preference: Auto vs fest
33
34Gespeicherter Wert: `auto` | `en` | `de`. Default ohne Meta-Eintrag = `auto` (entspricht Spec «keine gespeicherte Einstellung»). Persistenz analog Appearance (Store-Meta). UI-Einstellung unter Appearance oder General; Anzeige der effektiven Sprache bei `auto` klar kennzeichnen.
35
36Effektive Locale:
37
38```
39meta fehlt / auto --> OS beginnt mit "de"? --> de : en
40meta en|de --> genau dieser Wert
41```
42
43OS-Locale: Plattform-übliche Abfrage (Linux `LANG`/`LC_ALL`/`LC_MESSAGES`, Windows/macOS über vorhandene System-APIs im Repo bzw. schlanke Ergänzung). Nur Prefix `de` zählt; `de_CH`, `de_DE`, `de-AT` → Deutsch (Produkttexte dennoch Deutschland-Orthografie).
44
45### Strings beim Render, nicht als `'static` Bootstrap
46
47Sichtbare Labels über Lookup zur Render-Zeit (`t!` oder Wrapper), damit Locale-Wechsel ohne Neustart wirkt. Const-`&'static str` die einmal bei Init gebacken werden, nur wo unvermeidbar und dann nach Locale-Wechsel invalidieren/neu binden (Tray-Menü neu syncen).
48
49### Call-Notices: IDs statt englischer Sätze
50
51`CallUpdate::Notice(String)` trägt heute fertigen Englisch-Text. Für Lokalisierung:
52
53```
54calling / app-state UI (crates/app)
55------------------ ---------------
56NoticeId + optionale Args --> t!("call.notice....", args)
57format!("Camera...: {error}") --> Key + error als Arg (error intern Englisch ok)
58```
59
60Stabile IDs für bekannte Notices (`ShareRefused`, `OnHold`, …). Dynamische Fehler: Template-Key + Argument. Tests in `calling` prüfen IDs/Enums, nicht übersetzte Sätze. UI-Tests können Locale setzen und DE/EN-Text asserten.
61
62Alternative verworfen: `t!` direkt in `calling` — zieht Locale-Katalog in ein Nicht-UI-Crate und koppelt Unit-Tests an Übersetzungen.
63
64### Lieferphasen (ein Change, Endzustand C)
65
661. Gerüst: Katalog, Preference, OS-Default, Settings-Steuerung, `set_locale`, Fallback.
672. Chrome: Rail, Settings-Nav/Texte, häufige Dialoge (Cancel/Save/…).
683. Kernflächen: Chat, Calls, Calendar, Composer, Shortcuts-Beschriftungen.
694. Notices/Tray/Agents/Fenster-Titel/Rest-Fehlertexte; Calling auf Notice-IDs.
70
71Jede Phase darf mit Fallback `en` shippen; Spec «gesamte UI» ist erfüllt, wenn Phase 4 fertig und Verify grün ist.
72
73### OpenSpec vs Produktorthografie
74
75OpenSpec-Artefakte und Agent-Texte: Schweizer Schreibweise (kein Eszett). Produktkatalog `de`: Deutschland-Deutsch inklusive Eszett. Kein Widerspruch — unterschiedliche Textsorten.
76
77## Risks / Trade-offs
78
79- [Riesen-Diff / Layout-Tests mit englischen Strings] → Phasen; Tests locale setzen oder auf Keys/Rollen prüfen; `layout_guard` und sichtbare String-Asserts gezielt anpassen.
80- [Tray/OS-Menüs cachen Labels] → nach Locale-Wechsel `sync_tray` und vergleichbare Rebuilds.
81- [Längere DE-Strings sprengen Layout] → kritische Buttons in DE prüfen; wo nötig kürzere Formulierungen, nicht Schrift skalieren.
82- [Notice-ID-Migration lässt Rest-Literale] → Inventar der `CallUpdate::Notice`-Pfade; CI oder Test «keine neuen englischen Notice-Literale» optional später.
83- [gpui-component ohne `de` in `locales/ui.yml`] → fehlende Widget-Keys fallen auf `en`; bei Bedarf `de`-Zeilen im Vendor nachziehen oder akzeptieren bis Folge-Change.
84
85## Migration Plan
86
87Kein Server-State. Bestehende Installationen ohne Meta-Key verhalten sich wie `auto` (OS). Rollback: Preference entfernen / auf `en` setzen; Code-Revert auf dem Fork-Branch. Lieferung nur nach Forgejo-`origin`.
openspec/changes/archive/2026-11-12-ui-locale-de-en/proposal.md added +34 −0
@@ -0,0 +1,34 @@
1 # Proposal
2
3 ## Why
4
5 Die gesamte App-Oberfläche ist heute englisch hardcodiert. Nutzer mit deutscher Systemsprache und der Fork-Zielgruppe brauchen eine durchgängig deutschsprachige UI, ohne die englische Basis und Upstream-Kompatibilität zu verlieren. Message-Translation und Caption-Sprachen existieren schon; die App-UI-Sprache fehlt.
6
7 ## What Changes
8
9 - Die App bietet zwei UI-Sprachen: Englisch und Deutsch (Deutschland-Orthografie im Produktkatalog).
10 - Beim ersten Start folgt die UI der OS-Locale: System-Locale `de*` → Deutsch, sonst Englisch.
11 - Nutzer können die UI-Sprache in den Einstellungen dauerhaft überschreiben; die Wahl wird gespeichert und gilt beim nächsten Start.
12 - Umschalten aktualisiert sichtbare UI-Texte ohne Neustart, soweit die Texte zur Laufzeit aufgelöst werden.
13 - Alle produktseitigen UI-Texte sind lokalisiert: Navigation, Settings, Dialoge, Menüs, Tooltips, Shortcuts, Toasts, Tray, Agent-UI und Call-/Fehler-Hinweise.
14 - Call- und ähnliche Nutzerhinweise tragen stabile Schlüssel; der Anzeigetext entsteht erst an der UI-Grenze in der aktiven Locale.
15 - Fehlende Übersetzungen fallen auf Englisch zurück statt leerer oder roher Keys.
16 - Unverändert ausserhalb: Chat-/Server-Inhalte, Adaptive Cards vom Server, Geräte-Namen vom OS, Wire-Protokoll-Strings, Captions-Spoken-Language, bestehende Message-Translation.
17
18 ## Capabilities
19
20 ### New Capabilities
21
22 - `ui-locale`: UI-Sprache der App wählen, aus OS-Locale ableiten, persistieren und auf die gesamte App-Oberfläche anwenden (Englisch und Deutsch).
23
24 ### Modified Capabilities
25
26 - Keine. Message-Translation und Caption-Sprachen bleiben eigene, unveränderte Verhaltensbereiche.
27
28 ## Impact
29
30 - UI-Crate (`crates/app` und verwandte Views), Persistenz analog Appearance/Settings-Meta, Tray- und Toast-Texte.
31 - Call-Hinweise und vergleichbare Nutzertexte in `crates/calling` / `app-state`: Umstellung von englischen Literalen auf stabile Hinweis-IDs, Auflösung in der UI.
32 - Katalog und Locale-Laufzeit analog dem bestehenden `rust-i18n`-Muster in `vendor/gpui-component` (eigener App-Katalog, Vendor-YAML nicht mischen).
33 - Layout-/UI-Tests, die englische sichtbare Strings erwarten, müssen locale-bewusst werden oder gegen Keys/IDs prüfen.
34 - Lieferung auf dem Fork (`origin` Forgejo). Kein Riesen-PR der ganzen i18n-Welle an Upstream; Infrastruktur kann später als eigene Scheibe angeboten werden.
@@ -0,0 +1,34 @@
1# Proposal
2
3## Why
4
5Die gesamte App-Oberfläche ist heute englisch hardcodiert. Nutzer mit deutscher Systemsprache und der Fork-Zielgruppe brauchen eine durchgängig deutschsprachige UI, ohne die englische Basis und Upstream-Kompatibilität zu verlieren. Message-Translation und Caption-Sprachen existieren schon; die App-UI-Sprache fehlt.
6
7## What Changes
8
9- Die App bietet zwei UI-Sprachen: Englisch und Deutsch (Deutschland-Orthografie im Produktkatalog).
10- Beim ersten Start folgt die UI der OS-Locale: System-Locale `de*` → Deutsch, sonst Englisch.
11- Nutzer können die UI-Sprache in den Einstellungen dauerhaft überschreiben; die Wahl wird gespeichert und gilt beim nächsten Start.
12- Umschalten aktualisiert sichtbare UI-Texte ohne Neustart, soweit die Texte zur Laufzeit aufgelöst werden.
13- Alle produktseitigen UI-Texte sind lokalisiert: Navigation, Settings, Dialoge, Menüs, Tooltips, Shortcuts, Toasts, Tray, Agent-UI und Call-/Fehler-Hinweise.
14- Call- und ähnliche Nutzerhinweise tragen stabile Schlüssel; der Anzeigetext entsteht erst an der UI-Grenze in der aktiven Locale.
15- Fehlende Übersetzungen fallen auf Englisch zurück statt leerer oder roher Keys.
16- Unverändert ausserhalb: Chat-/Server-Inhalte, Adaptive Cards vom Server, Geräte-Namen vom OS, Wire-Protokoll-Strings, Captions-Spoken-Language, bestehende Message-Translation.
17
18## Capabilities
19
20### New Capabilities
21
22- `ui-locale`: UI-Sprache der App wählen, aus OS-Locale ableiten, persistieren und auf die gesamte App-Oberfläche anwenden (Englisch und Deutsch).
23
24### Modified Capabilities
25
26- Keine. Message-Translation und Caption-Sprachen bleiben eigene, unveränderte Verhaltensbereiche.
27
28## Impact
29
30- UI-Crate (`crates/app` und verwandte Views), Persistenz analog Appearance/Settings-Meta, Tray- und Toast-Texte.
31- Call-Hinweise und vergleichbare Nutzertexte in `crates/calling` / `app-state`: Umstellung von englischen Literalen auf stabile Hinweis-IDs, Auflösung in der UI.
32- Katalog und Locale-Laufzeit analog dem bestehenden `rust-i18n`-Muster in `vendor/gpui-component` (eigener App-Katalog, Vendor-YAML nicht mischen).
33- Layout-/UI-Tests, die englische sichtbare Strings erwarten, müssen locale-bewusst werden oder gegen Keys/IDs prüfen.
34- Lieferung auf dem Fork (`origin` Forgejo). Kein Riesen-PR der ganzen i18n-Welle an Upstream; Infrastruktur kann später als eigene Scheibe angeboten werden.
openspec/changes/archive/2026-11-12-ui-locale-de-en/specs/ui-locale/spec.md added +104 −0
@@ -0,0 +1,104 @@
1 # Spec Delta
2
3 ## Purpose
4
5 Steuert die Sprache der App-Oberfläche: Ableitung aus der System-Locale beim ersten Start, dauerhafte Nutzerwahl und Anwendung auf alle produktseitigen UI-Texte in Englisch und Deutsch.
6
7 ## ADDED Requirements
8
9 ### Requirement: Unterstützte UI-Sprachen
10
11 Die App MUST genau die UI-Sprachen Englisch und Deutsch anbieten. Deutsch MUST Deutschland-Orthografie im sichtbaren Produkttext verwenden.
12
13 #### Scenario: Sprachenwahl zeigt DE und EN
14
15 - **WHEN** der Nutzer die UI-Spracheinstellung öffnet
16 - **THEN** stehen Englisch und Deutsch zur Auswahl
17 - **AND** keine weitere UI-Sprache ist wählbar
18
19 ### Requirement: Erster Start folgt der OS-Locale
20
21 Ohne gespeicherte UI-Spracheinstellung MUST die App die System-Locale auswerten: beginnt die Locale mit `de`, MUST die UI Deutsch sein; sonst MUST sie Englisch sein.
22
23 #### Scenario: System Deutsch
24
25 - **GIVEN** es existiert noch keine gespeicherte UI-Sprache
26 - **WHEN** die App startet und die System-Locale mit `de` beginnt
27 - **THEN** zeigt die App ihre Oberflächentexte auf Deutsch
28
29 #### Scenario: System nicht Deutsch
30
31 - **GIVEN** es existiert noch keine gespeicherte UI-Sprache
32 - **WHEN** die App startet und die System-Locale nicht mit `de` beginnt
33 - **THEN** zeigt die App ihre Oberflächentexte auf Englisch
34
35 ### Requirement: Nutzerwahl überschreibt und persistiert
36
37 Der Nutzer MUST die UI-Sprache in den Einstellungen auf Englisch oder Deutsch setzen können. Die Wahl MUST gespeichert werden und MUST bei späteren Starts gelten, unabhängig von der dann aktuellen System-Locale.
38
39 #### Scenario: Explizit Deutsch speichern
40
41 - **WHEN** der Nutzer die UI-Sprache auf Deutsch setzt
42 - **THEN** zeigt die App Deutsch
43 - **AND** nach Neustart der App bleibt Deutsch aktiv, auch wenn die System-Locale nicht mit `de` beginnt
44
45 #### Scenario: Explizit Englisch speichern
46
47 - **WHEN** der Nutzer die UI-Sprache auf Englisch setzt
48 - **THEN** zeigt die App Englisch
49 - **AND** nach Neustart bleibt Englisch aktiv, auch wenn die System-Locale mit `de` beginnt
50
51 ### Requirement: Umschalten ohne Neustart
52
53 Ändert der Nutzer die UI-Sprache, MUST die sichtbare Oberfläche die neue Sprache annehmen, ohne dass die App beendet werden muss.
54
55 #### Scenario: Wechsel in den Einstellungen
56
57 - **WHEN** der Nutzer in einer laufenden Sitzung von Englisch auf Deutsch wechselt
58 - **THEN** erscheinen Navigation, Einstellungen und Dialoge in Deutsch
59 - **AND** die Sitzung bleibt geöffnet
60
61 ### Requirement: Gesamte produktseitige UI ist lokalisiert
62
63 Alle von der App selbst stammenden Oberflächentexte MUST in der aktiven UI-Sprache erscheinen. Das umfasst Navigation, Einstellungen, Dialoge, Menüs, Tooltips, Tastaturkürzel-Beschriftungen, Toasts, Tray-Menü, Agent-UI und Nutzerhinweise aus Gesprächen und Fehlersituationen.
64
65 #### Scenario: Settings und Chrome
66
67 - **WHEN** die UI-Sprache Deutsch ist
68 - **THEN** sind Einstellungsnavigation, Rail und häufige Dialogaktionen (etwa Abbrechen und Speichern) auf Deutsch
69
70 #### Scenario: Call-Hinweis
71
72 - **WHEN** die UI-Sprache Deutsch ist und ein lokal erzeugter Call-Hinweis angezeigt wird
73 - **THEN** erscheint der Hinweistext auf Deutsch
74
75 #### Scenario: Tray
76
77 - **WHEN** die UI-Sprache Deutsch ist und der Nutzer das Tray-Menü öffnet
78 - **THEN** sind die Menüeinträge auf Deutsch
79
80 ### Requirement: Fehlende Übersetzung fällt auf Englisch zurück
81
82 Fehlt für einen UI-Text die Übersetzung in der aktiven Sprache, MUST die App den englischen Text zeigen statt eines leeren Labels oder eines rohen Schlüssels.
83
84 #### Scenario: Fehlender Key unter Deutsch
85
86 - **WHEN** die UI-Sprache Deutsch ist und für einen UI-Text keine deutsche Übersetzung vorliegt
87 - **THEN** zeigt die App den englischen Text für diesen Eintrag
88 - **AND** die übrigen lokalisierten Texte bleiben auf Deutsch
89
90 ### Requirement: Fremder Content bleibt unverändert
91
92 Server- und Nutzerinhalte MUST die UI-Locale nicht ersetzen. Message-Translation, Captions-Spoken-Language, Adaptive-Card-Titel vom Server und Gerätenamen vom Betriebssystem bleiben eigene Pfade.
93
94 #### Scenario: Chat-Nachricht
95
96 - **WHEN** die UI-Sprache Deutsch ist und eine englische Chat-Nachricht angezeigt wird
97 - **THEN** bleibt der Nachrichteninhalt Englisch
98 - **AND** die umgebenden App-Steuerelemente sind Deutsch
99
100 #### Scenario: Message-Translation unverändert
101
102 - **WHEN** der Nutzer Message-Translation nutzt
103 - **THEN** gilt weiterhin die bestehende Translation-Einstellung
104 - **AND** die UI-Locale ersetzt diese Einstellung nicht
@@ -0,0 +1,104 @@
1# Spec Delta
2
3## Purpose
4
5Steuert die Sprache der App-Oberfläche: Ableitung aus der System-Locale beim ersten Start, dauerhafte Nutzerwahl und Anwendung auf alle produktseitigen UI-Texte in Englisch und Deutsch.
6
7## ADDED Requirements
8
9### Requirement: Unterstützte UI-Sprachen
10
11Die App MUST genau die UI-Sprachen Englisch und Deutsch anbieten. Deutsch MUST Deutschland-Orthografie im sichtbaren Produkttext verwenden.
12
13#### Scenario: Sprachenwahl zeigt DE und EN
14
15- **WHEN** der Nutzer die UI-Spracheinstellung öffnet
16- **THEN** stehen Englisch und Deutsch zur Auswahl
17- **AND** keine weitere UI-Sprache ist wählbar
18
19### Requirement: Erster Start folgt der OS-Locale
20
21Ohne gespeicherte UI-Spracheinstellung MUST die App die System-Locale auswerten: beginnt die Locale mit `de`, MUST die UI Deutsch sein; sonst MUST sie Englisch sein.
22
23#### Scenario: System Deutsch
24
25- **GIVEN** es existiert noch keine gespeicherte UI-Sprache
26- **WHEN** die App startet und die System-Locale mit `de` beginnt
27- **THEN** zeigt die App ihre Oberflächentexte auf Deutsch
28
29#### Scenario: System nicht Deutsch
30
31- **GIVEN** es existiert noch keine gespeicherte UI-Sprache
32- **WHEN** die App startet und die System-Locale nicht mit `de` beginnt
33- **THEN** zeigt die App ihre Oberflächentexte auf Englisch
34
35### Requirement: Nutzerwahl überschreibt und persistiert
36
37Der Nutzer MUST die UI-Sprache in den Einstellungen auf Englisch oder Deutsch setzen können. Die Wahl MUST gespeichert werden und MUST bei späteren Starts gelten, unabhängig von der dann aktuellen System-Locale.
38
39#### Scenario: Explizit Deutsch speichern
40
41- **WHEN** der Nutzer die UI-Sprache auf Deutsch setzt
42- **THEN** zeigt die App Deutsch
43- **AND** nach Neustart der App bleibt Deutsch aktiv, auch wenn die System-Locale nicht mit `de` beginnt
44
45#### Scenario: Explizit Englisch speichern
46
47- **WHEN** der Nutzer die UI-Sprache auf Englisch setzt
48- **THEN** zeigt die App Englisch
49- **AND** nach Neustart bleibt Englisch aktiv, auch wenn die System-Locale mit `de` beginnt
50
51### Requirement: Umschalten ohne Neustart
52
53Ändert der Nutzer die UI-Sprache, MUST die sichtbare Oberfläche die neue Sprache annehmen, ohne dass die App beendet werden muss.
54
55#### Scenario: Wechsel in den Einstellungen
56
57- **WHEN** der Nutzer in einer laufenden Sitzung von Englisch auf Deutsch wechselt
58- **THEN** erscheinen Navigation, Einstellungen und Dialoge in Deutsch
59- **AND** die Sitzung bleibt geöffnet
60
61### Requirement: Gesamte produktseitige UI ist lokalisiert
62
63Alle von der App selbst stammenden Oberflächentexte MUST in der aktiven UI-Sprache erscheinen. Das umfasst Navigation, Einstellungen, Dialoge, Menüs, Tooltips, Tastaturkürzel-Beschriftungen, Toasts, Tray-Menü, Agent-UI und Nutzerhinweise aus Gesprächen und Fehlersituationen.
64
65#### Scenario: Settings und Chrome
66
67- **WHEN** die UI-Sprache Deutsch ist
68- **THEN** sind Einstellungsnavigation, Rail und häufige Dialogaktionen (etwa Abbrechen und Speichern) auf Deutsch
69
70#### Scenario: Call-Hinweis
71
72- **WHEN** die UI-Sprache Deutsch ist und ein lokal erzeugter Call-Hinweis angezeigt wird
73- **THEN** erscheint der Hinweistext auf Deutsch
74
75#### Scenario: Tray
76
77- **WHEN** die UI-Sprache Deutsch ist und der Nutzer das Tray-Menü öffnet
78- **THEN** sind die Menüeinträge auf Deutsch
79
80### Requirement: Fehlende Übersetzung fällt auf Englisch zurück
81
82Fehlt für einen UI-Text die Übersetzung in der aktiven Sprache, MUST die App den englischen Text zeigen statt eines leeren Labels oder eines rohen Schlüssels.
83
84#### Scenario: Fehlender Key unter Deutsch
85
86- **WHEN** die UI-Sprache Deutsch ist und für einen UI-Text keine deutsche Übersetzung vorliegt
87- **THEN** zeigt die App den englischen Text für diesen Eintrag
88- **AND** die übrigen lokalisierten Texte bleiben auf Deutsch
89
90### Requirement: Fremder Content bleibt unverändert
91
92Server- und Nutzerinhalte MUST die UI-Locale nicht ersetzen. Message-Translation, Captions-Spoken-Language, Adaptive-Card-Titel vom Server und Gerätenamen vom Betriebssystem bleiben eigene Pfade.
93
94#### Scenario: Chat-Nachricht
95
96- **WHEN** die UI-Sprache Deutsch ist und eine englische Chat-Nachricht angezeigt wird
97- **THEN** bleibt der Nachrichteninhalt Englisch
98- **AND** die umgebenden App-Steuerelemente sind Deutsch
99
100#### Scenario: Message-Translation unverändert
101
102- **WHEN** der Nutzer Message-Translation nutzt
103- **THEN** gilt weiterhin die bestehende Translation-Einstellung
104- **AND** die UI-Locale ersetzt diese Einstellung nicht
openspec/changes/archive/2026-11-12-ui-locale-de-en/tasks.md added +33 −0
@@ -0,0 +1,33 @@
1 # Tasks
2
3 ## 1. Locale-Gerüst
4
5 - [x] 1.1 App-Katalog `en`/`de` mit `rust-i18n` (eigener Katalog, Fallback `en`) und Start-Hook anbinden; `gpui-component`/`gpui_kit` `set_locale` mitziehen. Prüfen mit `cargo test -p app --lib ui_locale` (oder schmalerer Filter sobald Modul steht).
6 - [x] 1.2 Preference `auto`|`en`|`de` laden/speichern (Store-Meta analog Appearance) und effektive Locale aus OS ableiten (`de*` → `de`, sonst `en`). Prüfen mit `cargo test -p app-base --lib ui_locale` bzw. dem Crate, das die Preference hält.
7 - [x] 1.3 Settings-Steuerung für UI-Sprache (inkl. Kennzeichnung bei `auto`); Wechsel setzt Locale live und persistiert. Prüfen mit `cargo test -p app --lib ui_locale_settings`.
8
9 ## 2. Chrome und Settings
10
11 - [x] 2.1 Rail, Sidebar-Tabs und Settings-Navigation/Suchbegriffe über Locale-Lookup. Prüfen: sichtbare Labels unter Locale `de` und `en` in `cargo test -p app --lib ui_locale_chrome`.
12 - [x] 2.2 Häufige Dialogaktionen und Settings-Abschnitte General/Appearance/Notifications auf Katalog umstellen. Prüfen mit `cargo test -p app --lib ui_locale_settings`.
13
14 ## 3. Kernflächen
15
16 - [x] 3.1 Chat-/Conversation-UI (Composer-Hinweise, Menüs, Tooltips) lokalisieren. Prüfen mit `cargo test -p app --lib ui_locale_chat`.
17 - [x] 3.2 Call-UI (Controls, Prejoin, Layout-Hinweise, Tooltips) lokalisieren. Prüfen mit `cargo test -p app --lib ui_locale_call`.
18 - [x] 3.3 Calendar- und übrige Dialoge der Kernflächen lokalisieren. Prüfen mit `cargo test -p app --lib ui_locale_calendar`.
19
20 ## 4. Notices, Tray, Agents, Rest
21
22 - [x] 4.1 Stabile Notice-IDs (plus Args) in `calling`/`app-state` statt englischer Notice-Literale; UI löst Texte auf. Prüfen mit `cargo test -p calling --lib notice_id` und `cargo test -p app --lib ui_locale_notice`.
23 - [x] 4.2 Tray-Menü, Toasts, Fenster-Titel und Agent-UI lokalisieren; nach Locale-Wechsel Tray neu syncen. Prüfen mit `cargo test -p app --lib ui_locale_tray`.
24 - [x] 4.3 Restliche produktseitige Nutzertexte (Shortcuts-Beschriftungen, verbleibende Fehlerhinweise) abdecken; fehlende DE-Keys fallen auf EN zurück. Prüfen mit `cargo test -p app --lib ui_locale_fallback`.
25
26 ## 5. Zusammenspiel
27
28 - [x] 5.1 `cargo test -p app --lib ui_locale`, `cargo test -p calling --lib notice_id` und die Preference-Tests der Phase 1 gemeinsam grün.
29 - [x] 5.2 Manuell: frische Daten ohne Meta → System `de*` zeigt DE; Override EN überlebt Neustart; Wechsel DE↔EN ohne App-Neustart; ein Call-Hinweis und das Tray-Menü folgen der Locale. Chat-Nachrichteninhalt bleibt unverändert.
30
31 ## Workflow follow-up
32
33 - Nach Umsetzen mit `/opsx-apply` und Review den Change archivieren (`/opsx-archive`), damit `ui-locale` unter `openspec/specs/` landet.
@@ -0,0 +1,33 @@
1# Tasks
2
3## 1. Locale-Gerüst
4
5- [x] 1.1 App-Katalog `en`/`de` mit `rust-i18n` (eigener Katalog, Fallback `en`) und Start-Hook anbinden; `gpui-component`/`gpui_kit` `set_locale` mitziehen. Prüfen mit `cargo test -p app --lib ui_locale` (oder schmalerer Filter sobald Modul steht).
6- [x] 1.2 Preference `auto`|`en`|`de` laden/speichern (Store-Meta analog Appearance) und effektive Locale aus OS ableiten (`de*` → `de`, sonst `en`). Prüfen mit `cargo test -p app-base --lib ui_locale` bzw. dem Crate, das die Preference hält.
7- [x] 1.3 Settings-Steuerung für UI-Sprache (inkl. Kennzeichnung bei `auto`); Wechsel setzt Locale live und persistiert. Prüfen mit `cargo test -p app --lib ui_locale_settings`.
8
9## 2. Chrome und Settings
10
11- [x] 2.1 Rail, Sidebar-Tabs und Settings-Navigation/Suchbegriffe über Locale-Lookup. Prüfen: sichtbare Labels unter Locale `de` und `en` in `cargo test -p app --lib ui_locale_chrome`.
12- [x] 2.2 Häufige Dialogaktionen und Settings-Abschnitte General/Appearance/Notifications auf Katalog umstellen. Prüfen mit `cargo test -p app --lib ui_locale_settings`.
13
14## 3. Kernflächen
15
16- [x] 3.1 Chat-/Conversation-UI (Composer-Hinweise, Menüs, Tooltips) lokalisieren. Prüfen mit `cargo test -p app --lib ui_locale_chat`.
17- [x] 3.2 Call-UI (Controls, Prejoin, Layout-Hinweise, Tooltips) lokalisieren. Prüfen mit `cargo test -p app --lib ui_locale_call`.
18- [x] 3.3 Calendar- und übrige Dialoge der Kernflächen lokalisieren. Prüfen mit `cargo test -p app --lib ui_locale_calendar`.
19
20## 4. Notices, Tray, Agents, Rest
21
22- [x] 4.1 Stabile Notice-IDs (plus Args) in `calling`/`app-state` statt englischer Notice-Literale; UI löst Texte auf. Prüfen mit `cargo test -p calling --lib notice_id` und `cargo test -p app --lib ui_locale_notice`.
23- [x] 4.2 Tray-Menü, Toasts, Fenster-Titel und Agent-UI lokalisieren; nach Locale-Wechsel Tray neu syncen. Prüfen mit `cargo test -p app --lib ui_locale_tray`.
24- [x] 4.3 Restliche produktseitige Nutzertexte (Shortcuts-Beschriftungen, verbleibende Fehlerhinweise) abdecken; fehlende DE-Keys fallen auf EN zurück. Prüfen mit `cargo test -p app --lib ui_locale_fallback`.
25
26## 5. Zusammenspiel
27
28- [x] 5.1 `cargo test -p app --lib ui_locale`, `cargo test -p calling --lib notice_id` und die Preference-Tests der Phase 1 gemeinsam grün.
29- [x] 5.2 Manuell: frische Daten ohne Meta → System `de*` zeigt DE; Override EN überlebt Neustart; Wechsel DE↔EN ohne App-Neustart; ein Call-Hinweis und das Tray-Menü folgen der Locale. Chat-Nachrichteninhalt bleibt unverändert.
30
31## Workflow follow-up
32
33- Nach Umsetzen mit `/opsx-apply` und Review den Change archivieren (`/opsx-archive`), damit `ui-locale` unter `openspec/specs/` landet.
openspec/specs/ui-locale/spec.md added +103 −0
@@ -0,0 +1,103 @@
1 # ui-locale Specification
2
3 ## Purpose
4 Steuert die Sprache der App-Oberfläche: Ableitung aus der System-Locale beim ersten Start, dauerhafte Nutzerwahl und Anwendung auf alle produktseitigen UI-Texte in Englisch und Deutsch.
5
6 ## Requirements
7
8 ### Requirement: Unterstützte UI-Sprachen
9
10 Die App MUST genau die UI-Sprachen Englisch und Deutsch anbieten. Deutsch MUST Deutschland-Orthografie im sichtbaren Produkttext verwenden.
11
12 #### Scenario: Sprachenwahl zeigt DE und EN
13
14 - **WHEN** der Nutzer die UI-Spracheinstellung öffnet
15 - **THEN** stehen Englisch und Deutsch zur Auswahl
16 - **AND** keine weitere UI-Sprache ist wählbar
17
18 ### Requirement: Erster Start folgt der OS-Locale
19
20 Ohne gespeicherte UI-Spracheinstellung MUST die App die System-Locale auswerten: beginnt die Locale mit `de`, MUST die UI Deutsch sein; sonst MUST sie Englisch sein.
21
22 #### Scenario: System Deutsch
23
24 - **GIVEN** es existiert noch keine gespeicherte UI-Sprache
25 - **WHEN** die App startet und die System-Locale mit `de` beginnt
26 - **THEN** zeigt die App ihre Oberflächentexte auf Deutsch
27
28 #### Scenario: System nicht Deutsch
29
30 - **GIVEN** es existiert noch keine gespeicherte UI-Sprache
31 - **WHEN** die App startet und die System-Locale nicht mit `de` beginnt
32 - **THEN** zeigt die App ihre Oberflächentexte auf Englisch
33
34 ### Requirement: Nutzerwahl überschreibt und persistiert
35
36 Der Nutzer MUST die UI-Sprache in den Einstellungen auf Englisch oder Deutsch setzen können. Die Wahl MUST gespeichert werden und MUST bei späteren Starts gelten, unabhängig von der dann aktuellen System-Locale.
37
38 #### Scenario: Explizit Deutsch speichern
39
40 - **WHEN** der Nutzer die UI-Sprache auf Deutsch setzt
41 - **THEN** zeigt die App Deutsch
42 - **AND** nach Neustart der App bleibt Deutsch aktiv, auch wenn die System-Locale nicht mit `de` beginnt
43
44 #### Scenario: Explizit Englisch speichern
45
46 - **WHEN** der Nutzer die UI-Sprache auf Englisch setzt
47 - **THEN** zeigt die App Englisch
48 - **AND** nach Neustart bleibt Englisch aktiv, auch wenn die System-Locale mit `de` beginnt
49
50 ### Requirement: Umschalten ohne Neustart
51
52 Ändert der Nutzer die UI-Sprache, MUST die sichtbare Oberfläche die neue Sprache annehmen, ohne dass die App beendet werden muss.
53
54 #### Scenario: Wechsel in den Einstellungen
55
56 - **WHEN** der Nutzer in einer laufenden Sitzung von Englisch auf Deutsch wechselt
57 - **THEN** erscheinen Navigation, Einstellungen und Dialoge in Deutsch
58 - **AND** die Sitzung bleibt geöffnet
59
60 ### Requirement: Gesamte produktseitige UI ist lokalisiert
61
62 Alle von der App selbst stammenden Oberflächentexte MUST in der aktiven UI-Sprache erscheinen. Das umfasst Navigation, Einstellungen, Dialoge, Menüs, Tooltips, Tastaturkürzel-Beschriftungen, Toasts, Tray-Menü, Agent-UI und Nutzerhinweise aus Gesprächen und Fehlersituationen.
63
64 #### Scenario: Settings und Chrome
65
66 - **WHEN** die UI-Sprache Deutsch ist
67 - **THEN** sind Einstellungsnavigation, Rail und häufige Dialogaktionen (etwa Abbrechen und Speichern) auf Deutsch
68
69 #### Scenario: Call-Hinweis
70
71 - **WHEN** die UI-Sprache Deutsch ist und ein lokal erzeugter Call-Hinweis angezeigt wird
72 - **THEN** erscheint der Hinweistext auf Deutsch
73
74 #### Scenario: Tray
75
76 - **WHEN** die UI-Sprache Deutsch ist und der Nutzer das Tray-Menü öffnet
77 - **THEN** sind die Menüeinträge auf Deutsch
78
79 ### Requirement: Fehlende Übersetzung fällt auf Englisch zurück
80
81 Fehlt für einen UI-Text die Übersetzung in der aktiven Sprache, MUST die App den englischen Text zeigen statt eines leeren Labels oder eines rohen Schlüssels.
82
83 #### Scenario: Fehlender Key unter Deutsch
84
85 - **WHEN** die UI-Sprache Deutsch ist und für einen UI-Text keine deutsche Übersetzung vorliegt
86 - **THEN** zeigt die App den englischen Text für diesen Eintrag
87 - **AND** die übrigen lokalisierten Texte bleiben auf Deutsch
88
89 ### Requirement: Fremder Content bleibt unverändert
90
91 Server- und Nutzerinhalte MUST die UI-Locale nicht ersetzen. Message-Translation, Captions-Spoken-Language, Adaptive-Card-Titel vom Server und Gerätenamen vom Betriebssystem bleiben eigene Pfade.
92
93 #### Scenario: Chat-Nachricht
94
95 - **WHEN** die UI-Sprache Deutsch ist und eine englische Chat-Nachricht angezeigt wird
96 - **THEN** bleibt der Nachrichteninhalt Englisch
97 - **AND** die umgebenden App-Steuerelemente sind Deutsch
98
99 #### Scenario: Message-Translation unverändert
100
101 - **WHEN** der Nutzer Message-Translation nutzt
102 - **THEN** gilt weiterhin die bestehende Translation-Einstellung
103 - **AND** die UI-Locale ersetzt diese Einstellung nicht
@@ -0,0 +1,103 @@
1# ui-locale Specification
2
3## Purpose
4Steuert die Sprache der App-Oberfläche: Ableitung aus der System-Locale beim ersten Start, dauerhafte Nutzerwahl und Anwendung auf alle produktseitigen UI-Texte in Englisch und Deutsch.
5
6## Requirements
7
8### Requirement: Unterstützte UI-Sprachen
9
10Die App MUST genau die UI-Sprachen Englisch und Deutsch anbieten. Deutsch MUST Deutschland-Orthografie im sichtbaren Produkttext verwenden.
11
12#### Scenario: Sprachenwahl zeigt DE und EN
13
14- **WHEN** der Nutzer die UI-Spracheinstellung öffnet
15- **THEN** stehen Englisch und Deutsch zur Auswahl
16- **AND** keine weitere UI-Sprache ist wählbar
17
18### Requirement: Erster Start folgt der OS-Locale
19
20Ohne gespeicherte UI-Spracheinstellung MUST die App die System-Locale auswerten: beginnt die Locale mit `de`, MUST die UI Deutsch sein; sonst MUST sie Englisch sein.
21
22#### Scenario: System Deutsch
23
24- **GIVEN** es existiert noch keine gespeicherte UI-Sprache
25- **WHEN** die App startet und die System-Locale mit `de` beginnt
26- **THEN** zeigt die App ihre Oberflächentexte auf Deutsch
27
28#### Scenario: System nicht Deutsch
29
30- **GIVEN** es existiert noch keine gespeicherte UI-Sprache
31- **WHEN** die App startet und die System-Locale nicht mit `de` beginnt
32- **THEN** zeigt die App ihre Oberflächentexte auf Englisch
33
34### Requirement: Nutzerwahl überschreibt und persistiert
35
36Der Nutzer MUST die UI-Sprache in den Einstellungen auf Englisch oder Deutsch setzen können. Die Wahl MUST gespeichert werden und MUST bei späteren Starts gelten, unabhängig von der dann aktuellen System-Locale.
37
38#### Scenario: Explizit Deutsch speichern
39
40- **WHEN** der Nutzer die UI-Sprache auf Deutsch setzt
41- **THEN** zeigt die App Deutsch
42- **AND** nach Neustart der App bleibt Deutsch aktiv, auch wenn die System-Locale nicht mit `de` beginnt
43
44#### Scenario: Explizit Englisch speichern
45
46- **WHEN** der Nutzer die UI-Sprache auf Englisch setzt
47- **THEN** zeigt die App Englisch
48- **AND** nach Neustart bleibt Englisch aktiv, auch wenn die System-Locale mit `de` beginnt
49
50### Requirement: Umschalten ohne Neustart
51
52Ändert der Nutzer die UI-Sprache, MUST die sichtbare Oberfläche die neue Sprache annehmen, ohne dass die App beendet werden muss.
53
54#### Scenario: Wechsel in den Einstellungen
55
56- **WHEN** der Nutzer in einer laufenden Sitzung von Englisch auf Deutsch wechselt
57- **THEN** erscheinen Navigation, Einstellungen und Dialoge in Deutsch
58- **AND** die Sitzung bleibt geöffnet
59
60### Requirement: Gesamte produktseitige UI ist lokalisiert
61
62Alle von der App selbst stammenden Oberflächentexte MUST in der aktiven UI-Sprache erscheinen. Das umfasst Navigation, Einstellungen, Dialoge, Menüs, Tooltips, Tastaturkürzel-Beschriftungen, Toasts, Tray-Menü, Agent-UI und Nutzerhinweise aus Gesprächen und Fehlersituationen.
63
64#### Scenario: Settings und Chrome
65
66- **WHEN** die UI-Sprache Deutsch ist
67- **THEN** sind Einstellungsnavigation, Rail und häufige Dialogaktionen (etwa Abbrechen und Speichern) auf Deutsch
68
69#### Scenario: Call-Hinweis
70
71- **WHEN** die UI-Sprache Deutsch ist und ein lokal erzeugter Call-Hinweis angezeigt wird
72- **THEN** erscheint der Hinweistext auf Deutsch
73
74#### Scenario: Tray
75
76- **WHEN** die UI-Sprache Deutsch ist und der Nutzer das Tray-Menü öffnet
77- **THEN** sind die Menüeinträge auf Deutsch
78
79### Requirement: Fehlende Übersetzung fällt auf Englisch zurück
80
81Fehlt für einen UI-Text die Übersetzung in der aktiven Sprache, MUST die App den englischen Text zeigen statt eines leeren Labels oder eines rohen Schlüssels.
82
83#### Scenario: Fehlender Key unter Deutsch
84
85- **WHEN** die UI-Sprache Deutsch ist und für einen UI-Text keine deutsche Übersetzung vorliegt
86- **THEN** zeigt die App den englischen Text für diesen Eintrag
87- **AND** die übrigen lokalisierten Texte bleiben auf Deutsch
88
89### Requirement: Fremder Content bleibt unverändert
90
91Server- und Nutzerinhalte MUST die UI-Locale nicht ersetzen. Message-Translation, Captions-Spoken-Language, Adaptive-Card-Titel vom Server und Gerätenamen vom Betriebssystem bleiben eigene Pfade.
92
93#### Scenario: Chat-Nachricht
94
95- **WHEN** die UI-Sprache Deutsch ist und eine englische Chat-Nachricht angezeigt wird
96- **THEN** bleibt der Nachrichteninhalt Englisch
97- **AND** die umgebenden App-Steuerelemente sind Deutsch
98
99#### Scenario: Message-Translation unverändert
100
101- **WHEN** der Nutzer Message-Translation nutzt
102- **THEN** gilt weiterhin die bestehende Translation-Einstellung
103- **AND** die UI-Locale ersetzt diese Einstellung nicht