BlueGit

ict rusty-teams

Files

rusty-teams / crates / app / src / call / overlay.rs

overlay.rs

overlay.rs 23.0 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2use std::time::{Duration, Instant};
3
4use calling::{ShareKind, ShareSource};
5use gpui_kit::*;
6
7use super::model::format_elapsed;
8use super::overlay_layout::{
9 BorderVisibility, MINI_POSITION_KEY, bar_collapsed, bar_rect, border_rects, border_thickness,
10 border_visibility, format_position, mini_rect, mini_work_area, parse_position,
11};
12use super::share_overlay::{
13 GALLERY_POSITION_KEY, GalleryLayout, LocalShare, Monitor, Surface, excluded_from_capture,
14 gallery_available_height, gallery_candidates, gallery_layout, gallery_rect,
15 minimize_on_share_start, overlay_plan,
16};
17use crate::app_state::AppState;
18use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
19use crate::views::call_mini_window::MiniWindowView;
20use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
21use crate::views::call_share_gallery::ShareGalleryView;
22use crate::views::share_bar::{ShareBarView, ShareBorderView};
23
24const TICK: Duration = Duration::from_millis(100);
25const IDLE_TICK: Duration = Duration::from_millis(250);
26const SLOW_TICK_EVERY: u32 = 5;
27const BORDER_SIDES: usize = 4;
28
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30enum Role {
31 Bar,
32 Mini,
33 Gallery,
34 Border(usize),
35}
36
37struct Placed {
38 handle: AnyWindowHandle,
39 native: Option<NativeHandle>,
40 rect: Option<ScreenRect>,
41 anchor: Option<NativeHandle>,
42 visible: bool,
43}
44
45impl Placed {
46 fn place(&mut self, rect: ScreenRect, cx: &mut App) {
47 if self.rect == Some(rect) {
48 return;
49 }
50 self.rect = Some(rect);
51 let Some(native) = self.native else {
52 return;
53 };
54 match self.anchor {
55 Some(_) => {
56 platform::place_rect(native, rect.left, rect.top, rect.width(), rect.height())
57 }
58 None => platform::place(native, rect.left, rect.top, rect.width(), rect.height()),
59 }
60 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
61 self.handle
62 .update(cx, |_, window, cx| window.bounds_changed(cx))
63 .ok();
64 }
65
66 fn set_visible(&mut self, visible: bool) {
67 let Some(native) = self.native else {
68 return;
69 };
70 if self.visible == visible {
71 return;
72 }
73 self.visible = visible;
74 if visible {
75 platform::show_window_inactive(native);
76 } else {
77 platform::hide_window(native);
78 }
79 }
80}
81
82struct ShareSession {
83 started: Instant,
84 source: Option<ShareSource>,
85 geometry: Option<ShareGeometry>,
86 minimize_checked: bool,
87}
88
89pub struct CallWindows {
90 app: Entity<AppState>,
91 main_window: AnyWindowHandle,
92 main_native: Option<NativeHandle>,
93 work_area: Option<WorkArea>,
94 minimized: bool,
95 windows: HashMap<Role, Placed>,
96 opening: HashSet<Role>,
97 share: Option<ShareSession>,
98 pop_out: Option<AnyWindowHandle>,
99 pop_out_opening: bool,
100 pinned: bool,
101 bar_idle_since: Instant,
102 bar_collapsed: bool,
103 shown_second: u64,
104 mini_saved: Option<(i32, i32)>,
105 mini_seen: Option<(i32, i32)>,
106 gallery_saved: Option<(i32, i32)>,
107 gallery_seen: Option<(i32, i32)>,
108 gallery_layout: GalleryLayout,
109 speaker_only: bool,
110 main_excluded: bool,
111 minimized_for_share: bool,
112 ticks: u32,
113}
114
115fn display_work_area(cx: &App) -> Option<WorkArea> {
116 let bounds = cx.primary_display()?.bounds();
117 let left = f32::from(bounds.origin.x) as i32;
118 let top = f32::from(bounds.origin.y) as i32;
119 Some(WorkArea {
120 left,
121 top,
122 right: left + f32::from(bounds.size.width) as i32,
123 bottom: top + f32::from(bounds.size.height) as i32,
124 scale: 1.,
125 })
126}
127
128fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
129 let bounds = Bounds::new(
130 point(px(rect.left as f32 / scale), px(rect.top as f32 / scale)),
131 size(
132 px(rect.width() as f32 / scale),
133 px(rect.height() as f32 / scale),
134 ),
135 );
136 WindowOptions {
137 window_bounds: Some(WindowBounds::Windowed(bounds)),
138 titlebar: None,
139 focus: false,
140 show: true,
141 kind: WindowKind::PopUp,
142 is_movable: matches!(role, Role::Mini | Role::Gallery),
143 is_resizable: false,
144 is_minimizable: false,
145 window_background: match role {
146 Role::Border(_) => WindowBackgroundAppearance::Opaque,
147 Role::Bar | Role::Mini | Role::Gallery => WindowBackgroundAppearance::Transparent,
148 },
149 ..Default::default()
150 }
151}
152
153impl CallWindows {
154 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
155 let saved_position = |key: &str, cx: &App| {
156 app.read(cx)
157 .store
158 .meta(key)
159 .ok()
160 .flatten()
161 .and_then(|text| parse_position(&text))
162 };
163 let mini_saved = saved_position(MINI_POSITION_KEY, cx);
164 let gallery_saved = saved_position(GALLERY_POSITION_KEY, cx);
165 let windows = CallWindows {
166 app,
167 main_window: window.window_handle(),
168 main_native: platform::native_handle(window),
169 work_area: None,
170 minimized: false,
171 windows: HashMap::new(),
172 opening: HashSet::new(),
173 share: None,
174 pop_out: None,
175 pop_out_opening: false,
176 pinned: false,
177 bar_idle_since: Instant::now(),
178 bar_collapsed: false,
179 shown_second: 0,
180 mini_saved,
181 mini_seen: None,
182 gallery_saved,
183 gallery_seen: None,
184 gallery_layout: gallery_layout(0, true, f32::MAX),
185 speaker_only: false,
186 main_excluded: false,
187 minimized_for_share: false,
188 ticks: 0,
189 };
190 cx.spawn(async move |this, cx| {
191 let mut pause = TICK;
192 loop {
193 cx.background_executor().timer(pause).await;
194 match this.update(cx, |windows, cx| windows.tick(cx)) {
195 Ok(next_pause) => pause = next_pause,
196 Err(_) => break,
197 }
198 }
199 })
200 .detach();
201 windows
202 }
203
204 pub fn app(&self) -> &Entity<AppState> {
205 &self.app
206 }
207
208 pub fn pinned(&self) -> bool {
209 self.pinned
210 }
211
212 pub fn bar_collapsed(&self) -> bool {
213 self.bar_collapsed
214 }
215
216 pub fn gallery_layout(&self) -> GalleryLayout {
217 self.gallery_layout
218 }
219
220 pub fn sharing(&self) -> bool {
221 self.share.is_some()
222 }
223
224 pub fn toggle_speaker_only(&mut self, cx: &mut Context<Self>) {
225 self.speaker_only = !self.speaker_only;
226 cx.notify();
227 }
228
229 pub fn share_text(&self) -> String {
230 let Some(session) = &self.share else {
231 return String::new();
232 };
233 let what = match session.source.as_ref().map(|source| source.kind) {
234 Some(ShareKind::Window) => "window",
235 _ => "screen",
236 };
237 format!(
238 "Sharing {what} {}",
239 format_elapsed(session.started.elapsed())
240 )
241 }
242
243 pub fn toggle_pin(&mut self, cx: &mut Context<Self>) {
244 self.pinned = !self.pinned;
245 self.bar_idle_since = Instant::now();
246 cx.notify();
247 }
248
249 pub fn wake_bar(&mut self, cx: &mut Context<Self>) {
250 self.bar_idle_since = Instant::now();
251 if self.bar_collapsed {
252 self.bar_collapsed = false;
253 cx.notify();
254 }
255 }
256
257 pub fn return_to_call(&mut self, cx: &mut Context<Self>) {
258 if let Some(native) = self.main_native {
259 platform::restore_and_raise(native);
260 }
261 self.main_window
262 .update(cx, |_, window, _| window.activate_window())
263 .ok();
264 self.app.update(cx, |state, cx| state.show_call(true, cx));
265 }
266
267 fn idle(&self, cx: &App) -> bool {
268 self.app.read(cx).call.is_none()
269 && self.share.is_none()
270 && self.windows.is_empty()
271 && self.opening.is_empty()
272 && !self.main_excluded
273 }
274
275 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
276 if self.idle(cx) {
277 return IDLE_TICK;
278 }
279 self.ticks = self.ticks.wrapping_add(1);
280 let slow = self.ticks % SLOW_TICK_EVERY == 0;
281 self.refresh_main_window();
282 self.sync_share(slow, cx);
283 self.sync_capture_exclusion();
284 self.sync_pop_out(cx);
285 self.sync_monitor(cx);
286 if slow {
287 self.track_position(Role::Mini, cx);
288 self.track_position(Role::Gallery, cx);
289 }
290 TICK
291 }
292
293 fn refresh_main_window(&mut self) {
294 let Some(native) = self.main_native else {
295 return;
296 };
297 let minimized = platform::window_minimized(native);
298 if self.minimized && !minimized {
299 self.minimized_for_share = false;
300 }
301 self.minimized = minimized;
302 if !self.minimized {
303 self.work_area = platform::work_area(native).or(self.work_area);
304 }
305 }
306
307 fn local_share(&self, cx: &App) -> Option<Option<ShareSource>> {
308 let model = &self.app.read(cx).call.as_ref()?.model;
309 let label = model.local_share.as_ref()?;
310 Some(
311 model
312 .share_sources
313 .iter()
314 .find(|source| &source.label() == label)
315 .cloned(),
316 )
317 }
318
319 fn sync_share(&mut self, refresh_geometry: bool, cx: &mut Context<Self>) {
320 let Some(source) = self.local_share(cx) else {
321 self.end_share(cx);
322 return;
323 };
324 let mut refresh_geometry = refresh_geometry;
325 if self.share.is_none() {
326 self.bar_idle_since = Instant::now();
327 self.share = Some(ShareSession {
328 started: Instant::now(),
329 source: None,
330 geometry: None,
331 minimize_checked: false,
332 });
333 refresh_geometry = true;
334 }
335 let Some(session) = self.share.as_mut() else {
336 return;
337 };
338 session.source = source;
339 let shared_window = session
340 .source
341 .as_ref()
342 .filter(|source| source.kind == ShareKind::Window)
343 .map(|source| source.id as NativeHandle);
344 if refresh_geometry || shared_window.is_some() {
345 session.geometry = session
346 .source
347 .as_ref()
348 .and_then(|source| platform::share_geometry(source.kind, source.id));
349 }
350 let geometry = session.geometry;
351 let elapsed_seconds = session.started.elapsed().as_secs();
352 let check_minimize = !std::mem::replace(&mut session.minimize_checked, true);
353 if check_minimize {
354 self.minimize_for_share(geometry.map(|geometry| geometry.target), cx);
355 }
356 let Some(work) = geometry
357 .map(|geometry| geometry.work)
358 .or(self.work_area)
359 .or_else(|| display_work_area(cx))
360 else {
361 return;
362 };
363 let can_collapse = self
364 .windows
365 .get(&Role::Bar)
366 .is_some_and(|placed| placed.native.is_some());
367 let collapsed = can_collapse && bar_collapsed(self.pinned, self.bar_idle_since.elapsed());
368 if collapsed != self.bar_collapsed || elapsed_seconds != self.shown_second {
369 self.bar_collapsed = collapsed;
370 self.shown_second = elapsed_seconds;
371 cx.notify();
372 }
373 self.ensure_window(Role::Bar, bar_rect(work, collapsed), work.scale, true, cx);
374 match border_visibility(shared_window.is_some(), geometry.is_some()) {
375 BorderVisibility::Show => {
376 let thickness = border_thickness(work.scale);
377 let rects = geometry.map(|geometry| border_rects(geometry.target, thickness));
378 for (side, rect) in rects.into_iter().flatten().enumerate() {
379 if let Some(placed) = self.windows.get_mut(&Role::Border(side)) {
380 placed.anchor = shared_window;
381 placed.set_visible(true);
382 }
383 self.ensure_window(Role::Border(side), rect, work.scale, true, cx);
384 }
385 self.restack_borders(shared_window);
386 }
387 BorderVisibility::Hide => {
388 for side in 0..BORDER_SIDES {
389 if let Some(placed) = self.windows.get_mut(&Role::Border(side)) {
390 placed.set_visible(false);
391 }
392 }
393 }
394 BorderVisibility::Close => self.close_borders(cx),
395 }
396 }
397
398 fn local_share_mode(&self) -> LocalShare {
399 let kind = self
400 .share
401 .as_ref()
402 .and_then(|session| session.source.as_ref())
403 .map(|source| source.kind);
404 LocalShare::of(kind, self.share.is_some())
405 }
406
407 fn minimize_for_share(&mut self, shared: Option<ScreenRect>, cx: &mut Context<Self>) {
408 let Some(native) = self.main_native.filter(|_| !self.minimized) else {
409 return;
410 };
411 if !minimize_on_share_start(
412 self.local_share_mode(),
413 platform::window_rect(native),
414 shared,
415 ) {
416 return;
417 }
418 self.minimized_for_share = true;
419 self.main_window
420 .update(cx, |_, window, _| window.minimize_window())
421 .ok();
422 }
423
424 fn sync_capture_exclusion(&mut self) {
425 let Some(native) = self.main_native else {
426 return;
427 };
428 let wanted = excluded_from_capture(Surface::Main, self.local_share_mode());
429 if wanted == self.main_excluded {
430 return;
431 }
432 self.main_excluded = wanted;
433 if wanted {
434 platform::exclude_from_capture(native);
435 } else {
436 platform::include_in_capture(native);
437 }
438 }
439
440 fn end_share(&mut self, cx: &mut Context<Self>) {
441 if self.share.take().is_none() {
442 return;
443 }
444 if std::mem::take(&mut self.minimized_for_share) && self.minimized {
445 self.return_to_call(cx);
446 }
447 self.bar_collapsed = false;
448 self.close(Role::Bar, cx);
449 self.close_borders(cx);
450 }
451
452 fn close_borders(&mut self, cx: &mut Context<Self>) {
453 for side in 0..BORDER_SIDES {
454 self.close(Role::Border(side), cx);
455 }
456 }
457
458 fn sync_pop_out(&mut self, cx: &mut Context<Self>) {
459 let wanted = self
460 .app
461 .read(cx)
462 .call
463 .as_ref()
464 .is_some_and(|call| call.share_stage.popped && call.model.screen_sharer.is_some());
465 match (wanted, self.pop_out) {
466 (true, None) => self.open_pop_out(cx),
467 (false, Some(handle)) => {
468 self.pop_out = None;
469 handle
470 .update(cx, |_, window, _| window.remove_window())
471 .ok();
472 }
473 (true, Some(handle)) => {
474 if handle.update(cx, |_, _, _| ()).is_err() {
475 self.pop_out = None;
476 self.app
477 .update(cx, |state, cx| state.return_stage_from_pop_out(cx));
478 }
479 }
480 (false, None) => {}
481 }
482 }
483
484 fn open_pop_out(&mut self, cx: &mut Context<Self>) {
485 if self.pop_out_opening {
486 return;
487 }
488 self.pop_out_opening = true;
489 let controller = cx.entity();
490 let app = self.app.clone();
491 let options = WindowOptions {
492 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
493 None,
494 size(px(POP_OUT_SIZE.0), px(POP_OUT_SIZE.1)),
495 cx,
496 ))),
497 titlebar: Some(TitlebarOptions {
498 title: Some(POP_OUT_TITLE.into()),
499 ..Default::default()
500 }),
501 ..Default::default()
502 };
503 // open_window draws right away, and the view reads the app entity while rendering.
504 cx.defer(move |cx| {
505 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
506 cx.new(|cx| SharePopOutView::new(app, window, cx))
507 });
508 controller.update(cx, |this, _| {
509 this.pop_out_opening = false;
510 this.pop_out = opened.ok().map(|(handle, _)| handle);
511 });
512 });
513 }
514
515 fn sync_monitor(&mut self, cx: &mut Context<Self>) {
516 let in_call = self.app.read(cx).call.is_some();
517 let plan = overlay_plan(
518 in_call,
519 self.local_share_mode(),
520 self.minimized,
521 self.speaker_only,
522 );
523 let work = self.work_area.or_else(|| display_work_area(cx));
524 match (plan.monitor, work) {
525 (Monitor::Mini, Some(main_work)) => {
526 self.close(Role::Gallery, cx);
527 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
528 let rect = mini_rect(work, self.mini_saved);
529 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
530 }
531 (Monitor::Gallery, Some(main_work)) => {
532 self.close(Role::Mini, cx);
533 self.place_gallery(main_work, cx);
534 }
535 _ => {
536 self.close(Role::Mini, cx);
537 self.close(Role::Gallery, cx);
538 }
539 }
540 }
541
542 fn place_gallery(&mut self, main_work: WorkArea, cx: &mut Context<Self>) {
543 let work = mini_work_area(main_work, self.gallery_saved, platform::work_area_at);
544 let (others, self_tile) = self.app.read(cx).call.as_ref().map_or((0, true), |call| {
545 (
546 gallery_candidates(&call.model).len(),
547 !call.model.view.hide_me,
548 )
549 });
550 let layout = gallery_layout(others, self_tile, gallery_available_height(work));
551 if layout != self.gallery_layout {
552 self.gallery_layout = layout;
553 cx.notify();
554 }
555 let origin = self
556 .windows
557 .get(&Role::Gallery)
558 .and_then(|placed| placed.native)
559 .and_then(platform::window_rect)
560 .map(|rect| (rect.left, rect.top))
561 .or(self.gallery_saved);
562 let rect = gallery_rect(work, layout, origin);
563 match self.windows.get_mut(&Role::Gallery) {
564 Some(placed) => {
565 let size = |rect: ScreenRect| (rect.width(), rect.height());
566 if placed.rect.map(size) != Some(size(rect)) {
567 placed.place(rect, cx);
568 }
569 }
570 None => self.open(Role::Gallery, rect, work.scale, cx),
571 }
572 }
573
574 fn track_position(&mut self, role: Role, cx: &mut Context<Self>) {
575 let Some(native) = self.windows.get(&role).and_then(|placed| placed.native) else {
576 return;
577 };
578 let Some(rect) = platform::window_rect(native) else {
579 return;
580 };
581 let (key, saved, seen) = match role {
582 Role::Mini => (MINI_POSITION_KEY, &mut self.mini_saved, &mut self.mini_seen),
583 Role::Gallery => (
584 GALLERY_POSITION_KEY,
585 &mut self.gallery_saved,
586 &mut self.gallery_seen,
587 ),
588 Role::Bar | Role::Border(_) => return,
589 };
590 let position = (rect.left, rect.top);
591 let settled = *seen == Some(position);
592 *seen = Some(position);
593 if settled && *saved != Some(position) {
594 *saved = Some(position);
595 let _ = self
596 .app
597 .read(cx)
598 .store
599 .set_meta(key, &format_position(position.0, position.1));
600 }
601 }
602
603 fn restack_borders(&self, shared_window: Option<NativeHandle>) {
604 let Some(shared) = shared_window else {
605 return;
606 };
607 let group: Vec<NativeHandle> = (0..BORDER_SIDES)
608 .filter_map(|side| self.windows.get(&Role::Border(side))?.native)
609 .collect();
610 platform::stack_group_above(shared, &group);
611 }
612
613 fn ensure_window(
614 &mut self,
615 role: Role,
616 rect: ScreenRect,
617 scale: f32,
618 follow: bool,
619 cx: &mut Context<Self>,
620 ) {
621 match self.windows.get_mut(&role) {
622 Some(placed) => {
623 if placed.rect.is_none() || follow && placed.rect != Some(rect) {
624 placed.place(rect, cx);
625 }
626 }
627 None => self.open(role, rect, scale, cx),
628 }
629 }
630
631 fn close(&mut self, role: Role, cx: &mut Context<Self>) {
632 if let Some(placed) = self.windows.remove(&role) {
633 placed
634 .handle
635 .update(cx, |_, window, _| window.remove_window())
636 .ok();
637 }
638 }
639
640 fn open(&mut self, role: Role, rect: ScreenRect, scale: f32, cx: &mut Context<Self>) {
641 if !self.opening.insert(role) {
642 return;
643 }
644 let controller = cx.entity();
645 let options = overlay_options(role, rect, scale);
646 // open_window draws right away, and the views read this entity while rendering.
647 cx.defer(move |cx| {
648 let view_controller = controller.clone();
649 let opened = cx.open_window(options, move |window, cx| {
650 let view: AnyView = match role {
651 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
652 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
653 Role::Gallery => cx
654 .new(|cx| ShareGalleryView::new(view_controller, cx))
655 .into(),
656 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
657 };
658 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
659 });
660 let placed = opened.ok().map(|handle| {
661 let handle = AnyWindowHandle::from(handle);
662 let native = handle
663 .update(cx, |_, window, _| platform::native_handle(window))
664 .ok()
665 .flatten();
666 if let Some(native) = native {
667 platform::prepare_toast_window(native);
668 platform::exclude_from_capture(native);
669 }
670 if matches!(role, Role::Border(_)) {
671 handle
672 .update(cx, |_, window, _| {
673 platform::make_window_click_through(window)
674 })
675 .ok();
676 }
677 Placed {
678 handle,
679 native,
680 rect: None,
681 anchor: None,
682 visible: true,
683 }
684 });
685 controller.update(cx, |this, _| {
686 this.opening.remove(&role);
687 if let Some(placed) = placed {
688 this.windows.insert(role, placed);
689 }
690 });
691 });
692 }
693}