BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / views / prejoin_view.rs

prejoin_view.rs

prejoin_view.rs 19.0 KiB Download Raw
1use std::time::{Duration, Instant};
2
3use calling::camera::list_cameras;
4use calling::devices::{AudioDevice, DeviceLists, list_devices, shared_factory};
5use calling::{DeviceChoice, DeviceEntry, camera_entries};
6use gpui_kit::assets::IconName;
7use gpui_kit::component::Disableable as _;
8use gpui_kit::component::button::{Button, ButtonVariants as _};
9use gpui_kit::component::menu::{DropdownMenu as _, PopupMenu};
10use gpui_kit::component::{h_flex, v_flex};
11use gpui_kit::prelude::FluentBuilder as _;
12use gpui_kit::*;
13
14use super::avatar::person_avatar;
15use super::call_extras::{BackgroundMenu, background_items};
16use super::call_view::{device_items, round_control};
17use crate::app_state::AppState;
18use crate::call::{AudioChoice, CameraPreview, JoinOptions, PendingJoin};
19use crate::theme;
20
21const CONTENT_WIDTH: f32 = 560.;
22const PREVIEW_HEIGHT: f32 = 315.;
23const PREVIEW_RADIUS: f32 = 12.;
24const AVATAR_SIZE: f32 = 96.;
25const SELECT_WIDTH: f32 = 176.;
26const SECTION_GAP: f32 = 12.;
27const PANE_PADDING: f32 = 12.;
28const PREVIEW_MIN_HEIGHT: f32 = 60.;
29const FRAME_TICK: Duration = Duration::from_millis(100);
30const FPS_TICK: Duration = Duration::from_millis(500);
31const CAMERA_OFF_TEXT: &str = "Your camera is off";
32const DEFAULT_LABEL: &str = "Default device";
33const DEMO_MICROPHONES: [&str; 2] = ["Headset microphone", "Laptop microphone"];
34const DEMO_SPEAKERS: [&str; 2] = ["Headset earphones", "Laptop speakers"];
35
36pub struct PrejoinView {
37 app: Entity<AppState>,
38 pending_id: u64,
39 demo: bool,
40 preview: CameraPreview,
41 options: JoinOptions,
42 cameras: Vec<DeviceEntry>,
43 devices: DeviceLists,
44 camera: DeviceChoice,
45 applied_background: crate::call::BackgroundPick,
46 tick: u32,
47 _subscription: Subscription,
48 _release: Subscription,
49}
50
51struct DeviceSelect {
52 id: &'static str,
53 label: &'static str,
54 entries: Vec<DeviceEntry>,
55 current: DeviceChoice,
56 enabled: bool,
57}
58
59fn demo_devices() -> DeviceLists {
60 let device = |index: u16, name: &str| AudioDevice {
61 index,
62 guid: format!("demo-{name}"),
63 name: name.to_owned(),
64 };
65 DeviceLists {
66 inputs: DEMO_MICROPHONES
67 .iter()
68 .enumerate()
69 .map(|(index, name)| device(index as u16, name))
70 .collect(),
71 outputs: DEMO_SPEAKERS
72 .iter()
73 .enumerate()
74 .map(|(index, name)| device(index as u16, name))
75 .collect(),
76 }
77}
78
79fn label_of(entries: &[DeviceEntry], choice: &DeviceChoice) -> String {
80 entries
81 .iter()
82 .find(|entry| &entry.choice == choice)
83 .map_or_else(|| DEFAULT_LABEL.to_owned(), |entry| entry.label.clone())
84}
85
86impl PrejoinView {
87 pub fn new(
88 app: Entity<AppState>,
89 pending: &PendingJoin,
90 _window: &mut Window,
91 cx: &mut Context<Self>,
92 ) -> Self {
93 let subscription = cx.observe(&app, |view, _, cx| view.sync_background(cx));
94 let release = cx.on_release(|view, cx| view.preview.stop(cx));
95 let (preview, mut updates) = CameraPreview::new();
96 let state = app.read(cx);
97 let demo = state.mode.demo;
98 let mut options = state.join_options.clone();
99 options.camera_on = options.camera_on && !state.mode.read_only;
100 let camera = state.call_camera.clone();
101 let mut view = PrejoinView {
102 pending_id: pending.id,
103 demo,
104 preview,
105 options,
106 cameras: camera_entries(&[]),
107 devices: if demo {
108 demo_devices()
109 } else {
110 DeviceLists::default()
111 },
112 camera,
113 applied_background: crate::call::BackgroundPick::None,
114 tick: 0,
115 _subscription: subscription,
116 _release: release,
117 app,
118 };
119 cx.spawn(async move |this, cx| {
120 while updates.recv().await.is_some() {
121 if this.update(cx, |view, cx| view.take_frames(cx)).is_err() {
122 return;
123 }
124 }
125 })
126 .detach();
127 cx.spawn(async move |this, cx| {
128 loop {
129 cx.background_executor().timer(FPS_TICK).await;
130 if this
131 .update(cx, |view, cx| {
132 view.preview.tick(Instant::now());
133 cx.notify();
134 })
135 .is_err()
136 {
137 break;
138 }
139 }
140 })
141 .detach();
142 if demo {
143 cx.spawn(async move |this, cx| {
144 loop {
145 cx.background_executor().timer(FRAME_TICK).await;
146 if this.update(cx, |view, cx| view.demo_frame(cx)).is_err() {
147 break;
148 }
149 }
150 })
151 .detach();
152 } else {
153 view.load_devices(cx);
154 }
155 view.sync_background(cx);
156 view.restart_preview();
157 view
158 }
159
160 pub fn pending_id(&self) -> u64 {
161 self.pending_id
162 }
163
164 fn take_frames(&mut self, cx: &mut Context<Self>) {
165 self.preview.take_frames(cx);
166 cx.notify();
167 }
168
169 fn demo_frame(&mut self, cx: &mut Context<Self>) {
170 if self.options.camera_on {
171 self.tick = self.tick.wrapping_add(1);
172 self.preview.publish_demo_frame(self.tick);
173 self.take_frames(cx);
174 }
175 }
176
177 fn load_devices(&mut self, cx: &mut Context<Self>) {
178 cx.spawn(async move |this, cx| {
179 let (cameras, devices) = cx
180 .background_executor()
181 .spawn(async { (list_cameras(), list_devices(&shared_factory())) })
182 .await;
183 this.update(cx, |view, cx| {
184 view.cameras = camera_entries(&cameras);
185 view.devices = devices;
186 cx.notify();
187 })
188 .ok();
189 })
190 .detach();
191 }
192
193 fn restart_preview(&mut self) {
194 if self.options.camera_on && !self.demo {
195 self.preview.start(&self.camera);
196 }
197 }
198
199 fn sync_background(&mut self, cx: &mut Context<Self>) {
200 let state = self.app.read(cx);
201 let pick = state.call_background.clone();
202 if pick == self.applied_background {
203 return;
204 }
205 if let Some(choice) = state.call_backgrounds.choice_for(&pick) {
206 self.preview.set_background(choice);
207 self.applied_background = pick;
208 }
209 cx.notify();
210 }
211
212 fn toggle_camera(&mut self, cx: &mut Context<Self>) {
213 self.options.camera_on = !self.options.camera_on;
214 if self.options.camera_on {
215 self.restart_preview();
216 } else {
217 self.preview.stop(cx);
218 }
219 cx.notify();
220 }
221
222 fn toggle_mic(&mut self, cx: &mut Context<Self>) {
223 self.options.mic_on = !self.options.mic_on;
224 cx.notify();
225 }
226
227 fn set_audio(&mut self, audio: AudioChoice, cx: &mut Context<Self>) {
228 self.options.audio = audio;
229 cx.notify();
230 }
231
232 fn pick_camera(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
233 self.camera = choice.clone();
234 self.app
235 .update(cx, |state, cx| state.select_call_camera(choice, cx));
236 self.restart_preview();
237 cx.notify();
238 }
239
240 fn pick_input(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
241 self.options.input = choice;
242 cx.notify();
243 }
244
245 fn pick_output(&mut self, choice: DeviceChoice, cx: &mut Context<Self>) {
246 self.options.output = choice;
247 cx.notify();
248 }
249
250 fn join(&mut self, cx: &mut Context<Self>) {
251 self.preview.stop(cx);
252 let options = self.options.clone();
253 self.app
254 .update(cx, |state, cx| state.confirm_prejoin(options, cx));
255 }
256
257 fn cancel(&mut self, cx: &mut Context<Self>) {
258 self.app.update(cx, |state, cx| state.cancel_prejoin(cx));
259 }
260
261 fn preview_status(&self) -> String {
262 match self.preview.failure() {
263 Some(reason) => format!("Camera could not start: {reason}"),
264 None => "Starting camera...".to_owned(),
265 }
266 }
267
268 fn preview_box(&self, cx: &mut Context<Self>) -> Div {
269 let state = self.app.read(cx);
270 let image = self
271 .options
272 .camera_on
273 .then(|| self.preview.image(Instant::now()))
274 .flatten();
275 let me = state.directory.me.clone();
276 let face = match (&image, self.options.camera_on) {
277 (Some(image), _) => img(ImageSource::Render(image.clone()))
278 .size_full()
279 .object_fit(ObjectFit::Cover)
280 .into_any_element(),
281 (None, true) => centered_note(&self.preview_status()),
282 (None, false) => v_flex()
283 .items_center()
284 .gap(px(10.))
285 .child(person_avatar(
286 &state.directory,
287 me.as_ref().map(|me| me.user_id.as_str()),
288 me.as_ref().map_or("You", |me| me.display_name.as_str()),
289 AVATAR_SIZE,
290 ))
291 .child(
292 div()
293 .text_size(px(13.))
294 .text_color(theme::text_muted())
295 .child(CAMERA_OFF_TEXT),
296 )
297 .into_any_element(),
298 };
299 div()
300 .debug_selector(|| "shell/islands/main/prejoin/preview".into())
301 .relative()
302 .w_full()
303 .h(px(PREVIEW_HEIGHT))
304 .flex_shrink(1.)
305 .min_h(px(PREVIEW_MIN_HEIGHT))
306 .flex()
307 .items_center()
308 .justify_center()
309 .overflow_hidden()
310 .rounded(px(PREVIEW_RADIUS))
311 .bg(theme::background())
312 .child(face)
313 }
314
315 fn controls(&self, cx: &mut Context<Self>) -> impl IntoElement {
316 let view = cx.entity();
317 let camera_view = view.clone();
318 let mic_view = view.clone();
319 let (camera_glyph, camera_bg, camera_fg) = if self.options.camera_on {
320 (IconName::Video, theme::accent(), theme::on_accent())
321 } else {
322 (IconName::VideoOff, theme::surface_raised(), theme::text())
323 };
324 let (mic_glyph, mic_bg, mic_fg) = if self.options.mic_on {
325 (IconName::Mic, theme::surface_raised(), theme::text())
326 } else {
327 (IconName::MicOff, theme::red(), theme::white())
328 };
329 let audio_on = self.options.audio == AudioChoice::Computer;
330 let backgrounds = BackgroundMenu::of(self.app.read(cx));
331 let background_app = self.app.clone();
332 h_flex()
333 .debug_selector(|| "shell/islands/main/prejoin/controls".into())
334 .flex_none()
335 .gap(px(10.))
336 .items_center()
337 .justify_center()
338 .child(
339 round_control("prejoin-camera", camera_glyph, camera_bg, camera_fg).on_click(
340 move |_, _, cx| camera_view.update(cx, |view, cx| view.toggle_camera(cx)),
341 ),
342 )
343 .child(
344 round_control("prejoin-mic", mic_glyph, mic_bg, mic_fg)
345 .when(!audio_on, |button| button.opacity(0.4).cursor_default())
346 .when(audio_on, |button| {
347 button.on_click(move |_, _, cx| {
348 mic_view.update(cx, |view, cx| view.toggle_mic(cx))
349 })
350 }),
351 )
352 .child(
353 Button::new("prejoin-background")
354 .outline()
355 .label("Background")
356 .icon(IconName::ChevronDown)
357 .dropdown_menu(move |menu: PopupMenu, _, _| {
358 background_items(menu, &background_app, &backgrounds)
359 }),
360 )
361 }
362
363 fn select(
364 &self,
365 spec: DeviceSelect,
366 pick: impl Fn(&mut PrejoinView, DeviceChoice, &mut Context<PrejoinView>) + Clone + 'static,
367 cx: &mut Context<Self>,
368 ) -> Div {
369 let DeviceSelect {
370 id,
371 label,
372 entries,
373 current,
374 enabled,
375 } = spec;
376 let view = cx.entity();
377 let face = label_of(&entries, &current);
378 let items_entries = entries;
379 let items_current = current;
380 let button = Button::new(id)
381 .outline()
382 .w_full()
383 .label(face)
384 .icon(IconName::ChevronDown)
385 .disabled(!enabled)
386 .dropdown_menu(move |menu, _, _| {
387 let view = view.clone();
388 let pick = pick.clone();
389 device_items(items_entries.clone(), &items_current, move |choice, cx| {
390 let pick = pick.clone();
391 view.update(cx, |view, cx| pick(view, choice, cx));
392 })
393 .into_iter()
394 .fold(menu, |menu, item| menu.item(item))
395 });
396 v_flex()
397 .flex_1()
398 .min_w_0()
399 .max_w(px(SELECT_WIDTH))
400 .gap(px(4.))
401 .child(
402 div()
403 .text_size(px(12.))
404 .text_color(theme::text_muted())
405 .child(label),
406 )
407 .child(div().w_full().overflow_hidden().child(button))
408 }
409
410 fn audio_choice(&self, choice: AudioChoice, cx: &mut Context<Self>) -> Stateful<Div> {
411 let selected = self.options.audio == choice;
412 let view = cx.entity();
413 h_flex()
414 .id(match choice {
415 AudioChoice::Computer => "prejoin-audio-computer",
416 AudioChoice::NoAudio => "prejoin-audio-none",
417 })
418 .h(px(32.))
419 .px(px(14.))
420 .items_center()
421 .rounded(px(8.))
422 .border_1()
423 .border_color(if selected {
424 theme::accent()
425 } else {
426 theme::border_strong()
427 })
428 .when(selected, |option| option.bg(theme::surface_raised()))
429 .cursor_pointer()
430 .text_size(px(13.))
431 .text_color(theme::text())
432 .child(choice.label())
433 .on_click(move |_, _, cx| view.update(cx, |view, cx| view.set_audio(choice, cx)))
434 }
435}
436
437fn centered_note(text: &str) -> AnyElement {
438 div()
439 .text_size(px(13.))
440 .text_color(theme::text_muted())
441 .child(text.to_owned())
442 .into_any_element()
443}
444
445impl Render for PrejoinView {
446 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
447 let title = self
448 .app
449 .read(cx)
450 .prejoin
451 .as_ref()
452 .map(|pending| pending.join.title.clone())
453 .unwrap_or_default();
454 let audio_on = self.options.audio == AudioChoice::Computer;
455 let (cameras, camera) = (self.cameras.clone(), self.camera.clone());
456 let (inputs, input) = (self.devices.input_entries(), self.options.input.clone());
457 let (outputs, output) = (self.devices.output_entries(), self.options.output.clone());
458 let devices = h_flex()
459 .debug_selector(|| "shell/islands/main/prejoin/devices".into())
460 .flex_none()
461 .w_full()
462 .gap(px(10.))
463 .child(self.select(
464 DeviceSelect {
465 id: "prejoin-camera-select",
466 label: "Camera",
467 entries: cameras,
468 current: camera,
469 enabled: true,
470 },
471 |view, choice, cx| view.pick_camera(choice, cx),
472 cx,
473 ))
474 .child(self.select(
475 DeviceSelect {
476 id: "prejoin-mic-select",
477 label: "Microphone",
478 entries: inputs,
479 current: input,
480 enabled: audio_on,
481 },
482 |view, choice, cx| view.pick_input(choice, cx),
483 cx,
484 ))
485 .child(self.select(
486 DeviceSelect {
487 id: "prejoin-speaker-select",
488 label: "Speaker",
489 entries: outputs,
490 current: output,
491 enabled: audio_on,
492 },
493 |view, choice, cx| view.pick_output(choice, cx),
494 cx,
495 ));
496 let audio_row = h_flex()
497 .debug_selector(|| "shell/islands/main/prejoin/audio".into())
498 .flex_none()
499 .flex_wrap()
500 .gap(px(8.))
501 .child(self.audio_choice(AudioChoice::Computer, cx))
502 .child(self.audio_choice(AudioChoice::NoAudio, cx));
503 let cancel_view = cx.entity();
504 let join_view = cx.entity();
505 let actions = h_flex()
506 .debug_selector(|| "shell/islands/main/prejoin/actions".into())
507 .flex_none()
508 .gap(px(8.))
509 .justify_end()
510 .child(
511 Button::new("prejoin-cancel")
512 .ghost()
513 .label("Cancel")
514 .on_click(move |_, _, cx| cancel_view.update(cx, |view, cx| view.cancel(cx))),
515 )
516 .child(
517 Button::new("prejoin-join")
518 .primary()
519 .label("Join now")
520 .on_click(move |_, _, cx| join_view.update(cx, |view, cx| view.join(cx))),
521 );
522 v_flex()
523 .debug_selector(|| "shell/islands/main".into())
524 .size_full()
525 .p(px(PANE_PADDING))
526 .items_center()
527 .justify_center()
528 .rounded(px(10.))
529 .bg(theme::surface())
530 .overflow_hidden()
531 .child(
532 v_flex()
533 .debug_selector(|| "shell/islands/main/prejoin".into())
534 .w(px(CONTENT_WIDTH))
535 .max_w_full()
536 .max_h_full()
537 .min_h_0()
538 .gap(px(SECTION_GAP))
539 .child(
540 v_flex()
541 .flex_none()
542 .gap(px(2.))
543 .child(
544 div()
545 .truncate()
546 .text_size(px(20.))
547 .font_weight(FontWeight::SEMIBOLD)
548 .text_color(theme::text_strong())
549 .child(title),
550 )
551 .child(
552 div()
553 .truncate()
554 .text_size(px(13.))
555 .text_color(theme::text_muted())
556 .child("Choose your video and audio settings, then join"),
557 ),
558 )
559 .child(self.preview_box(cx))
560 .child(self.controls(cx))
561 .child(devices)
562 .child(audio_row)
563 .child(actions),
564 )
565 }
566}