forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

camera_view.rs667 lines, 20.5 KiBHistoryRawDownload
1use std::time::{Duration, Instant};
2
3use common::model::Id;
4
5use common::share::{Fps, Kind, Quality, Resolution};
6use gpui_kit::{
7 AnyElement, AppContext as _, Context, Div, Entity, InteractiveElement, IntoElement,
8 ParentElement, StatefulInteractiveElement, Styled, Task, Window, assets::IconName, div,
9 prelude::FluentBuilder as _, px,
10};
11
12use super::{
13 Palette, Tooltip as _, Yumush,
14 media_view::into_render_image,
15 notify_error,
16 parts::{Ink, Text, Voice, caption, scrim, voice_line, words},
17 style::{radius, size, space},
18 surface::Surface,
19 widget::spawn_warn,
20};
21use crate::lang::w;
22use crate::share::session::WatchQuality;
23
24const SLOTS: usize = 6;
25const IDLE_TICK: Duration = Duration::from_millis(250);
26const FRAME_TICK: Duration = Duration::from_millis(16);
27const PUMP_STALL: Duration = Duration::from_millis(50);
28const TILE_W: f32 = size::THUMB * 1.5;
29const TILE_H: f32 = TILE_W * 9. / 16.;
30
31pub(super) const TILE_QUALITY: WatchQuality = WatchQuality::Fixed(Quality {
32 resolution: Resolution::P360,
33 fps: Fps::F15,
34});
35
36#[derive(Clone, Copy, PartialEq, Eq)]
37pub(super) enum Stage {
38 Strip,
39 Grid,
40 Hidden,
41}
42
43pub(super) fn tile_quality(stage: Stage) -> WatchQuality {
44 match stage {
45 Stage::Grid => WatchQuality::Auto,
46 Stage::Strip | Stage::Hidden => TILE_QUALITY,
47 }
48}
49
50pub(super) struct Tile {
51 pub(super) shown: bool,
52 pub(super) surface: Entity<Surface>,
53}
54
55fn tile_cover(stage: Stage) -> bool {
56 stage != Stage::Grid
57}
58
59impl Yumush {
60 fn tile_sources(&self) -> Vec<(Id, Kind)> {
61 let shown = self.chat.stage != Stage::Hidden;
62 self.stage_sources()
63 .into_iter()
64 .filter(|(_, kind)| shown || *kind == Kind::Camera)
65 .collect()
66 }
67
68 pub(super) fn tick_tiles(
69 &mut self,
70 mut window: Option<&mut Window>,
71 cx: &mut Context<Self>,
72 ) -> bool {
73 let wanted = self.tile_sources();
74 let viewing = self.viewing();
75 let quality = tile_quality(self.chat.stage);
76 let mut changed = false;
77
78 for &source in &wanted {
79 if self.chat.tiles.contains_key(&source) {
80 continue;
81 }
82 let cover = tile_cover(self.chat.stage);
83 let network = self.network.clone();
84 let surface = cx.new(|cx| Surface::new(cover, network, source, cx));
85 self.chat.tiles.insert(
86 source,
87 Tile {
88 shown: false,
89 surface,
90 },
91 );
92 changed = true;
93 if viewing == Some(source) {
94 continue;
95 }
96 let (user_id, kind) = source;
97 let network = self.network.clone();
98 let volume = self.settings.share.volume;
99 let choice = self.settings.voice.choice.clone();
100 let top = self.share_top(user_id, kind);
101 spawn_warn(cx, "tile watch", async move {
102 network
103 .watch_share(user_id, kind, quality, top, volume, choice)
104 .await
105 });
106 }
107
108 let gone: Vec<(Id, Kind)> = self
109 .chat
110 .tiles
111 .keys()
112 .filter(|source| !wanted.contains(source))
113 .copied()
114 .collect();
115 for source in gone {
116 if let Some(tile) = self.chat.tiles.remove(&source)
117 && let Some(frame) = tile
118 .surface
119 .update(cx, |surface, cx| surface.replace(None, cx))
120 {
121 cx.drop_image(frame, window.as_deref_mut());
122 }
123 if viewing != Some(source) {
124 let network = self.network.clone();
125 let (user_id, kind) = source;
126 cx.spawn(async move |_, _| {
127 let _ = network.unwatch_share(user_id, kind).await;
128 })
129 .detach();
130 }
131 changed = true;
132 }
133
134 for (&(user_id, kind), tile) in self.chat.tiles.iter_mut() {
135 if viewing == Some((user_id, kind)) {
136 continue;
137 }
138 let Some(frame) = self.network.share_frame(user_id, kind) else {
139 continue;
140 };
141 let next = into_render_image(frame);
142 changed |= !tile.shown && next.is_some();
143 tile.shown |= next.is_some();
144 if let Some(old) = tile
145 .surface
146 .update(cx, |surface, cx| surface.replace(next, cx))
147 {
148 cx.drop_image(old, window.as_deref_mut());
149 }
150 }
151
152 if changed {
153 cx.notify();
154 }
155 !self.chat.tiles.is_empty()
156 }
157
158 pub(super) fn set_stage(&mut self, stage: Stage, cx: &mut Context<Self>) {
159 self.chat.stage = stage;
160 let viewing = self.viewing();
161 let quality = tile_quality(stage);
162 for (&(user_id, kind), tile) in &self.chat.tiles {
163 if viewing != Some((user_id, kind)) {
164 self.network.set_watch_quality(user_id, kind, quality);
165 }
166 tile.surface
167 .update(cx, |surface, cx| surface.set_cover(tile_cover(stage), cx));
168 }
169 cx.notify();
170 }
171
172 pub(super) fn toggle_camera(&mut self, window: &mut Window, cx: &mut Context<Self>) {
173 let network = self.network.clone();
174 let on = network.camera_on();
175 let settings = self.settings.share.clone();
176
177 cx.spawn_in(window, async move |this, cx| {
178 if on {
179 let _ = network.stop_camera().await;
180 } else if let Err(error) = network.start_camera(&settings).await {
181 notify_error(&this, cx, error);
182 }
183 let _ = this.update(cx, |_, cx| cx.notify());
184 })
185 .detach();
186 }
187
188 pub(super) fn in_stage_chat(&self) -> bool {
189 self.chat.voice_community().is_some()
190 && self.chat.selected_community_id == self.chat.voice_community()
191 }
192
193 pub(super) fn stage_sources(&self) -> Vec<(Id, Kind)> {
194 let Some(community_id) = self.chat.voice_community() else {
195 return Vec::new();
196 };
197 let mut shares: Vec<&common::share::Share> = self
198 .chat
199 .shares
200 .get(&community_id)
201 .into_iter()
202 .flatten()
203 .collect();
204 shares.sort_by_key(|share| (share.kind != Kind::Camera, share.started_ms, share.user_id));
205 shares
206 .into_iter()
207 .map(|share| (share.user_id, share.kind))
208 .collect()
209 }
210
211 pub(super) fn stage_strip(
212 &self,
213 entity: &Entity<Self>,
214 palette: Palette,
215 ) -> Option<impl IntoElement> {
216 let shown = match self.chat.stage {
217 Stage::Strip => true,
218 Stage::Grid => self.chat.viewer.is_some(),
219 Stage::Hidden => false,
220 };
221 if !shown || !self.in_stage_chat() {
222 return None;
223 }
224 let sources = self.stage_sources();
225 let (shown, more) = strip_slots(self.chat.strip_size.0, sources.len());
226 (!sources.is_empty()).then(|| {
227 div()
228 .id("stage_strip")
229 .relative()
230 .w_full()
231 .child(probe(entity.clone(), |yumush| &mut yumush.chat.strip_size))
232 .flex()
233 .flex_shrink_0()
234 .gap(px(space::LG))
235 .px(px(space::XL))
236 .pb(px(space::LG))
237 .children(
238 sources
239 .into_iter()
240 .take(shown)
241 .map(|source| stage_tile(entity, self, palette, source).into_any_element()),
242 )
243 .children((more > 0).then(|| more_tile(entity, more, palette).into_any_element()))
244 })
245 }
246
247 fn slots(&self, ids: &[Id]) -> (Vec<Id>, usize) {
248 let speaking = |id: &Id| self.chat.waves.audible(*id);
249 let mut shown: Vec<Id> = ids
250 .iter()
251 .filter(|id| speaking(id))
252 .take(SLOTS)
253 .copied()
254 .collect();
255 shown.extend(
256 ids.iter()
257 .filter(|id| !speaking(id))
258 .take(SLOTS - shown.len())
259 .copied(),
260 );
261 shown.sort_by_key(|id| ids.iter().position(|other| other == id));
262 let more = ids.len() - shown.len();
263 (shown, more)
264 }
265
266 fn voice_captions(&self, ids: &[Id], palette: Palette) -> Vec<Div> {
267 let t = palette.tokens;
268 let (shown, more) = self.slots(ids);
269 shown
270 .into_iter()
271 .filter_map(|id| self.chat.author(id))
272 .map(|user| {
273 let voice = if self.chat.waves.speaking.contains(&user.id) {
274 Voice::Live(t.person(user.id))
275 } else {
276 Voice::Quiet
277 };
278 let screen = self
279 .chat
280 .voice_community()
281 .and_then(|community_id| {
282 self.chat.share_of(community_id, user.id, Kind::Screen)
283 })
284 .is_some();
285 caption(
286 user.username.clone(),
287 voice_line(self.chat.waves.voice(user.id), voice, t),
288 t,
289 )
290 .h(px(size::CONTROL_SM))
291 .children(screen.then(|| {
292 super::call_bar::share_meter(
293 self.chat.waves.share(user.id),
294 t.person(user.id),
295 t,
296 )
297 }))
298 })
299 .chain(
300 (more > 0)
301 .then(|| caption(w().common.more(more), voice_line(None, Voice::Quiet, t), t)),
302 )
303 .collect()
304 }
305
306 pub(super) fn voice_band(&self, palette: Palette) -> Div {
307 let ids = self
308 .chat
309 .voice_community()
310 .map(|community_id| self.chat.voice_ids(community_id).to_vec())
311 .unwrap_or_default();
312 div()
313 .flex()
314 .flex_shrink_0()
315 .gap(px(space::XL))
316 .px(px(space::XL))
317 .py(px(space::LG))
318 .children(
319 self.voice_captions(&ids, palette)
320 .into_iter()
321 .map(|caption| caption.flex_1().min_w_0()),
322 )
323 }
324
325 pub(super) fn stage_grid(
326 &self,
327 entity: &Entity<Self>,
328 palette: Palette,
329 cx: &gpui_kit::App,
330 ) -> Option<impl IntoElement> {
331 if self.chat.stage != Stage::Grid
332 || !self.in_stage_chat()
333 || self
334 .chat
335 .viewer
336 .as_ref()
337 .is_some_and(|viewer| !viewer.fullscreen)
338 {
339 return None;
340 }
341 self.chat.voice_community()?;
342 let sources = self.stage_sources();
343 if sources.is_empty() {
344 return None;
345 }
346 let aspects: Vec<f32> = sources
347 .iter()
348 .map(|source| {
349 self.chat
350 .tiles
351 .get(source)
352 .map_or(WIDE, |tile| tile.surface.read(cx).aspect())
353 })
354 .collect();
355 let size = self.chat.grid_size;
356 let columns = grid_columns(&aspects, size);
357 let (cell_w, cell_h) = cell_size(sources.len(), columns, size);
358 let mut cells = sources.into_iter().zip(aspects).map(|(source, aspect)| {
359 let width = cell_w.min(cell_h * aspect);
360 grid_cell(entity, self, palette, source, (width, width / aspect))
361 });
362 let rows = (0..sources_rows(columns, cells.len()))
363 .map(|_| {
364 div()
365 .flex()
366 .justify_center()
367 .items_center()
368 .gap(px(GRID_GAP))
369 .children(cells.by_ref().take(columns).collect::<Vec<_>>())
370 })
371 .collect::<Vec<_>>();
372 let measure = entity.clone();
373
374 Some(
375 div()
376 .flex_1()
377 .min_h_0()
378 .relative()
379 .flex()
380 .flex_col()
381 .justify_center()
382 .gap(px(GRID_GAP))
383 .child(probe(measure, |yumush| &mut yumush.chat.grid_size))
384 .children(rows),
385 )
386 }
387}
388
389fn probe(entity: Entity<Yumush>, slot: fn(&mut Yumush) -> &mut (f32, f32)) -> impl IntoElement {
390 gpui_kit::canvas(
391 move |bounds, _, cx| {
392 let size = (f32::from(bounds.size.width), f32::from(bounds.size.height));
393 entity.update(cx, |yumush, cx| {
394 let stored = slot(yumush);
395 if *stored != size {
396 *stored = size;
397 cx.notify();
398 }
399 });
400 },
401 |_, _, _, _| {},
402 )
403 .absolute()
404 .inset_0()
405}
406
407fn strip_slots(width: f32, count: usize) -> (usize, usize) {
408 let fit =
409 (((width - 2. * space::XL + space::LG) / (TILE_W + space::LG)).floor() as usize).max(1);
410 if count <= fit {
411 (count, 0)
412 } else {
413 let shown = fit - 1;
414 (shown, count - shown)
415 }
416}
417
418const WIDE: f32 = 16. / 9.;
419const GRID_GAP: f32 = super::style::stroke::LINE;
420
421fn sources_rows(columns: usize, count: usize) -> usize {
422 count.div_ceil(columns.max(1))
423}
424
425fn cell_size(count: usize, columns: usize, (width, height): (f32, f32)) -> (f32, f32) {
426 let rows = sources_rows(columns, count);
427 (
428 (width - GRID_GAP * (columns - 1) as f32) / columns as f32,
429 (height - GRID_GAP * (rows - 1) as f32) / rows as f32,
430 )
431}
432
433fn grid_columns(aspects: &[f32], size: (f32, f32)) -> usize {
434 (1..=aspects.len().max(1))
435 .max_by(|a, b| {
436 let area = |columns: usize| {
437 let (cell_w, cell_h) = cell_size(aspects.len(), columns, size);
438 aspects
439 .iter()
440 .map(|aspect| {
441 let width = cell_w.min(cell_h * aspect);
442 width * width / aspect
443 })
444 .sum::<f32>()
445 };
446 area(*a).total_cmp(&area(*b))
447 })
448 .unwrap_or(1)
449}
450
451pub(super) fn ticker(cx: &mut Context<Yumush>) -> Task<()> {
452 cx.spawn(async move |this, cx| {
453 let mut tick = IDLE_TICK;
454 loop {
455 cx.background_executor().timer(tick).await;
456 match this.update(cx, |yumush, cx| yumush.idle_tick(cx)) {
457 Ok(true) => tick = FRAME_TICK,
458 Ok(false) => tick = IDLE_TICK,
459 Err(_) => break,
460 }
461 }
462 })
463}
464
465impl Yumush {
466 fn streaming(&self) -> bool {
467 self.chat.viewer.is_some() || !self.chat.tiles.is_empty() || self.media_playing()
468 }
469
470 fn pump(&mut self, window: &mut Window, cx: &mut Context<Self>) {
471 self.pumping = false;
472 self.pumped = Instant::now();
473 self.tick_viewer(Some(window), cx);
474 self.tick_tiles(Some(window), cx);
475 self.tick_player(window, cx);
476 self.schedule_pump(window, cx);
477 }
478
479 fn idle_tick(&mut self, cx: &mut Context<Self>) -> bool {
480 if self.pumped.elapsed() > PUMP_STALL {
481 self.tick_viewer(None, cx);
482 self.tick_tiles(None, cx);
483 }
484 self.streaming()
485 }
486
487 pub(super) fn schedule_pump(&mut self, window: &mut Window, cx: &mut Context<Self>) {
488 if self.pumping || !self.streaming() {
489 return;
490 }
491 self.pumping = true;
492 let this = cx.entity().downgrade();
493 window.on_next_frame(move |window, cx| {
494 let _ = this.update(cx, |yumush, cx| yumush.pump(window, cx));
495 });
496 }
497}
498
499fn stage_tile(
500 entity: &Entity<Yumush>,
501 yumush: &Yumush,
502 palette: Palette,
503 (user_id, kind): (Id, Kind),
504) -> impl IntoElement {
505 let t = palette.tokens;
506 let entity = entity.clone();
507 let focused = yumush.is_watching(user_id, kind);
508 let surface = yumush
509 .chat
510 .tiles
511 .get(&(user_id, kind))
512 .filter(|tile| tile.shown)
513 .map(|tile| tile.surface.clone());
514
515 div()
516 .id(format!("stage_{user_id}_{kind:?}"))
517 .tip(w().camera_view.watch)
518 .cursor_pointer()
519 .flex()
520 .flex_col()
521 .flex_shrink_0()
522 .gap(px(space::SM))
523 .w(px(TILE_W))
524 .on_click(move |_, window, cx| {
525 entity.update(cx, |yumush, cx| {
526 yumush.toggle_viewer(user_id, kind, window, cx)
527 });
528 })
529 .child(tile_name(yumush, (user_id, kind), focused, t))
530 .child(
531 div()
532 .h(px(TILE_H))
533 .rounded(px(radius::MD))
534 .overflow_hidden()
535 .bg(t.raise())
536 .children(surface),
537 )
538}
539
540fn more_tile(entity: &Entity<Yumush>, more: usize, palette: Palette) -> impl IntoElement {
541 let t = palette.tokens;
542 let entity = entity.clone();
543 div()
544 .id("stage_more")
545 .cursor_pointer()
546 .flex()
547 .flex_col()
548 .flex_shrink_0()
549 .gap(px(space::SM))
550 .w(px(TILE_W))
551 .on_click(move |_, _, cx| {
552 entity.update(cx, |yumush, cx| {
553 yumush.close_viewer(cx);
554 yumush.set_stage(Stage::Grid, cx);
555 });
556 })
557 .child(super::parts::band(space::XS).h(px(size::ICON)).child(words(
558 w().camera_view.streams,
559 Text::Label,
560 Ink::Dim,
561 t,
562 )))
563 .child(
564 div()
565 .h(px(TILE_H))
566 .flex()
567 .items_center()
568 .justify_center()
569 .rounded(px(radius::MD))
570 .bg(t.raise())
571 .child(words(format!("+{more}"), Text::Title, Ink::Paper, t)),
572 )
573}
574
575fn grid_cell(
576 entity: &Entity<Yumush>,
577 yumush: &Yumush,
578 palette: Palette,
579 (user_id, kind): (Id, Kind),
580 (width, height): (f32, f32),
581) -> AnyElement {
582 let entity = entity.clone();
583 let surface = yumush
584 .chat
585 .tiles
586 .get(&(user_id, kind))
587 .filter(|tile| tile.shown)
588 .map(|tile| tile.surface.clone());
589 div()
590 .id(format!("grid_{user_id}_{kind:?}"))
591 .w(px(width))
592 .h(px(height))
593 .flex_none()
594 .relative()
595 .overflow_hidden()
596 .cursor_pointer()
597 .tip(w().camera_view.watch)
598 .on_click(move |_, window, cx| {
599 entity.update(cx, |yumush, cx| {
600 yumush.toggle_viewer(user_id, kind, window, cx)
601 });
602 })
603 .child(div().absolute().inset_0().children(surface))
604 .child(
605 tile_label(yumush, palette, (user_id, kind))
606 .absolute()
607 .left(px(space::MD))
608 .top(px(space::MD)),
609 )
610 .into_any_element()
611}
612
613pub(super) fn tile_label(yumush: &Yumush, palette: Palette, source: (Id, Kind)) -> Div {
614 let t = palette.tokens;
615 let user_id = source.0;
616 let muted = yumush.chat.server_muted.contains(&user_id)
617 || (yumush.is_me(user_id) && yumush.chat.voice_flags().is_some_and(|(muted, _)| muted));
618
619 scrim(t)
620 .child(tile_name(yumush, source, true, t))
621 .children(muted.then(|| super::parts::small_icon(IconName::MicOff).text_color(t.bad())))
622}
623
624fn tile_name(
625 yumush: &Yumush,
626 (user_id, kind): (Id, Kind),
627 focused: bool,
628 t: super::style::Tokens,
629) -> Div {
630 let name = yumush
631 .chat
632 .author(user_id)
633 .map_or_else(|| user_id.to_string(), |user| user.username.clone());
634 let audible = yumush.chat.waves.audible(user_id);
635 let ink = if audible || focused {
636 Ink::Paper
637 } else {
638 Ink::Dim
639 };
640 super::parts::band(space::XS)
641 .h(px(size::ICON))
642 .child(
643 super::parts::small_icon(match kind {
644 Kind::Camera => IconName::Video,
645 Kind::Screen => IconName::ScreenShare,
646 })
647 .text_color(if audible { t.person(user_id) } else { t.dim() }),
648 )
649 .child(
650 words(name, Text::Label, ink, t)
651 .truncate()
652 .when(audible, |name| name.text_color(t.person(user_id))),
653 )
654}
655
656#[cfg(test)]
657mod tests {
658 use super::{WIDE, grid_columns};
659
660 #[test]
661 fn grid_columns_fill_the_shape() {
662 assert_eq!(grid_columns(&[WIDE], (1300., 900.)), 1);
663 assert_eq!(grid_columns(&[WIDE, WIDE], (1300., 900.)), 1);
664 assert_eq!(grid_columns(&[WIDE, WIDE], (2400., 600.)), 2);
665 assert_eq!(grid_columns(&[WIDE; 4], (1600., 900.)), 2);
666 }
667}