use std::{ collections::HashMap, sync::Arc, time::{Duration, Instant}, }; use super::camera_view::CAMERA_BUSY; use common::model::Id; use common::share::{Codec, Fps, Kind, Mode, Quality, Resolution, clamp, options}; use std::sync::atomic::Ordering; use crate::lang::w; use crate::share::Target; use gpui_kit::{ Anchor, AnyElement, App, AppContext, Context, Div, Entity, InteractiveElement, IntoElement, KeyDownEvent, Keystroke, Modifiers, MouseButton, ObjectFit, ParentElement, PlatformInput, RenderImage, StatefulInteractiveElement, Styled, StyledImage, Subscription, Window, assets::IconName, component::{ WindowExt, popover::Popover, slider::{SliderEvent, SliderState}, }, div, img, prelude::FluentBuilder as _, px, uniform_list, }; use super::{ Tooltip as _, Trigger, Yumush, camera_view, chat::View, clickable, entity_action, media_view::into_render_image, notify_error, parts::{self, Scale, Tone, icon_button, scrim}, settings_page::segmented, stream_stats::{stream_card, watch_stats}, style::{Tokens, radius, size, space, text}, surface::Surface, text, widget::spawn_warn, }; use crate::{ settings::{self, ShareAudio, ShareCodec, ShareSettings}, share::{ audio::{AudioApp, AudioKind, is_excluded, is_picked}, encode::capabilities, watch::WatchQuality, }, }; const FULL_VOLUME: f32 = 100.; const VOLUME_WIDTH: f32 = 80.; const APPS_HEIGHT: f32 = 160.; const PICK_COLUMNS: usize = 3; const PICK_REFRESH: Duration = Duration::from_millis(1500); const PICK_ROW: f32 = size::THUMB + size::ROW; const PREVIEW_AGE: Duration = Duration::from_secs(3); const TOP_QUALITY: Quality = Quality { resolution: Resolution::P2160, fps: Fps::F60, }; const FLOAT_RIGHT: f32 = space::LG; const FLOAT_BOTTOM: f32 = size::ROW * 2. + space::XL; const FLOAT_WIDTH: f32 = size::MEDIA; const FLOAT_HEIGHT: f32 = size::MEDIA * 9. / 16.; const DRAG_SLOP: f32 = 4.; const BAR_TTL: Duration = Duration::from_millis(2500); const APPS_REFRESH: Duration = Duration::from_secs(2); const APPS_IDLE: Duration = Duration::from_secs(5); #[derive(Default)] struct Picker { sources: Vec<(Target, String)>, previews: HashMap)>, } #[derive(Default, Clone, Copy)] enum Drag { #[default] Idle, Pressed { start: gpui_kit::Point, from: (f32, f32), }, Dragging { start: gpui_kit::Point, from: (f32, f32), }, } impl Drag { fn grab(self) -> Option<(gpui_kit::Point, (f32, f32))> { match self { Drag::Idle => None, Drag::Pressed { start, from } | Drag::Dragging { start, from } => Some((start, from)), } } } #[derive(Default)] pub(super) struct Float { shift: (f32, f32), drag: Drag, } pub(super) const RESOLUTIONS: [(Resolution, &str); 6] = [ (Resolution::P360, "360"), (Resolution::P480, "480"), (Resolution::P720, "720"), (Resolution::P1080, "1080"), (Resolution::P1440, "1440"), (Resolution::P2160, "2160"), ]; pub(super) const FPS: [(Fps, &str); 3] = [(Fps::F15, "15"), (Fps::F30, "30"), (Fps::F60, "60")]; pub(super) fn codecs() -> [(ShareCodec, &'static str); 4] { [ (ShareCodec::Auto, w().share_view.auto), (ShareCodec::Only(Codec::Av1), "AV1"), (ShareCodec::Only(Codec::H265), "H265"), (ShareCodec::Only(Codec::H264), "H264"), ] } #[derive(Clone, Copy, PartialEq, Eq)] pub(super) enum AudioMode { Off, Everything, App, } impl AudioMode { fn all() -> [(Self, &'static str); 3] { [ (Self::Off, w().share_view.off), (Self::Everything, w().share_view.all), (Self::App, w().share_view.pick), ] } fn of(audio: &ShareAudio) -> Self { match audio { ShareAudio::Off => Self::Off, ShareAudio::Everything => Self::Everything, ShareAudio::App { .. } | ShareAudio::Device(_) => Self::App, } } } fn audio_choice(app: &AudioApp) -> ShareAudio { match app.kind { AudioKind::App => ShareAudio::App { name: app.name.clone(), pid: app.pid, }, AudioKind::Output | AudioKind::Input => ShareAudio::Device(app.node.clone()), } } fn is_chosen(audio: &ShareAudio, app: &AudioApp) -> bool { match audio { ShareAudio::App { name, pid } => { app.kind == AudioKind::App && is_picked((name, *pid), &app.name, app.pid) } ShareAudio::Device(node) => app.kind != AudioKind::App && *node == app.node, _ => false, } } pub(super) struct Viewer { user_id: Id, kind: Kind, shown: bool, surface: Entity, pub(super) fullscreen: bool, volume: Entity, restore: f32, active: Instant, cursor_hidden: bool, stats: bool, _subscriptions: Vec, } impl Picker { fn refresh(&mut self, sources: Vec) -> Vec> { let mut dropped = Vec::new(); let now = Instant::now(); self.sources = sources .into_iter() .map(|source| { if let Some(preview) = source.preview { let image = Arc::new(RenderImage::new(vec![image::Frame::new(preview)])); if let Some((_, old)) = self.previews.insert(source.target, (now, image)) { dropped.push(old); } } (source.target, source.name) }) .collect(); let alive: Vec = self.sources.iter().map(|(target, _)| *target).collect(); self.previews.retain(|target, (_, image)| { let keep = alive.contains(target); if !keep { dropped.push(image.clone()); } keep }); dropped } } fn pick_tile( index: usize, target: Target, name: String, preview: Option>, entity: &Entity, t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); clickable(("share_target", index), t, move |window, cx| { window.close_dialog(cx); entity.update(cx, |yumush, cx| yumush.share_to(Some(target), window, cx)); }) .flex_1() .min_w_0() .p(px(space::XS)) .flex() .flex_col() .gap(px(space::XS)) .rounded(px(radius::MD)) .child( div() .h(px(size::THUMB)) .rounded(px(radius::SM)) .overflow_hidden() .bg(t.raise()) .children(preview.map(|image| img(image).size_full().object_fit(ObjectFit::Contain))), ) .child(div().truncate().text_size(px(text::LABEL)).child(name)) } impl Yumush { pub(super) fn load_shares(&self, community_id: Id, cx: &mut Context) { let network = self.network.clone(); cx.spawn(async move |this, cx| { let Ok(shares) = network.shares(community_id).await else { return; }; let _ = this.update(cx, |yumush, cx| { yumush.chat.session.shares.insert(community_id, shares); cx.notify(); }); }) .detach(); } pub(super) fn toggle_share(&mut self, window: &mut Window, cx: &mut Context) { if self.share_busy { return; } if self.network.share_source(Kind::Screen).is_some() || !crate::share::capture::PICKS { self.share_to(None, window, cx); return; } self.pick_share(window, cx); } fn pick_share(&mut self, window: &mut Window, cx: &mut Context) { let entity = cx.entity(); let t = Tokens::of(cx); let picker: Entity = cx.new(|_| Picker::default()); let weak = picker.downgrade(); window.open_dialog(cx, move |dialog, _, cx| { let rows = picker.read(cx).sources.len().div_ceil(PICK_COLUMNS); let list = { let picker = picker.clone(); let entity = entity.clone(); uniform_list("share_targets", rows, move |range, _, cx| { let picker = picker.read(cx); range .map(|row| { let start = row * PICK_COLUMNS; let end = (start + PICK_COLUMNS).min(picker.sources.len()); let tiles = (start..end).map(|index| { let (target, name) = &picker.sources[index]; let preview = picker.previews.get(target).map(|(_, image)| image.clone()); pick_tile(index, *target, name.clone(), preview, &entity, t) }); let fillers = (end..start + PICK_COLUMNS).map(|_| div().flex_1()); div() .h(px(PICK_ROW)) .flex() .gap(px(space::SM)) .children(tiles) .children(fillers) }) .collect() }) .h(px((rows as f32 * PICK_ROW).min(size::PAGE))) }; dialog .title(w().share_view.share) .w(px(size::PAGE)) .child(list) }); cx.spawn_in(window, async move |_, cx| { loop { let Ok(ages) = weak.read_with(cx, |picker, _| { picker .previews .iter() .map(|(target, (taken, _))| (*target, *taken)) .collect::>() }) else { return; }; let sources = cx .background_executor() .spawn(async move { let stale = |target: Target| { ages.get(&target) .is_none_or(|taken| taken.elapsed() >= PREVIEW_AGE) }; crate::share::capture::targets(&stale) }) .await; let Some(picker) = weak.upgrade() else { return; }; let alive = cx.update(|window, cx| { let dropped = picker.update(cx, |picker, _| picker.refresh(sources)); for image in dropped { cx.drop_image(image, Some(window)); } window.refresh(); }); drop(picker); if alive.is_err() { return; } cx.background_executor().timer(PICK_REFRESH).await; } }) .detach(); } fn share_to(&mut self, target: Option, window: &mut Window, cx: &mut Context) { let network = self.network.clone(); let sharing = network.share_source(Kind::Screen).is_some(); let settings = self.settings.share.clone(); self.share_busy = true; cx.spawn_in(window, async move |this, cx| { if sharing { let _ = network.stop(Kind::Screen).await; } else if let Err(error) = network.start(Kind::Screen, &settings, target).await { notify_error(&this, cx, error); } let _ = this.update(cx, |yumush, cx| { yumush.share_busy = false; cx.notify(); }); }) .detach(); } fn toggle_share_mute(&mut self, window: &mut Window, cx: &mut Context) { let current = self.settings.share.volume; let Some(viewer) = self.chat.session.viewer.as_mut() else { return; }; let next = if current > 0. { viewer.restore = current; 0. } else { viewer.restore }; let slider = viewer.volume.clone(); slider.update(cx, |slider, cx| slider.set_value(next, window, cx)); self.update_share(cx, |settings| settings.volume = next); } fn update_share(&mut self, cx: &mut Context, change: impl FnOnce(&mut ShareSettings)) { let before = self.settings.share.clone(); change(&mut self.settings.share); settings::save(&self.settings); self.network.set_share_settings(&self.settings.share); if self.network.sharing_any() && before.encoding_differs(&self.settings.share) { let network = self.network.clone(); let settings = self.settings.share.clone(); spawn_warn(cx, "share update", async move { network.update_share(&settings).await }); } cx.notify(); } pub(super) fn refresh_share_apps(&mut self, cx: &mut Context) { self.share_apps_seen.set(Instant::now()); if self.share_apps_task.is_some() { return; } self.share_apps_task = Some(cx.spawn(async move |this, cx| { loop { let (apps, cameras) = cx .background_executor() .spawn(async move { ( crate::share::audio_capture::apps(), crate::share::camera::devices(), ) }) .await; let shown = this .update(cx, |yumush, cx| { yumush.share_apps = apps; yumush.camera_devices = cameras; cx.notify(); yumush.share_apps_seen.get().elapsed() < APPS_IDLE }) .unwrap_or(false); if !shown { let _ = this.update(cx, |yumush, _| yumush.share_apps_task = None); return; } cx.background_executor().timer(APPS_REFRESH).await; } })); } fn refresh_camera_modes(&self, cx: &mut Context) { let device = self.settings.share.camera_device.clone(); let fresh = self.network.share_modes(Kind::Camera).is_none(); cx.spawn(async move |this, cx| { let modes = cx .background_executor() .spawn(async move { fresh.then(|| crate::share::camera::list(device.as_deref())) }) .await; let _ = this.update(cx, |yumush, cx| { if let Some(modes) = modes { yumush.camera_modes = modes; } cx.notify(); }); }) .detach(); } pub(super) fn set_camera_device(&mut self, device: String, cx: &mut Context) { self.update_share(cx, |settings| settings.camera_device = Some(device)); self.refresh_camera_modes(cx); if !CAMERA_BUSY.load(Ordering::Relaxed) && self.network.share_source(Kind::Camera).is_some() { self.switch_camera(cx); } } fn switch_camera(&mut self, cx: &mut Context) { CAMERA_BUSY.store(true, Ordering::Relaxed); let network = self.network.clone(); let settings = self.settings.share.clone(); let device = settings.camera_device.clone(); cx.spawn(async move |this, cx| { let switched = async { network.stop(Kind::Camera).await?; network.start(Kind::Camera, &settings, None).await } .await; if let Err(error) = switched { tracing::warn!("camera switch failed: {error}"); } let _ = this.update(cx, |yumush, cx| yumush.settle_camera(device, cx)); }) .detach(); } pub(super) fn settle_camera(&mut self, device: Option, cx: &mut Context) { CAMERA_BUSY.store(false, Ordering::Relaxed); if self.network.share_source(Kind::Camera).is_some() && self.settings.share.camera_device != device { self.switch_camera(cx); } else { cx.notify(); } } pub(super) fn set_share_resolution( &mut self, kind: Kind, resolution: Resolution, cx: &mut Context, ) { self.update_share(cx, |settings| match kind { Kind::Screen => settings.top.resolution = resolution, Kind::Camera => settings.camera.resolution = resolution, }); } pub(super) fn set_share_codec(&mut self, codec: ShareCodec, cx: &mut Context) { self.update_share(cx, |settings| settings.codec = codec); } pub(super) fn set_share_fps(&mut self, kind: Kind, fps: Fps, cx: &mut Context) { self.update_share(cx, |settings| match kind { Kind::Screen => settings.top.fps = fps, Kind::Camera => settings.camera.fps = fps, }); } pub(super) fn set_share_audio_mode(&mut self, mode: AudioMode, cx: &mut Context) { self.refresh_share_apps(cx); let audio = match (mode, self.share_apps.first()) { (AudioMode::Off, _) => ShareAudio::Off, (AudioMode::Everything, _) => ShareAudio::Everything, (AudioMode::App, Some(app)) => audio_choice(app), (AudioMode::App, None) => return, }; self.update_share(cx, |settings| settings.audio = audio); } pub(super) fn set_share_source(&mut self, app: &AudioApp, cx: &mut Context) { let audio = audio_choice(app); self.update_share(cx, |settings| settings.audio = audio); } pub(super) fn set_share_included( &mut self, app: &AudioApp, included: bool, cx: &mut Context, ) { let siblings: Vec = self .share_apps .iter() .filter(|other| other.kind == AudioKind::App && other.name == app.name) .map(AudioApp::key) .collect(); let name = app.name.clone(); let key = app.key(); self.update_share(cx, |settings| { let excluded = &mut settings.excluded; let app_off = excluded.contains(&name); excluded.retain(|entry| *entry != name && *entry != key); match (included, siblings.len() > 1) { (false, false) => excluded.push(name), (false, true) => excluded.push(key), (true, true) if app_off => { let others: Vec = siblings .into_iter() .filter(|sibling| *sibling != key && !excluded.contains(sibling)) .collect(); excluded.extend(others); } (true, _) => {} } }); } pub(super) fn share_top(&self, user_id: Id, kind: Kind) -> Quality { self.chat .voice_community() .and_then(|community_id| self.chat.share_of(community_id, user_id, kind)) .map_or(TOP_QUALITY, |share| share.source.top) } pub(super) fn is_watching(&self, user_id: Id, kind: Kind) -> bool { self.chat .session .viewer .as_ref() .is_some_and(|viewer| viewer.user_id == user_id && viewer.kind == kind) } pub(super) fn viewing(&self) -> Option<(Id, Kind)> { self.chat .session .viewer .as_ref() .map(|viewer| (viewer.user_id, viewer.kind)) } pub(super) fn toggle_viewer( &mut self, user_id: Id, kind: Kind, window: &mut Window, cx: &mut Context, ) { let watching = self.is_watching(user_id, kind); self.close_viewer(cx); if watching { return; } let volume_level = self.settings.share.volume; let volume = cx.new(|_| { SliderState::new() .min(0.) .max(100.) .default_value(volume_level) }); let subscriptions = vec![cx.subscribe(&volume, |this, _, event: &SliderEvent, cx| { if let SliderEvent::Change(value) = event { let volume = value.start(); this.update_share(cx, |settings| settings.volume = volume); } })]; self.chat.session.viewer = Some(Viewer { user_id, kind, shown: false, surface: cx.new(|cx| Surface::new(false, self.network.clone(), (user_id, kind), cx)), fullscreen: false, volume, restore: FULL_VOLUME, active: Instant::now(), cursor_hidden: false, stats: false, _subscriptions: subscriptions, }); let network = self.network.clone(); let watch = WatchQuality::Auto; let volume = self.settings.share.volume; let choice = self.settings.voice.choice.clone(); let top = self.share_top(user_id, kind); if self.chat.session.tiles.contains_key(&(user_id, kind)) { network.set_watch_quality(user_id, kind, watch); } else { cx.spawn_in(window, async move |this, cx| { if let Err(error) = network .watch_share(user_id, kind, watch, top, volume, choice) .await { let _ = this.update(cx, |yumush, cx| { if yumush.is_watching(user_id, kind) { yumush.close_viewer(cx); } }); notify_error(&this, cx, error); } }) .detach(); } cx.notify(); } pub(super) fn close_viewer(&mut self, cx: &mut Context) { let Some(viewer) = self.chat.session.viewer.take() else { return; }; let surface = viewer.surface.clone(); cx.defer(move |cx| { if let Some(frame) = surface.update(cx, |surface, cx| surface.replace(None, cx)) { cx.drop_image(frame, None); } }); let source = (viewer.user_id, viewer.kind); if self.chat.session.tiles.contains_key(&source) { self.network .set_watch_quality(source.0, source.1, self.chat.stage.quality()); } else { self.unwatch_tile(source, cx); } cx.notify(); } pub(super) fn tick_viewer(&mut self, mut window: Option<&mut Window>, cx: &mut Context) { let Some(viewer) = self.chat.session.viewer.as_mut() else { return; }; let Some(frame) = self.network.share_frame(viewer.user_id, viewer.kind) else { return; }; let next = into_render_image(frame); let appeared = !viewer.shown && next.is_some(); viewer.shown |= next.is_some(); let previous = viewer .surface .update(cx, |surface, cx| surface.replace(next.clone(), cx)); if let Some(tile) = self .chat .session .tiles .get_mut(&(viewer.user_id, viewer.kind)) { tile.shown |= next.is_some(); if let Some(old) = tile .surface .update(cx, |surface, cx| surface.replace(next, cx)) && !previous .as_ref() .is_some_and(|current| Arc::ptr_eq(current, &old)) { cx.drop_image(old, window.as_deref_mut()); } } if let Some(old) = previous { cx.drop_image(old, window); } if appeared { cx.notify(); } } pub(super) fn toggle_fullscreen(&mut self, cx: &mut Context) { if let Some(viewer) = self.chat.session.viewer.as_mut() { viewer.fullscreen = !viewer.fullscreen; } cx.notify(); } pub(super) fn share_settings_button( &self, entity: &Entity, t: Tokens, kind: Kind, cx: &App, ) -> impl IntoElement { let refresh = entity.clone(); let settings = entity.clone(); let (id, button, tip) = match kind { Kind::Screen => ( "screen_settings", "screen_settings_button", w().share_view.screen_settings, ), Kind::Camera => ( "camera_settings", "camera_settings_button", w().share_view.camera_settings, ), }; Popover::new(id) .anchor(Anchor::BottomRight) .appearance(false) .trigger(Trigger::new( super::parts::chevron_face(false, super::style::Tokens::of(cx)) .id(button) .on_mouse_down(MouseButton::Left, move |_, _, cx| { refresh.update(cx, |yumush, cx| { yumush.share_tab = kind; yumush.share_more = false; yumush.refresh_share_apps(cx); if kind == Kind::Camera { yumush.refresh_camera_modes(cx); } }); }) .tip(tip), )) .content(move |_, _, cx| { let entity = settings.clone(); settings_card(&entity, entity.read(cx), t) }) } pub(super) fn inline_viewer(&self, entity: &Entity, t: Tokens) -> Option
{ let viewer = self .chat .session .viewer .as_ref() .filter(|viewer| !viewer.fullscreen) .filter(|_| self.chat.session.selected_community_id == self.chat.voice_community())?; Some(self.viewer_pane(viewer, entity, t)) } fn drag_float(&mut self, position: gpui_kit::Point, window: &Window) -> bool { let Some((start, from)) = self.chat.session.float.drag.grab() else { return false; }; let viewport = window.viewport_size(); let (width, height) = (f32::from(viewport.width), f32::from(viewport.height)); let x = (from.0 + f32::from(position.x - start.x)) .max(FLOAT_RIGHT - (width - FLOAT_WIDTH)) .min(FLOAT_RIGHT); let y = (from.1 + f32::from(position.y - start.y)) .max(FLOAT_BOTTOM - (height - FLOAT_HEIGHT)) .min(FLOAT_BOTTOM); let moved = (x - from.0).abs() + (y - from.1).abs() > DRAG_SLOP; let float = &mut self.chat.session.float; float.shift = (x, y); if moved { float.drag = Drag::Dragging { start, from }; } true } fn release_float(&mut self) { let float = &mut self.chat.session.float; if let Drag::Pressed { .. } = float.drag { float.drag = Drag::Idle; } } pub(super) fn float_moved( &mut self, event: &gpui_kit::MouseMoveEvent, window: &Window, cx: &mut Context, ) { if event.pressed_button != Some(MouseButton::Left) { self.release_float(); return; } if self.drag_float(event.position, window) { cx.notify(); } } pub(super) fn floating_viewer(&self, entity: &Entity, t: Tokens) -> Option
{ let viewer = self .chat .session .viewer .as_ref() .filter(|viewer| !viewer.fullscreen)?; let community = self.chat.voice_community()?; if self.chat.session.view == View::Chat && self.chat.session.selected_community_id == Some(community) { return None; } let (dx, dy) = self.chat.session.float.shift; let (grab, drag, release) = (entity.clone(), entity.clone(), entity.clone()); let entity = entity.clone(); Some( div() .absolute() .right(px(FLOAT_RIGHT - dx)) .bottom(px(FLOAT_BOTTOM - dy)) .w(px(FLOAT_WIDTH)) .h(px(FLOAT_HEIGHT)) .rounded(px(radius::LG)) .overflow_hidden() .bg(gpui_kit::black()) .child( div() .id("floating_viewer") .size_full() .occlude() .cursor_pointer() .on_mouse_down(MouseButton::Left, move |event, _, cx| { grab.update(cx, |yumush, _| { let float = &mut yumush.chat.session.float; float.drag = Drag::Pressed { start: event.position, from: float.shift, }; }) }) .on_mouse_move(move |event, window, cx| { drag.update(cx, |yumush, cx| yumush.float_moved(event, window, cx)) }) .on_mouse_up(MouseButton::Left, move |_, _, cx| { release.update(cx, |yumush, _| yumush.release_float()) }) .on_click(move |_, window, cx| { entity.update(cx, |yumush, cx| { let dragged = std::mem::take(&mut yumush.chat.session.float.drag); if matches!(dragged, Drag::Dragging { .. }) { return; } yumush.select_community(community, window, cx); }) }) .when(viewer.shown, |video| video.child(viewer.surface.clone())) .when(!viewer.shown, |video| { video .flex() .items_center() .justify_center() .child(gpui_kit::component::spinner::Spinner::new().color(t.dim())) }), ) .child( camera_view::tile_label(self, t, (viewer.user_id, viewer.kind)) .absolute() .left(px(space::SM)) .top(px(space::SM)), ), ) } pub(super) fn hide_idle_cursor(&mut self, window: &mut Window, cx: &mut App) { let Some(viewer) = self.chat.session.viewer.as_mut().filter(|viewer| { viewer.fullscreen && !viewer.cursor_hidden && viewer.active.elapsed() >= BAR_TTL }) else { return; }; viewer.cursor_hidden = true; window.defer(cx, |window, cx| { window.dispatch_event( PlatformInput::KeyDown(KeyDownEvent { keystroke: Keystroke { modifiers: Modifiers::default(), key: "f24".into(), key_char: Some(String::new()), }, is_held: false, prefer_character_input: false, }), cx, ); }); } pub(super) fn fullscreen_viewer(&self, entity: &Entity, t: Tokens) -> Option
{ let viewer = self .chat .session .viewer .as_ref() .filter(|viewer| viewer.fullscreen && self.chat.session.view == View::Chat)?; let bar = viewer.active.elapsed() < BAR_TTL; Some( div() .absolute() .inset_0() .flex() .bg(gpui_kit::black()) .child(self.viewer_pane(viewer, entity, t)) .when(bar, |this| { this.child( div() .absolute() .left_0() .right_0() .bottom(px(size::CONTROL + space::LG)) .child(self.voice_band(t).bg(t.ground())), ) .child( div() .absolute() .top(px(space::LG)) .left_0() .right_0() .flex() .justify_center() .child(scrim(t).child(parts::words( w().share_view.esc_exit, parts::Text::Label, parts::Ink::Dim, t, ))), ) }), ) } fn viewer_pane(&self, viewer: &Viewer, entity: &Entity, t: Tokens) -> Div { let (fullscreen_icon, fullscreen_tip) = if viewer.fullscreen { (IconName::Minimize, w().share_view.exit_fullscreen) } else { (IconName::Maximize, w().share_view.fullscreen) }; let audio = viewer.kind == Kind::Screen; let (user_id, kind) = (viewer.user_id, viewer.kind); let stats = watch_stats(self, user_id, kind); let bar = viewer.active.elapsed() < BAR_TTL; div() .flex_1() .min_h_0() .relative() .occlude() .when(!viewer.fullscreen, |this| this.bg(t.ground())) .on_mouse_move({ let entity = entity.clone(); move |_, _, cx| { entity.update(cx, |yumush, cx| { if let Some(viewer) = yumush.chat.session.viewer.as_mut() { let hidden = viewer.active.elapsed() >= BAR_TTL; viewer.active = Instant::now(); viewer.cursor_hidden = false; if hidden { cx.notify(); } } }) } }) .child( div() .id("viewer_video") .absolute() .inset_0() .when(!viewer.cursor_hidden, |video| video.cursor_pointer()) .on_click({ let entity = entity.clone(); move |_, _, cx| entity.update(cx, |yumush, cx| yumush.close_viewer(cx)) }) .when(viewer.shown, |video| video.child(viewer.surface.clone())) .when(!viewer.shown, |video| { video .flex() .items_center() .justify_center() .child(gpui_kit::component::spinner::Spinner::new().color(t.dim())) }), ) .child( camera_view::tile_label(self, t, (viewer.user_id, viewer.kind)) .absolute() .left(px(space::MD)) .top(px(space::MD)) .when(!bar, |this| this.invisible()), ) .children(stats.map(|_| { let entity = entity.clone(); parts::icon_button( "viewer_stats_button", IconName::ChartBar, w().share_view.stream_stats, if viewer.stats { Tone::On } else { Tone::Idle }, Scale::Normal, t, move |_, cx| { entity.update(cx, |yumush, cx| { if let Some(viewer) = yumush.chat.session.viewer.as_mut() { viewer.stats = !viewer.stats; } cx.notify(); }) }, ) .occlude() .absolute() .right(px(space::MD)) .top(px(space::MD)) .when(!bar && !viewer.stats, |this| this.invisible()) })) .when(viewer.stats, |this| { this.child( div() .occlude() .absolute() .right(px(space::MD)) .top(px(space::XXL)) .child(stream_card(self, user_id, kind, t)), ) }) .child( div() .absolute() .left_0() .right_0() .bottom(px(space::MD)) .flex() .justify_center() .on_mouse_up(MouseButton::Left, |_, _, cx| cx.stop_propagation()) .when(!bar, |this| this.invisible()) .child( scrim(t) .h(px(size::CONTROL)) .px(px(space::XS)) .gap(px(space::XS)) .children(audio.then(|| { let muted = self.settings.share.volume == 0.; icon_button( format!("share_mute_{muted}"), if muted { IconName::VolumeX } else { IconName::Volume2 }, if muted { w().share_view.unmute } else { w().share_view.mute }, Tone::Idle, Scale::Small, t, entity_action(entity, |yumush, window, cx| { yumush.toggle_share_mute(window, cx) }), ) })) .children(audio.then(|| { div() .w(px(VOLUME_WIDTH)) .child(parts::slider(&viewer.volume, t)) })) .child(icon_button( format!("share_fullscreen_{}", viewer.fullscreen), fullscreen_icon, fullscreen_tip, Tone::Idle, Scale::Small, t, entity_action(entity, |yumush, _, cx| yumush.toggle_fullscreen(cx)), )) .child(icon_button( "share_close".to_string(), IconName::X, w().share_view.close, Tone::Idle, Scale::Small, t, entity_action(entity, |yumush, _, cx| yumush.close_viewer(cx)), )), ), ) } } fn settings_card(entity: &Entity, yumush: &Yumush, t: Tokens) -> Div { let settings = &yumush.settings.share; let card = super::parts::quick(t).min_w(px(size::POPOVER)); let card = match yumush.share_tab { Kind::Camera => card.child(camera_devices(entity, yumush, t)), Kind::Screen => card .child(div().px(px(space::SM)).child(segmented( AudioMode::all(), AudioMode::of(&settings.audio), entity, t, Yumush::set_share_audio_mode, ))) .children(audio_list(entity, yumush, t)), }; card.child(super::parts::thread(t)) .child(quality_toggle(entity, yumush, t)) .when(yumush.share_more, |card| { card.children(quality_rows(entity, yumush, t)) }) } fn camera_devices(entity: &Entity, yumush: &Yumush, t: Tokens) -> Div { let chosen = yumush .settings .share .camera_device .clone() .filter(|device| yumush.camera_devices.contains(device)) .or_else(|| yumush.camera_devices.first().cloned()); if yumush.camera_devices.is_empty() { return div() .px(px(space::SM)) .text_color(t.dim()) .child(w().share_view.no_camera); } div().flex().flex_col().gap(px(space::XXS)).children( yumush .camera_devices .iter() .enumerate() .map(|(index, name)| { let entity = entity.clone(); let device = name.clone(); row_style(clickable(("camera_device", index), t, move |_, cx| { let device = device.clone(); entity.update(cx, |yumush, cx| yumush.set_camera_device(device, cx)); })) .child( div() .flex_1() .min_w_0() .truncate() .child(crate::share::camera::label(name).to_string()), ) .children((chosen.as_ref() == Some(name)).then(|| { super::parts::small_icon(IconName::Check) .flex_shrink_0() .text_color(t.paper()) })) }), ) } fn label(list: &[(T, &'static str)], value: T) -> &'static str { list.iter() .find(|(key, _)| *key == value) .map_or("", |(_, name)| *name) } fn shown_top(yumush: &Yumush, kind: Kind) -> (Vec, Quality) { let modes = share_modes(yumush, kind); let top = clamp( yumush.settings.share.top(kind), &modes, capabilities().max_height, ); (modes, top) } fn quality_toggle(entity: &Entity, yumush: &Yumush, t: Tokens) -> impl IntoElement { let open = yumush.share_more; let (_, top) = shown_top(yumush, yumush.share_tab); let summary = format!( "{} · {} fps · {}", label(&RESOLUTIONS, top.resolution), label(&FPS, top.fps), label(&codecs(), yumush.settings.share.codec), ); let entity = entity.clone(); row_style(clickable("share_quality", t, move |_, cx| { entity.update(cx, |yumush, cx| { yumush.share_more = !yumush.share_more; cx.notify(); }) })) .text_color(t.dim()) .child(div().flex_1().child(summary)) .child(super::parts::small_icon(if open { IconName::ChevronUp } else { IconName::ChevronDown })) } fn quality_rows(entity: &Entity, yumush: &Yumush, t: Tokens) -> [Div; 3] { let settings = &yumush.settings.share; let kind = yumush.share_tab; let (modes, top) = shown_top(yumush, kind); let max_height = capabilities().max_height; let (resolutions, fps) = options(&modes, top.resolution, max_height); let (set_resolution, set_fps): ( fn(&mut Yumush, Resolution, &mut Context), fn(&mut Yumush, Fps, &mut Context), ) = match kind { Kind::Screen => ( |yumush, resolution, cx| yumush.set_share_resolution(Kind::Screen, resolution, cx), |yumush, fps, cx| yumush.set_share_fps(Kind::Screen, fps, cx), ), Kind::Camera => ( |yumush, resolution, cx| yumush.set_share_resolution(Kind::Camera, resolution, cx), |yumush, fps, cx| yumush.set_share_fps(Kind::Camera, fps, cx), ), }; [ super::parts::quick_row( w().share_view.resolution, segmented( RESOLUTIONS .into_iter() .filter(|(resolution, _)| resolutions.contains(resolution)), top.resolution, entity, t, set_resolution, ), t, ), super::parts::quick_row( "FPS", segmented( FPS.into_iter().filter(|(value, _)| fps.contains(value)), top.fps, entity, t, set_fps, ), t, ), super::parts::quick_row( w().share_view.codec, segmented( codecs().into_iter().filter(|(codec, _)| match codec { ShareCodec::Auto => true, ShareCodec::Only(codec) => capabilities().encode.contains(codec), }), settings.codec, entity, t, Yumush::set_share_codec, ), t, ), ] } pub(super) fn share_modes(yumush: &Yumush, kind: Kind) -> Vec { yumush .network .share_modes(kind) .or_else(|| (kind == Kind::Camera).then(|| yumush.camera_modes.clone())) .filter(|modes| !modes.is_empty()) .unwrap_or_else(|| vec![(u32::MAX, u32::MAX)]) } fn audio_list(entity: &Entity, yumush: &Yumush, t: Tokens) -> Option { yumush.share_apps_seen.set(Instant::now()); let settings = &yumush.settings.share; match &settings.audio { ShareAudio::Off => None, ShareAudio::Everything if cfg!(target_os = "windows") => None, ShareAudio::Everything => { let apps: Vec<&AudioApp> = yumush .share_apps .iter() .filter(|app| app.kind == AudioKind::App) .collect(); (!apps.is_empty()).then(|| { let rows = div().flex().flex_col().gap(px(space::XXS)).children( apps.into_iter() .map(|app| include_row(entity, settings, app, t)), ); field(w().share_view.sound_from, app_list(rows), t).into_any_element() }) } audio => Some(app_list(pick_list(entity, audio, &yumush.share_apps, t)).into_any_element()), } } fn app_list(rows: impl IntoElement) -> impl IntoElement { div() .id("share_apps") .max_h(px(APPS_HEIGHT)) .overflow_y_scroll() .child(rows) } fn pick_list(entity: &Entity, audio: &ShareAudio, apps: &[AudioApp], t: Tokens) -> Div { let groups = [ (AudioKind::App, w().share_view.apps), (AudioKind::Output, w().share_view.outputs), (AudioKind::Input, w().share_view.inputs), ]; div() .flex() .flex_col() .gap(px(space::SM)) .children(groups.into_iter().filter_map(|(kind, label)| { let rows: Vec<_> = apps .iter() .filter(|app| app.kind == kind) .map(|app| pick_row(entity, is_chosen(audio, app), app, t)) .collect(); (!rows.is_empty()).then(|| group(label, rows, t)) })) } fn group(label: &'static str, rows: Vec, t: Tokens) -> Div { div() .flex() .flex_col() .gap(px(space::XXS)) .child(parts::caption_head(label, t)) .children(rows) } fn field(label: &'static str, control: impl IntoElement, t: Tokens) -> Div { div() .flex() .flex_col() .gap(px(space::SM)) .child( div() .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(label), ) .child(control) } pub(super) fn row_style(item: E) -> E { item.h(px(size::CONTROL_SM)) .px(px(space::SM)) .flex() .items_center() .gap(px(space::SM)) .rounded(px(radius::MD)) } fn name_cell(app: &AudioApp, t: Tokens) -> Div { div() .flex_1() .min_w_0() .flex() .items_baseline() .gap(px(space::SM)) .child(div().flex_none().child(app.name.clone())) .child( div() .min_w_0() .truncate() .text_size(text(text::CAPTION)) .text_color(t.dim()) .child(app.detail.clone()), ) } fn include_row( entity: &Entity, settings: &ShareSettings, app: &AudioApp, t: Tokens, ) -> impl IntoElement { let entity = entity.clone(); let included = !is_excluded(&settings.excluded, &app.name, app.pid); let target = app.clone(); row_style(div()) .child(name_cell(app, t)) .child(div().flex_shrink_0().child(super::parts::toggle( gpui_kit::ElementId::Name(format!("share_app_{}", app.key()).into()), included, t, move |_, cx| { entity.update(cx, |yumush, cx| { yumush.set_share_included(&target, !included, cx) }); }, ))) } fn pick_row(entity: &Entity, chosen: bool, app: &AudioApp, t: Tokens) -> impl IntoElement { let entity = entity.clone(); let target = app.clone(); row_style(clickable( format!("share_app_{}", app.key()), t, move |_, cx| { entity.update(cx, |yumush, cx| yumush.set_share_source(&target, cx)); }, )) .child(name_cell(app, t)) .children(chosen.then(|| { super::parts::small_icon(IconName::Check) .flex_shrink_0() .text_color(t.paper()) })) }