forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.07.5 MiB59842fdTahinli15 minutes ago405 commits

share_view.rs1358 lines, 47.1 KiBHistoryRawDownload
1use common::model::Id;
2use std::{
3 collections::HashMap,
4 sync::Arc,
5 time::{Duration, Instant},
6};
7
8use common::share::{Codec, Fps, Kind, Mode, Quality, Resolution, clamp, options};
9
10use crate::lang::w;
11use crate::share::Target;
12
13const FULL_VOLUME: f32 = 100.;
14const VOLUME_WIDTH: f32 = 80.;
15const APPS_HEIGHT: f32 = 160.;
16const PICK_COLUMNS: usize = 3;
17const PICK_REFRESH: Duration = Duration::from_millis(1500);
18
19const PICK_ROW: f32 = size::THUMB + size::ROW;
20const PREVIEW_AGE: Duration = Duration::from_secs(3);
21
22#[derive(Default)]
23struct Picker {
24 sources: Vec<(Target, String)>,
25 previews: HashMap<Target, (Instant, Arc<RenderImage>)>,
26}
27
28const TOP_QUALITY: Quality = Quality {
29 resolution: Resolution::P2160,
30 fps: Fps::F60,
31};
32use gpui_kit::{
33 Anchor, AnyElement, App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement,
34 KeyDownEvent, Keystroke, Modifiers, MouseButton, ObjectFit, ParentElement, PlatformInput,
35 RenderImage, StatefulInteractiveElement, Styled, StyledImage, Subscription, Window,
36 assets::IconName,
37 component::{
38 WindowExt,
39 popover::Popover,
40 slider::{SliderEvent, SliderState},
41 },
42 div, img,
43 prelude::FluentBuilder as _,
44 px, uniform_list,
45};
46
47use super::{
48 Palette, Tooltip as _, Trigger, Yumush, camera_view,
49 chat::View,
50 clickable, entity_action,
51 media_view::into_render_image,
52 notify_error,
53 parts::{self, Scale, Tone, icon_button, scrim},
54 settings_page::segmented,
55 stream_stats::{stream_card, watch_stats},
56 style::{radius, size, space, text},
57 surface::Surface,
58 text,
59 widget::spawn_warn,
60};
61use crate::{
62 settings::{self, ShareAudio, ShareCodec, ShareSettings},
63 share::{
64 audio::{AudioApp, AudioKind, is_excluded, is_picked},
65 encode::capabilities,
66 session::WatchQuality,
67 },
68};
69
70const FLOAT_RIGHT: f32 = space::LG;
71const FLOAT_BOTTOM: f32 = size::ROW * 2. + space::XL;
72const FLOAT_WIDTH: f32 = size::MEDIA;
73const FLOAT_HEIGHT: f32 = size::MEDIA * 9. / 16.;
74const DRAG_SLOP: f32 = 4.;
75
76#[derive(Default)]
77pub(super) struct Float {
78 shift: (f32, f32),
79 grab: Option<(gpui_kit::Point<gpui_kit::Pixels>, (f32, f32))>,
80 moved: bool,
81}
82
83const BAR_TTL: Duration = Duration::from_millis(2500);
84const APPS_REFRESH: Duration = Duration::from_secs(2);
85const APPS_IDLE: Duration = Duration::from_secs(5);
86
87pub(super) const RESOLUTIONS: [(Resolution, &str); 6] = [
88 (Resolution::P360, "360"),
89 (Resolution::P480, "480"),
90 (Resolution::P720, "720"),
91 (Resolution::P1080, "1080"),
92 (Resolution::P1440, "1440"),
93 (Resolution::P2160, "2160"),
94];
95pub(super) const FPS: [(Fps, &str); 3] = [(Fps::F15, "15"), (Fps::F30, "30"), (Fps::F60, "60")];
96
97pub(super) fn codecs() -> [(ShareCodec, &'static str); 4] {
98 [
99 (ShareCodec::Auto, w().share_view.auto),
100 (ShareCodec::Only(Codec::Av1), "AV1"),
101 (ShareCodec::Only(Codec::H265), "H265"),
102 (ShareCodec::Only(Codec::H264), "H264"),
103 ]
104}
105
106#[derive(Clone, Copy, PartialEq, Eq)]
107pub(super) enum AudioMode {
108 Off,
109 Everything,
110 App,
111}
112
113impl AudioMode {
114 fn all() -> [(Self, &'static str); 3] {
115 [
116 (Self::Off, w().share_view.off),
117 (Self::Everything, w().share_view.all),
118 (Self::App, w().share_view.pick),
119 ]
120 }
121
122 fn of(audio: &ShareAudio) -> Self {
123 match audio {
124 ShareAudio::Off => Self::Off,
125 ShareAudio::Everything => Self::Everything,
126 ShareAudio::App { .. } | ShareAudio::Device(_) => Self::App,
127 }
128 }
129}
130
131fn pick(app: &AudioApp) -> ShareAudio {
132 match app.kind {
133 AudioKind::App => ShareAudio::App {
134 name: app.name.clone(),
135 pid: app.pid,
136 },
137 AudioKind::Output | AudioKind::Input => ShareAudio::Device(app.node.clone()),
138 }
139}
140
141fn chosen(audio: &ShareAudio, app: &AudioApp) -> bool {
142 match audio {
143 ShareAudio::App { name, pid } => {
144 app.kind == AudioKind::App && is_picked((name, *pid), &app.name, app.pid)
145 }
146 ShareAudio::Device(node) => app.kind != AudioKind::App && *node == app.node,
147 _ => false,
148 }
149}
150
151pub(super) struct Viewer {
152 user_id: Id,
153 kind: Kind,
154 shown: bool,
155 surface: Entity<Surface>,
156 pub(super) fullscreen: bool,
157 volume: Entity<SliderState>,
158 restore: f32,
159 active: Instant,
160 cursor_hidden: bool,
161 stats: bool,
162 _subscriptions: Vec<Subscription>,
163}
164
165impl Picker {
166 fn refresh(&mut self, sources: Vec<crate::share::Source>) -> Vec<Arc<RenderImage>> {
167 let mut dropped = Vec::new();
168 let now = Instant::now();
169 self.sources = sources
170 .into_iter()
171 .map(|source| {
172 if let Some(preview) = source.preview {
173 let image = Arc::new(RenderImage::new(vec![image::Frame::new(preview)]));
174 if let Some((_, old)) = self.previews.insert(source.target, (now, image)) {
175 dropped.push(old);
176 }
177 }
178 (source.target, source.name)
179 })
180 .collect();
181 let alive: Vec<Target> = self.sources.iter().map(|(target, _)| *target).collect();
182 self.previews.retain(|target, (_, image)| {
183 let keep = alive.contains(target);
184 if !keep {
185 dropped.push(image.clone());
186 }
187 keep
188 });
189 dropped
190 }
191}
192
193fn pick_tile(
194 index: usize,
195 target: Target,
196 name: String,
197 preview: Option<Arc<RenderImage>>,
198 entity: &Entity<Yumush>,
199 palette: Palette,
200) -> impl IntoElement {
201 let entity = entity.clone();
202 clickable(("share_target", index), palette, move |window, cx| {
203 window.close_dialog(cx);
204 entity.update(cx, |yumush, cx| yumush.share_to(Some(target), window, cx));
205 })
206 .flex_1()
207 .min_w_0()
208 .p(px(space::XS))
209 .flex()
210 .flex_col()
211 .gap(px(space::XS))
212 .rounded(px(radius::MD))
213 .child(
214 div()
215 .h(px(size::THUMB))
216 .rounded(px(radius::SM))
217 .overflow_hidden()
218 .bg(palette.field)
219 .children(preview.map(|image| img(image).size_full().object_fit(ObjectFit::Contain))),
220 )
221 .child(div().truncate().text_size(px(text::LABEL)).child(name))
222}
223
224impl Yumush {
225 pub(super) fn load_shares(&self, community_id: Id, cx: &mut Context<Self>) {
226 let network = self.network.clone();
227
228 cx.spawn(async move |this, cx| {
229 let Ok(shares) = network.shares(community_id).await else {
230 return;
231 };
232 let _ = this.update(cx, |yumush, cx| {
233 yumush.chat.shares.insert(community_id, shares);
234 cx.notify();
235 });
236 })
237 .detach();
238 }
239
240 pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context<Self>) {
241 if self.share_busy {
242 return;
243 }
244 if self.network.sharing() || !crate::share::capture::PICKS {
245 self.share_to(None, window, cx);
246 return;
247 }
248 self.pick_share(window, cx);
249 }
250
251 fn pick_share(&mut self, window: &mut Window, cx: &mut Context<Self>) {
252 let entity = cx.entity();
253 let palette = super::palette(cx);
254 let picker: Entity<Picker> = cx.new(|_| Picker::default());
255 let weak = picker.downgrade();
256 window.open_dialog(cx, move |dialog, _, cx| {
257 let rows = picker.read(cx).sources.len().div_ceil(PICK_COLUMNS);
258 let list = {
259 let picker = picker.clone();
260 let entity = entity.clone();
261 uniform_list("share_targets", rows, move |range, _, cx| {
262 let picker = picker.read(cx);
263 range
264 .map(|row| {
265 let start = row * PICK_COLUMNS;
266 let end = (start + PICK_COLUMNS).min(picker.sources.len());
267 let tiles = (start..end).map(|index| {
268 let (target, name) = &picker.sources[index];
269 let preview =
270 picker.previews.get(target).map(|(_, image)| image.clone());
271 pick_tile(index, *target, name.clone(), preview, &entity, palette)
272 });
273 let fillers = (end..start + PICK_COLUMNS).map(|_| div().flex_1());
274 div()
275 .h(px(PICK_ROW))
276 .flex()
277 .gap(px(space::SM))
278 .children(tiles)
279 .children(fillers)
280 })
281 .collect()
282 })
283 .h(px((rows as f32 * PICK_ROW).min(size::PAGE)))
284 };
285 dialog
286 .title(w().share_view.share)
287 .w(px(size::PAGE))
288 .child(list)
289 });
290 cx.spawn_in(window, async move |_, cx| {
291 loop {
292 let Ok(ages) = weak.read_with(cx, |picker, _| {
293 picker
294 .previews
295 .iter()
296 .map(|(target, (taken, _))| (*target, *taken))
297 .collect::<HashMap<_, _>>()
298 }) else {
299 return;
300 };
301 let sources = cx
302 .background_executor()
303 .spawn(async move {
304 let stale = |target: Target| {
305 ages.get(&target)
306 .is_none_or(|taken| taken.elapsed() >= PREVIEW_AGE)
307 };
308 crate::share::capture::targets(&stale).unwrap_or_default()
309 })
310 .await;
311 let Some(picker) = weak.upgrade() else {
312 return;
313 };
314 let alive = cx.update(|window, cx| {
315 let dropped = picker.update(cx, |picker, _| picker.refresh(sources));
316 for image in dropped {
317 cx.drop_image(image, Some(window));
318 }
319 window.refresh();
320 });
321 drop(picker);
322 if alive.is_err() {
323 return;
324 }
325 cx.background_executor().timer(PICK_REFRESH).await;
326 }
327 })
328 .detach();
329 }
330
331 fn share_to(&mut self, target: Option<Target>, window: &mut Window, cx: &mut Context<Self>) {
332 let network = self.network.clone();
333 let sharing = network.sharing();
334 let settings = self.settings.share.clone();
335 self.share_busy = true;
336
337 cx.spawn_in(window, async move |this, cx| {
338 if sharing {
339 let _ = network.stop_share().await;
340 } else if let Err(error) = network.start_share(&settings, target).await {
341 notify_error(&this, cx, error);
342 }
343 let _ = this.update(cx, |yumush, cx| {
344 yumush.share_busy = false;
345 cx.notify();
346 });
347 })
348 .detach();
349 }
350
351 fn toggle_share_mute(&mut self, window: &mut Window, cx: &mut Context<Self>) {
352 let current = self.settings.share.volume;
353 let Some(viewer) = self.chat.viewer.as_mut() else {
354 return;
355 };
356 let next = if current > 0. {
357 viewer.restore = current;
358 0.
359 } else {
360 viewer.restore
361 };
362 let slider = viewer.volume.clone();
363 slider.update(cx, |slider, cx| slider.set_value(next, window, cx));
364 self.update_share(cx, |settings| settings.volume = next);
365 }
366
367 fn update_share(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut ShareSettings)) {
368 let before = self.settings.share.clone();
369 change(&mut self.settings.share);
370 settings::save(&self.settings);
371 self.network.set_share_settings(&self.settings.share);
372 if self.network.sharing_any() && before.encoding_differs(&self.settings.share) {
373 let network = self.network.clone();
374 let settings = self.settings.share.clone();
375 spawn_warn(cx, "share update", async move {
376 network.update_share(&settings).await
377 });
378 }
379 cx.notify();
380 }
381
382 pub(super) fn refresh_share_apps(&mut self, cx: &mut Context<Self>) {
383 self.share_apps_seen.set(Instant::now());
384 if self.share_apps_task.is_some() {
385 return;
386 }
387 let network = self.network.clone();
388 self.share_apps_task = Some(cx.spawn(async move |this, cx| {
389 loop {
390 let network = network.clone();
391 let (apps, cameras) = cx
392 .background_executor()
393 .spawn(async move { (network.audio_apps(), crate::share::camera::devices()) })
394 .await;
395 let shown = this
396 .update(cx, |yumush, cx| {
397 yumush.share_apps = apps;
398 yumush.camera_devices = cameras;
399 cx.notify();
400 yumush.share_apps_seen.get().elapsed() < APPS_IDLE
401 })
402 .unwrap_or(false);
403 if !shown {
404 let _ = this.update(cx, |yumush, _| yumush.share_apps_task = None);
405 return;
406 }
407 cx.background_executor().timer(APPS_REFRESH).await;
408 }
409 }));
410 }
411
412 fn refresh_camera_modes(&self, cx: &mut Context<Self>) {
413 let device = self.settings.share.camera_device.clone();
414 let fresh = self.network.share_modes(Kind::Camera).is_none();
415 cx.spawn(async move |this, cx| {
416 let (devices, modes) = cx
417 .background_executor()
418 .spawn(async move {
419 let modes = fresh.then(|| crate::share::camera::list(device.as_deref()));
420 (crate::share::camera::devices(), modes)
421 })
422 .await;
423 let _ = this.update(cx, |yumush, cx| {
424 yumush.camera_devices = devices;
425 if let Some(modes) = modes {
426 yumush.camera_modes = modes;
427 }
428 cx.notify();
429 });
430 })
431 .detach();
432 }
433
434 pub(super) fn set_camera_device(&mut self, device: String, cx: &mut Context<Self>) {
435 self.update_share(cx, |settings| settings.camera_device = Some(device));
436 self.refresh_camera_modes(cx);
437 if self.network.camera_on() {
438 let network = self.network.clone();
439 let settings = self.settings.share.clone();
440 spawn_warn(cx, "camera switch", async move {
441 network.stop_camera().await?;
442 network.start_camera(&settings).await
443 });
444 }
445 }
446
447 pub(super) fn set_share_resolution(&mut self, resolution: Resolution, cx: &mut Context<Self>) {
448 let kind = self.share_tab;
449 self.update_share(cx, |settings| match kind {
450 Kind::Screen => settings.top.resolution = resolution,
451 Kind::Camera => settings.camera.resolution = resolution,
452 });
453 }
454
455 pub(super) fn set_share_codec(&mut self, codec: ShareCodec, cx: &mut Context<Self>) {
456 self.update_share(cx, |settings| settings.codec = codec);
457 }
458
459 pub(super) fn set_share_fps(&mut self, fps: Fps, cx: &mut Context<Self>) {
460 let kind = self.share_tab;
461 self.update_share(cx, |settings| match kind {
462 Kind::Screen => settings.top.fps = fps,
463 Kind::Camera => settings.camera.fps = fps,
464 });
465 }
466
467 pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context<Self>) {
468 self.refresh_share_apps(cx);
469 let audio = match (mode, self.share_apps.first()) {
470 (AudioMode::Off, _) => ShareAudio::Off,
471 (AudioMode::Everything, _) => ShareAudio::Everything,
472 (AudioMode::App, Some(app)) => pick(app),
473 (AudioMode::App, None) => return,
474 };
475 self.update_share(cx, |settings| settings.audio = audio);
476 }
477
478 pub(super) fn set_share_source(&mut self, app: &AudioApp, cx: &mut Context<Self>) {
479 let audio = pick(app);
480 self.update_share(cx, |settings| settings.audio = audio);
481 }
482
483 pub(super) fn set_share_included(
484 &mut self,
485 app: &AudioApp,
486 included: bool,
487 cx: &mut Context<Self>,
488 ) {
489 let siblings: Vec<String> = self
490 .share_apps
491 .iter()
492 .filter(|other| other.kind == AudioKind::App && other.name == app.name)
493 .map(AudioApp::key)
494 .collect();
495 let name = app.name.clone();
496 let key = app.key();
497 self.update_share(cx, |settings| {
498 let excluded = &mut settings.excluded;
499 let app_off = excluded.contains(&name);
500 excluded.retain(|entry| *entry != name && *entry != key);
501 match (included, siblings.len() > 1) {
502 (false, false) => excluded.push(name),
503 (false, true) => excluded.push(key),
504 (true, true) if app_off => {
505 let others: Vec<String> = siblings
506 .into_iter()
507 .filter(|sibling| *sibling != key && !excluded.contains(sibling))
508 .collect();
509 excluded.extend(others);
510 }
511 (true, _) => {}
512 }
513 });
514 }
515
516 pub(super) fn share_top(&self, user_id: Id, kind: Kind) -> Quality {
517 self.chat
518 .voice_community()
519 .and_then(|community_id| self.chat.share_of(community_id, user_id, kind))
520 .map_or(TOP_QUALITY, |share| share.source.top)
521 }
522
523 pub(super) fn is_watching(&self, user_id: Id, kind: Kind) -> bool {
524 self.chat
525 .viewer
526 .as_ref()
527 .is_some_and(|viewer| viewer.user_id == user_id && viewer.kind == kind)
528 }
529
530 pub(super) fn viewing(&self) -> Option<(Id, Kind)> {
531 self.chat
532 .viewer
533 .as_ref()
534 .map(|viewer| (viewer.user_id, viewer.kind))
535 }
536
537 pub(super) fn toggle_viewer(
538 &mut self,
539 user_id: Id,
540 kind: Kind,
541 window: &mut Window,
542 cx: &mut Context<Self>,
543 ) {
544 let watching = self.is_watching(user_id, kind);
545 self.close_viewer(cx);
546 if watching {
547 return;
548 }
549
550 let volume_level = self.settings.share.volume;
551 let volume = cx.new(|_| {
552 SliderState::new()
553 .min(0.)
554 .max(100.)
555 .default_value(volume_level)
556 });
557 let subscriptions = vec![cx.subscribe(&volume, |this, _, event: &SliderEvent, cx| {
558 if let SliderEvent::Change(value) = event {
559 let volume = value.start();
560 this.update_share(cx, |settings| settings.volume = volume);
561 }
562 })];
563
564 self.chat.viewer = Some(Viewer {
565 user_id,
566 kind,
567 shown: false,
568 surface: cx.new(|cx| Surface::new(false, self.network.clone(), (user_id, kind), cx)),
569 fullscreen: false,
570 volume,
571 restore: FULL_VOLUME,
572 active: Instant::now(),
573 cursor_hidden: false,
574 stats: false,
575 _subscriptions: subscriptions,
576 });
577
578 let network = self.network.clone();
579 let watch = WatchQuality::Auto;
580 let volume = self.settings.share.volume;
581 let choice = self.settings.voice.choice.clone();
582 let top = self.share_top(user_id, kind);
583 if self.chat.tiles.contains_key(&(user_id, kind)) {
584 network.set_watch_quality(user_id, kind, watch);
585 } else {
586 cx.spawn_in(window, async move |this, cx| {
587 if let Err(error) = network
588 .watch_share(user_id, kind, watch, top, volume, choice)
589 .await
590 {
591 let _ = this.update(cx, |yumush, cx| {
592 if yumush.is_watching(user_id, kind) {
593 yumush.close_viewer(cx);
594 }
595 });
596 notify_error(&this, cx, error);
597 }
598 })
599 .detach();
600 }
601 cx.notify();
602 }
603
604 pub(super) fn close_viewer(&mut self, cx: &mut Context<Self>) {
605 let Some(viewer) = self.chat.viewer.take() else {
606 return;
607 };
608 let surface = viewer.surface.clone();
609 cx.defer(move |cx| {
610 if let Some(frame) = surface.update(cx, |surface, cx| surface.replace(None, cx)) {
611 cx.drop_image(frame, None);
612 }
613 });
614 let network = self.network.clone();
615 if self.chat.tiles.contains_key(&(viewer.user_id, viewer.kind)) {
616 network.set_watch_quality(
617 viewer.user_id,
618 viewer.kind,
619 camera_view::tile_quality(self.chat.stage),
620 );
621 } else {
622 let user_id = viewer.user_id;
623 let kind = viewer.kind;
624 cx.spawn(async move |_, _| {
625 let _ = network.unwatch_share(user_id, kind).await;
626 })
627 .detach();
628 }
629 cx.notify();
630 }
631
632 pub(super) fn tick_viewer(&mut self, mut window: Option<&mut Window>, cx: &mut Context<Self>) {
633 let Some(viewer) = self.chat.viewer.as_mut() else {
634 return;
635 };
636 let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else {
637 return;
638 };
639 let next = into_render_image(frame);
640 let appeared = !viewer.shown && next.is_some();
641 viewer.shown |= next.is_some();
642 let previous = viewer
643 .surface
644 .update(cx, |surface, cx| surface.replace(next.clone(), cx));
645 if let Some(tile) = self.chat.tiles.get_mut(&(viewer.user_id, viewer.kind)) {
646 tile.shown |= next.is_some();
647 if let Some(old) = tile
648 .surface
649 .update(cx, |surface, cx| surface.replace(next, cx))
650 && !previous
651 .as_ref()
652 .is_some_and(|current| Arc::ptr_eq(current, &old))
653 {
654 cx.drop_image(old, window.as_deref_mut());
655 }
656 }
657 if let Some(old) = previous {
658 cx.drop_image(old, window);
659 }
660 if appeared {
661 cx.notify();
662 }
663 }
664
665 pub(super) fn toggle_fullscreen(&mut self, cx: &mut Context<Self>) {
666 if let Some(viewer) = self.chat.viewer.as_mut() {
667 viewer.fullscreen = !viewer.fullscreen;
668 }
669 cx.notify();
670 }
671
672 pub(super) fn share_settings_button(
673 &self,
674 entity: &Entity<Self>,
675 palette: Palette,
676 kind: Kind,
677 cx: &App,
678 ) -> impl IntoElement {
679 let refresh = entity.clone();
680 let settings = entity.clone();
681 let (id, button, tip) = match kind {
682 Kind::Screen => (
683 "screen_settings",
684 "screen_settings_button",
685 w().share_view.screen_settings,
686 ),
687 Kind::Camera => (
688 "camera_settings",
689 "camera_settings_button",
690 w().share_view.camera_settings,
691 ),
692 };
693
694 Popover::new(id)
695 .anchor(Anchor::BottomRight)
696 .appearance(false)
697 .trigger(Trigger::new(
698 super::parts::chevron_face(false, super::style::Tokens::of(cx))
699 .id(button)
700 .on_mouse_down(MouseButton::Left, move |_, _, cx| {
701 refresh.update(cx, |yumush, cx| {
702 yumush.share_tab = kind;
703 yumush.share_more = false;
704 yumush.refresh_share_apps(cx);
705 if kind == Kind::Camera {
706 yumush.refresh_camera_modes(cx);
707 }
708 });
709 })
710 .tip(tip),
711 ))
712 .content(move |_, _, cx| {
713 let entity = settings.clone();
714 settings_card(&entity, entity.read(cx), palette)
715 })
716 }
717
718 pub(super) fn inline_viewer(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
719 let viewer = self
720 .chat
721 .viewer
722 .as_ref()
723 .filter(|viewer| !viewer.fullscreen)
724 .filter(|_| self.chat.selected_community_id == self.chat.voice_community())?;
725 Some(self.viewer_pane(viewer, entity, palette))
726 }
727
728 fn drag_float(&mut self, position: gpui_kit::Point<gpui_kit::Pixels>, window: &Window) -> bool {
729 let Some((start, from)) = self.chat.float.grab else {
730 return false;
731 };
732 let viewport = window.viewport_size();
733 let (width, height) = (f32::from(viewport.width), f32::from(viewport.height));
734 let x = (from.0 + f32::from(position.x - start.x))
735 .clamp(FLOAT_RIGHT - (width - FLOAT_WIDTH), FLOAT_RIGHT);
736 let y = (from.1 + f32::from(position.y - start.y))
737 .clamp(FLOAT_BOTTOM - (height - FLOAT_HEIGHT), FLOAT_BOTTOM);
738 let moved = (x - from.0).abs() + (y - from.1).abs() > DRAG_SLOP;
739 self.chat.float.moved |= moved;
740 self.chat.float.shift = (x, y);
741 true
742 }
743
744 pub(super) fn float_moved(
745 &mut self,
746 event: &gpui_kit::MouseMoveEvent,
747 window: &Window,
748 cx: &mut Context<Self>,
749 ) {
750 if event.pressed_button != Some(MouseButton::Left) {
751 self.chat.float.grab = None;
752 return;
753 }
754 if self.drag_float(event.position, window) {
755 cx.notify();
756 }
757 }
758
759 pub(super) fn floating_viewer(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
760 let viewer = self
761 .chat
762 .viewer
763 .as_ref()
764 .filter(|viewer| !viewer.fullscreen)?;
765 let community = self.chat.voice_community()?;
766 if self.chat.view == View::Chat && self.chat.selected_community_id == Some(community) {
767 return None;
768 }
769 let (dx, dy) = self.chat.float.shift;
770 let (grab, drag, release) = (entity.clone(), entity.clone(), entity.clone());
771 let entity = entity.clone();
772 Some(
773 div()
774 .absolute()
775 .right(px(FLOAT_RIGHT - dx))
776 .bottom(px(FLOAT_BOTTOM - dy))
777 .w(px(FLOAT_WIDTH))
778 .h(px(FLOAT_HEIGHT))
779 .rounded(px(radius::LG))
780 .overflow_hidden()
781 .bg(gpui_kit::black())
782 .child(
783 div()
784 .id("floating_viewer")
785 .size_full()
786 .occlude()
787 .cursor_pointer()
788 .on_mouse_down(MouseButton::Left, move |event, _, cx| {
789 grab.update(cx, |yumush, _| {
790 let float = &mut yumush.chat.float;
791 float.grab = Some((event.position, float.shift));
792 float.moved = false;
793 })
794 })
795 .on_mouse_move(move |event, window, cx| {
796 drag.update(cx, |yumush, cx| yumush.float_moved(event, window, cx))
797 })
798 .on_mouse_up(MouseButton::Left, move |_, _, cx| {
799 release.update(cx, |yumush, _| yumush.chat.float.grab = None)
800 })
801 .on_click(move |_, window, cx| {
802 entity.update(cx, |yumush, cx| {
803 if std::mem::take(&mut yumush.chat.float.moved) {
804 return;
805 }
806 yumush.select_community(community, window, cx);
807 })
808 })
809 .when(viewer.shown, |video| video.child(viewer.surface.clone())),
810 )
811 .child(
812 camera_view::tile_label(self, palette, (viewer.user_id, viewer.kind))
813 .absolute()
814 .left(px(space::SM))
815 .top(px(space::SM)),
816 ),
817 )
818 }
819
820 pub(super) fn hide_idle_cursor(&mut self, window: &mut Window, cx: &mut App) {
821 let Some(viewer) = self.chat.viewer.as_mut().filter(|viewer| {
822 viewer.fullscreen && !viewer.cursor_hidden && viewer.active.elapsed() >= BAR_TTL
823 }) else {
824 return;
825 };
826 viewer.cursor_hidden = true;
827 window.defer(cx, |window, cx| {
828 window.dispatch_event(
829 PlatformInput::KeyDown(KeyDownEvent {
830 keystroke: Keystroke {
831 modifiers: Modifiers::default(),
832 key: "f24".into(),
833 key_char: Some(String::new()),
834 },
835 is_held: false,
836 prefer_character_input: false,
837 }),
838 cx,
839 );
840 });
841 }
842
843 pub(super) fn fullscreen_viewer(&self, entity: &Entity<Self>, palette: Palette) -> Option<Div> {
844 let viewer = self
845 .chat
846 .viewer
847 .as_ref()
848 .filter(|viewer| viewer.fullscreen && self.chat.view == View::Chat)?;
849 let bar = viewer.active.elapsed() < BAR_TTL;
850 Some(
851 div()
852 .absolute()
853 .inset_0()
854 .flex()
855 .bg(gpui_kit::black())
856 .child(self.viewer_pane(viewer, entity, palette))
857 .when(bar, |this| {
858 this.child(
859 div()
860 .absolute()
861 .left_0()
862 .right_0()
863 .bottom(px(size::CONTROL + space::LG))
864 .child(self.voice_band(palette).bg(palette.tokens.ground())),
865 )
866 .child(
867 div()
868 .absolute()
869 .top(px(space::LG))
870 .left_0()
871 .right_0()
872 .flex()
873 .justify_center()
874 .child(scrim(palette.tokens).child(parts::words(
875 w().share_view.esc_exit,
876 parts::Text::Label,
877 parts::Ink::Dim,
878 palette.tokens,
879 ))),
880 )
881 }),
882 )
883 }
884
885 fn viewer_pane(&self, viewer: &Viewer, entity: &Entity<Self>, palette: Palette) -> Div {
886 let (fullscreen_icon, fullscreen_tip) = if viewer.fullscreen {
887 (IconName::Minimize, w().share_view.exit_fullscreen)
888 } else {
889 (IconName::Maximize, w().share_view.fullscreen)
890 };
891 let audio = viewer.kind == Kind::Screen;
892 let t = palette.tokens;
893 let (user_id, kind) = (viewer.user_id, viewer.kind);
894 let stats = watch_stats(self, user_id, kind);
895 let bar = viewer.active.elapsed() < BAR_TTL;
896
897 div()
898 .flex_1()
899 .min_h_0()
900 .relative()
901 .occlude()
902 .when(!viewer.fullscreen, |this| this.bg(palette.window))
903 .on_mouse_move({
904 let entity = entity.clone();
905 move |_, _, cx| {
906 entity.update(cx, |yumush, cx| {
907 if let Some(viewer) = yumush.chat.viewer.as_mut() {
908 let hidden = viewer.active.elapsed() >= BAR_TTL;
909 viewer.active = Instant::now();
910 viewer.cursor_hidden = false;
911 if hidden {
912 cx.notify();
913 }
914 }
915 })
916 }
917 })
918 .child(
919 div()
920 .id("viewer_video")
921 .absolute()
922 .inset_0()
923 .when(!viewer.cursor_hidden, |video| video.cursor_pointer())
924 .on_click({
925 let entity = entity.clone();
926 move |_, _, cx| entity.update(cx, |yumush, cx| yumush.close_viewer(cx))
927 })
928 .when(viewer.shown, |video| video.child(viewer.surface.clone())),
929 )
930 .child(
931 camera_view::tile_label(self, palette, (viewer.user_id, viewer.kind))
932 .absolute()
933 .left(px(space::MD))
934 .top(px(space::MD))
935 .when(!bar, |this| this.invisible()),
936 )
937 .children(stats.map(|_| {
938 let entity = entity.clone();
939 parts::icon_button(
940 "viewer_stats_button",
941 IconName::ChartBar,
942 w().share_view.stream_stats,
943 if viewer.stats { Tone::On } else { Tone::Idle },
944 Scale::Normal,
945 t,
946 move |_, cx| {
947 entity.update(cx, |yumush, cx| {
948 if let Some(viewer) = yumush.chat.viewer.as_mut() {
949 viewer.stats = !viewer.stats;
950 }
951 cx.notify();
952 })
953 },
954 )
955 .occlude()
956 .absolute()
957 .right(px(space::MD))
958 .top(px(space::MD))
959 .when(!bar && !viewer.stats, |this| this.invisible())
960 }))
961 .when(viewer.stats, |this| {
962 this.child(
963 div()
964 .occlude()
965 .absolute()
966 .right(px(space::MD))
967 .top(px(space::XXL))
968 .child(stream_card(self, user_id, kind, palette)),
969 )
970 })
971 .child(
972 div()
973 .absolute()
974 .left_0()
975 .right_0()
976 .bottom(px(space::MD))
977 .flex()
978 .justify_center()
979 .on_mouse_up(MouseButton::Left, |_, _, cx| cx.stop_propagation())
980 .when(!bar, |this| this.invisible())
981 .child(
982 scrim(t)
983 .h(px(size::CONTROL))
984 .px(px(space::XS))
985 .gap(px(space::XS))
986 .children(audio.then(|| {
987 let muted = self.settings.share.volume == 0.;
988 icon_button(
989 format!("share_mute_{muted}"),
990 if muted {
991 IconName::VolumeX
992 } else {
993 IconName::Volume2
994 },
995 if muted {
996 w().share_view.unmute
997 } else {
998 w().share_view.mute
999 },
1000 Tone::Idle,
1001 Scale::Small,
1002 palette.tokens,
1003 entity_action(entity, |yumush, window, cx| {
1004 yumush.toggle_share_mute(window, cx)
1005 }),
1006 )
1007 }))
1008 .children(audio.then(|| {
1009 div()
1010 .w(px(VOLUME_WIDTH))
1011 .child(parts::slider(&viewer.volume, t))
1012 }))
1013 .child(icon_button(
1014 format!("share_fullscreen_{}", viewer.fullscreen),
1015 fullscreen_icon,
1016 fullscreen_tip,
1017 Tone::Idle,
1018 Scale::Small,
1019 palette.tokens,
1020 entity_action(entity, |yumush, _, cx| yumush.toggle_fullscreen(cx)),
1021 ))
1022 .child(icon_button(
1023 "share_close".to_string(),
1024 IconName::X,
1025 w().share_view.close,
1026 Tone::Idle,
1027 Scale::Small,
1028 palette.tokens,
1029 entity_action(entity, |yumush, _, cx| yumush.close_viewer(cx)),
1030 )),
1031 ),
1032 )
1033 }
1034}
1035
1036fn settings_card(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Div {
1037 let settings = &yumush.settings.share;
1038 let t = palette.tokens;
1039 let card = super::parts::quick(t).min_w(px(size::POPOVER));
1040 let card = match yumush.share_tab {
1041 Kind::Camera => card.child(camera_devices(entity, yumush, palette)),
1042 Kind::Screen => card
1043 .child(div().px(px(space::SM)).child(segmented(
1044 AudioMode::all(),
1045 AudioMode::of(&settings.audio),
1046 entity,
1047 palette,
1048 Yumush::set_share_audio_mode,
1049 )))
1050 .children(audio_list(entity, yumush, palette)),
1051 };
1052 card.child(super::parts::thread(t))
1053 .child(quality_toggle(entity, yumush, palette))
1054 .when(yumush.share_more, |card| {
1055 card.children(quality_rows(entity, yumush, palette))
1056 })
1057}
1058
1059fn camera_devices(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Div {
1060 let chosen = yumush
1061 .settings
1062 .share
1063 .camera_device
1064 .clone()
1065 .filter(|device| yumush.camera_devices.contains(device))
1066 .or_else(|| yumush.camera_devices.first().cloned());
1067 if yumush.camera_devices.is_empty() {
1068 return div()
1069 .px(px(space::SM))
1070 .text_color(palette.muted)
1071 .child(w().share_view.no_camera);
1072 }
1073 div().flex().flex_col().gap(px(space::XXS)).children(
1074 yumush
1075 .camera_devices
1076 .iter()
1077 .enumerate()
1078 .map(|(index, name)| {
1079 let entity = entity.clone();
1080 let device = name.clone();
1081 row_style(clickable(
1082 ("camera_device", index),
1083 palette,
1084 move |_, cx| {
1085 let device = device.clone();
1086 entity.update(cx, |yumush, cx| yumush.set_camera_device(device, cx));
1087 },
1088 ))
1089 .child(
1090 div()
1091 .flex_1()
1092 .min_w_0()
1093 .truncate()
1094 .child(crate::share::camera::label(name).to_string()),
1095 )
1096 .children((chosen.as_ref() == Some(name)).then(|| {
1097 super::parts::small_icon(IconName::Check)
1098 .flex_shrink_0()
1099 .text_color(palette.text)
1100 }))
1101 }),
1102 )
1103}
1104
1105fn label<T: PartialEq>(list: &[(T, &'static str)], value: T) -> &'static str {
1106 list.iter()
1107 .find(|(key, _)| *key == value)
1108 .map_or("", |(_, name)| *name)
1109}
1110
1111fn quality_toggle(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> impl IntoElement {
1112 let open = yumush.share_more;
1113 let kind = yumush.share_tab;
1114 let modes = share_modes(yumush, kind);
1115 let top = clamp(
1116 yumush.settings.share.top(kind),
1117 &modes,
1118 capabilities().max_height,
1119 );
1120 let summary = format!(
1121 "{} · {} fps · {}",
1122 label(&RESOLUTIONS, top.resolution),
1123 label(&FPS, top.fps),
1124 label(&codecs(), yumush.settings.share.codec),
1125 );
1126 let entity = entity.clone();
1127 row_style(clickable("share_quality", palette, move |_, cx| {
1128 entity.update(cx, |yumush, cx| {
1129 yumush.share_more = !yumush.share_more;
1130 cx.notify();
1131 })
1132 }))
1133 .text_color(palette.muted)
1134 .child(div().flex_1().child(summary))
1135 .child(super::parts::small_icon(if open {
1136 IconName::ChevronUp
1137 } else {
1138 IconName::ChevronDown
1139 }))
1140}
1141
1142fn quality_rows(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> [Div; 3] {
1143 let settings = &yumush.settings.share;
1144 let kind = yumush.share_tab;
1145 let modes = share_modes(yumush, kind);
1146 let max_height = capabilities().max_height;
1147 let top = clamp(settings.top(kind), &modes, max_height);
1148 let (resolutions, fps) = options(&modes, top.resolution, max_height);
1149 let t = palette.tokens;
1150 [
1151 super::parts::quick_row(
1152 w().share_view.resolution,
1153 segmented(
1154 RESOLUTIONS
1155 .into_iter()
1156 .filter(|(resolution, _)| resolutions.contains(resolution)),
1157 top.resolution,
1158 entity,
1159 palette,
1160 Yumush::set_share_resolution,
1161 ),
1162 t,
1163 ),
1164 super::parts::quick_row(
1165 "FPS",
1166 segmented(
1167 FPS.into_iter().filter(|(value, _)| fps.contains(value)),
1168 top.fps,
1169 entity,
1170 palette,
1171 Yumush::set_share_fps,
1172 ),
1173 t,
1174 ),
1175 super::parts::quick_row(
1176 w().share_view.codec,
1177 segmented(
1178 codecs().into_iter().filter(|(codec, _)| match codec {
1179 ShareCodec::Auto => true,
1180 ShareCodec::Only(codec) => capabilities().encode.contains(codec),
1181 }),
1182 settings.codec,
1183 entity,
1184 palette,
1185 Yumush::set_share_codec,
1186 ),
1187 t,
1188 ),
1189 ]
1190}
1191
1192pub(super) fn share_modes(yumush: &Yumush, kind: Kind) -> Vec<Mode> {
1193 yumush
1194 .network
1195 .share_modes(kind)
1196 .or_else(|| (kind == Kind::Camera).then(|| yumush.camera_modes.clone()))
1197 .filter(|modes| !modes.is_empty())
1198 .unwrap_or_else(|| vec![(u32::MAX, u32::MAX)])
1199}
1200
1201fn audio_list(entity: &Entity<Yumush>, yumush: &Yumush, palette: Palette) -> Option<AnyElement> {
1202 yumush.share_apps_seen.set(Instant::now());
1203 let settings = &yumush.settings.share;
1204
1205 match &settings.audio {
1206 ShareAudio::Off => None,
1207 ShareAudio::Everything if cfg!(target_os = "windows") => None,
1208 ShareAudio::Everything => {
1209 let apps: Vec<&AudioApp> = yumush
1210 .share_apps
1211 .iter()
1212 .filter(|app| app.kind == AudioKind::App)
1213 .collect();
1214 (!apps.is_empty()).then(|| {
1215 let rows = div().flex().flex_col().gap(px(space::XXS)).children(
1216 apps.into_iter()
1217 .map(|app| include_row(entity, settings, app, palette)),
1218 );
1219 field(w().share_view.sound_from, app_list(rows), palette).into_any_element()
1220 })
1221 }
1222 audio => {
1223 Some(app_list(pick_list(entity, audio, &yumush.share_apps, palette)).into_any_element())
1224 }
1225 }
1226}
1227
1228fn app_list(rows: impl IntoElement) -> impl IntoElement {
1229 div()
1230 .id("share_apps")
1231 .max_h(px(APPS_HEIGHT))
1232 .overflow_y_scroll()
1233 .child(rows)
1234}
1235
1236fn pick_list(
1237 entity: &Entity<Yumush>,
1238 audio: &ShareAudio,
1239 apps: &[AudioApp],
1240 palette: Palette,
1241) -> Div {
1242 let groups = [
1243 (AudioKind::App, w().share_view.apps),
1244 (AudioKind::Output, w().share_view.outputs),
1245 (AudioKind::Input, w().share_view.inputs),
1246 ];
1247
1248 div()
1249 .flex()
1250 .flex_col()
1251 .gap(px(space::SM))
1252 .children(groups.into_iter().filter_map(|(kind, label)| {
1253 let rows: Vec<_> = apps
1254 .iter()
1255 .filter(|app| app.kind == kind)
1256 .map(|app| pick_row(entity, chosen(audio, app), app, palette))
1257 .collect();
1258 (!rows.is_empty()).then(|| group(label, rows, palette))
1259 }))
1260}
1261
1262fn group(label: &'static str, rows: Vec<impl IntoElement>, palette: Palette) -> Div {
1263 div()
1264 .flex()
1265 .flex_col()
1266 .gap(px(space::XXS))
1267 .child(parts::caption_head(label, palette.tokens))
1268 .children(rows)
1269}
1270
1271fn field(label: &'static str, control: impl IntoElement, palette: Palette) -> Div {
1272 div()
1273 .flex()
1274 .flex_col()
1275 .gap(px(space::SM))
1276 .child(
1277 div()
1278 .text_size(text(text::CAPTION))
1279 .text_color(palette.muted)
1280 .child(label),
1281 )
1282 .child(control)
1283}
1284
1285pub(super) fn row_style<E: Styled>(item: E) -> E {
1286 item.h(px(size::CONTROL_SM))
1287 .px(px(space::SM))
1288 .flex()
1289 .items_center()
1290 .gap(px(space::SM))
1291 .rounded(px(radius::MD))
1292}
1293
1294fn name_cell(app: &AudioApp, palette: Palette) -> Div {
1295 div()
1296 .flex_1()
1297 .min_w_0()
1298 .flex()
1299 .items_baseline()
1300 .gap(px(space::SM))
1301 .child(div().flex_none().child(app.name.clone()))
1302 .child(
1303 div()
1304 .min_w_0()
1305 .truncate()
1306 .text_size(text(text::CAPTION))
1307 .text_color(palette.muted)
1308 .child(app.detail.clone()),
1309 )
1310}
1311
1312fn include_row(
1313 entity: &Entity<Yumush>,
1314 settings: &ShareSettings,
1315 app: &AudioApp,
1316 palette: Palette,
1317) -> impl IntoElement {
1318 let entity = entity.clone();
1319 let included = !is_excluded(&settings.excluded, &app.name, app.pid);
1320 let target = app.clone();
1321
1322 row_style(div())
1323 .child(name_cell(app, palette))
1324 .child(div().flex_shrink_0().child(super::parts::toggle(
1325 gpui_kit::ElementId::Name(format!("share_app_{}", app.key()).into()),
1326 included,
1327 palette.tokens,
1328 move |_, cx| {
1329 entity.update(cx, |yumush, cx| {
1330 yumush.set_share_included(&target, !included, cx)
1331 });
1332 },
1333 )))
1334}
1335
1336fn pick_row(
1337 entity: &Entity<Yumush>,
1338 chosen: bool,
1339 app: &AudioApp,
1340 palette: Palette,
1341) -> impl IntoElement {
1342 let entity = entity.clone();
1343 let target = app.clone();
1344
1345 row_style(clickable(
1346 format!("share_app_{}", app.key()),
1347 palette,
1348 move |_, cx| {
1349 entity.update(cx, |yumush, cx| yumush.set_share_source(&target, cx));
1350 },
1351 ))
1352 .child(name_cell(app, palette))
1353 .children(chosen.then(|| {
1354 super::parts::small_icon(IconName::Check)
1355 .flex_shrink_0()
1356 .text_color(palette.text)
1357 }))
1358}