BlueGit

ict rusty-teams

Files

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

overlay.rs

overlay.rs 17.8 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_wanted, mini_work_area, parse_position,
11};
12use crate::app_state::AppState;
13use crate::notify::platform::{self, NativeHandle, ScreenRect, ShareGeometry, WorkArea};
14use crate::views::call_mini_window::MiniWindowView;
15use crate::views::call_pop_out::{POP_OUT_SIZE, POP_OUT_TITLE, SharePopOutView};
16use crate::views::share_bar::{ShareBarView, ShareBorderView};
17
18const TICK: Duration = Duration::from_millis(100);
19const IDLE_TICK: Duration = Duration::from_millis(250);
20const SLOW_TICK_EVERY: u32 = 5;
21const BORDER_SIDES: usize = 4;
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
24enum Role {
25 Bar,
26 Mini,
27 Border(usize),
28}
29
30struct Placed {
31 handle: AnyWindowHandle,
32 native: Option<NativeHandle>,
33 rect: Option<ScreenRect>,
34 anchor: Option<NativeHandle>,
35 visible: bool,
36}
37
38impl Placed {
39 fn place(&mut self, rect: ScreenRect, cx: &mut App) {
40 if self.rect == Some(rect) {
41 return;
42 }
43 self.rect = Some(rect);
44 let Some(native) = self.native else {
45 return;
46 };
47 match self.anchor {
48 Some(_) => {
49 platform::place_rect(native, rect.left, rect.top, rect.width(), rect.height())
50 }
51 None => platform::place(native, rect.left, rect.top, rect.width(), rect.height()),
52 }
53 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
54 self.handle
55 .update(cx, |_, window, cx| window.bounds_changed(cx))
56 .ok();
57 }
58
59 fn set_visible(&mut self, visible: bool) {
60 let Some(native) = self.native else {
61 return;
62 };
63 if self.visible == visible {
64 return;
65 }
66 self.visible = visible;
67 if visible {
68 platform::show_window_inactive(native);
69 } else {
70 platform::hide_window(native);
71 }
72 }
73}
74
75struct ShareSession {
76 started: Instant,
77 source: Option<ShareSource>,
78 geometry: Option<ShareGeometry>,
79}
80
81pub struct CallWindows {
82 app: Entity<AppState>,
83 main_window: AnyWindowHandle,
84 main_native: Option<NativeHandle>,
85 work_area: Option<WorkArea>,
86 minimized: bool,
87 windows: HashMap<Role, Placed>,
88 opening: HashSet<Role>,
89 share: Option<ShareSession>,
90 pop_out: Option<AnyWindowHandle>,
91 pop_out_opening: bool,
92 pinned: bool,
93 bar_idle_since: Instant,
94 bar_collapsed: bool,
95 shown_second: u64,
96 mini_saved: Option<(i32, i32)>,
97 mini_seen: Option<(i32, i32)>,
98 ticks: u32,
99}
100
101fn display_work_area(cx: &App) -> Option<WorkArea> {
102 let bounds = cx.primary_display()?.bounds();
103 let left = f32::from(bounds.origin.x) as i32;
104 let top = f32::from(bounds.origin.y) as i32;
105 Some(WorkArea {
106 left,
107 top,
108 right: left + f32::from(bounds.size.width) as i32,
109 bottom: top + f32::from(bounds.size.height) as i32,
110 scale: 1.,
111 })
112}
113
114fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
115 let bounds = Bounds::new(
116 point(px(rect.left as f32 / scale), px(rect.top as f32 / scale)),
117 size(
118 px(rect.width() as f32 / scale),
119 px(rect.height() as f32 / scale),
120 ),
121 );
122 WindowOptions {
123 window_bounds: Some(WindowBounds::Windowed(bounds)),
124 titlebar: None,
125 focus: false,
126 show: true,
127 kind: WindowKind::PopUp,
128 is_movable: role == Role::Mini,
129 is_resizable: false,
130 is_minimizable: false,
131 window_background: match role {
132 Role::Border(_) => WindowBackgroundAppearance::Opaque,
133 Role::Bar | Role::Mini => WindowBackgroundAppearance::Transparent,
134 },
135 ..Default::default()
136 }
137}
138
139impl CallWindows {
140 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
141 let mini_saved = app
142 .read(cx)
143 .store
144 .meta(MINI_POSITION_KEY)
145 .ok()
146 .flatten()
147 .and_then(|text| parse_position(&text));
148 let windows = CallWindows {
149 app,
150 main_window: window.window_handle(),
151 main_native: platform::native_handle(window),
152 work_area: None,
153 minimized: false,
154 windows: HashMap::new(),
155 opening: HashSet::new(),
156 share: None,
157 pop_out: None,
158 pop_out_opening: false,
159 pinned: false,
160 bar_idle_since: Instant::now(),
161 bar_collapsed: false,
162 shown_second: 0,
163 mini_saved,
164 mini_seen: None,
165 ticks: 0,
166 };
167 cx.spawn(async move |this, cx| {
168 let mut pause = TICK;
169 loop {
170 cx.background_executor().timer(pause).await;
171 match this.update(cx, |windows, cx| windows.tick(cx)) {
172 Ok(next_pause) => pause = next_pause,
173 Err(_) => break,
174 }
175 }
176 })
177 .detach();
178 windows
179 }
180
181 pub fn app(&self) -> &Entity<AppState> {
182 &self.app
183 }
184
185 pub fn pinned(&self) -> bool {
186 self.pinned
187 }
188
189 pub fn bar_collapsed(&self) -> bool {
190 self.bar_collapsed
191 }
192
193 pub fn share_text(&self) -> String {
194 let Some(session) = &self.share else {
195 return String::new();
196 };
197 let what = match session.source.as_ref().map(|source| source.kind) {
198 Some(ShareKind::Window) => "window",
199 _ => "screen",
200 };
201 format!(
202 "Sharing {what} {}",
203 format_elapsed(session.started.elapsed())
204 )
205 }
206
207 pub fn toggle_pin(&mut self, cx: &mut Context<Self>) {
208 self.pinned = !self.pinned;
209 self.bar_idle_since = Instant::now();
210 cx.notify();
211 }
212
213 pub fn wake_bar(&mut self, cx: &mut Context<Self>) {
214 self.bar_idle_since = Instant::now();
215 if self.bar_collapsed {
216 self.bar_collapsed = false;
217 cx.notify();
218 }
219 }
220
221 pub fn return_to_call(&mut self, cx: &mut Context<Self>) {
222 if let Some(native) = self.main_native {
223 platform::restore_and_raise(native);
224 }
225 self.main_window
226 .update(cx, |_, window, _| window.activate_window())
227 .ok();
228 self.app.update(cx, |state, cx| state.show_call(true, cx));
229 }
230
231 fn idle(&self, cx: &App) -> bool {
232 self.app.read(cx).call.is_none()
233 && self.share.is_none()
234 && self.windows.is_empty()
235 && self.opening.is_empty()
236 }
237
238 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
239 if self.idle(cx) {
240 return IDLE_TICK;
241 }
242 self.ticks = self.ticks.wrapping_add(1);
243 let slow = self.ticks % SLOW_TICK_EVERY == 0;
244 self.refresh_main_window();
245 self.sync_share(slow, cx);
246 self.sync_pop_out(cx);
247 self.sync_mini(cx);
248 if slow {
249 self.track_mini_position(cx);
250 }
251 TICK
252 }
253
254 fn refresh_main_window(&mut self) {
255 let Some(native) = self.main_native else {
256 return;
257 };
258 self.minimized = platform::window_minimized(native);
259 if !self.minimized {
260 self.work_area = platform::work_area(native).or(self.work_area);
261 }
262 }
263
264 fn local_share(&self, cx: &App) -> Option<Option<ShareSource>> {
265 let model = &self.app.read(cx).call.as_ref()?.model;
266 let label = model.local_share.as_ref()?;
267 Some(
268 model
269 .share_sources
270 .iter()
271 .find(|source| &source.label() == label)
272 .cloned(),
273 )
274 }
275
276 fn sync_share(&mut self, refresh_geometry: bool, cx: &mut Context<Self>) {
277 let Some(source) = self.local_share(cx) else {
278 self.end_share(cx);
279 return;
280 };
281 let mut refresh_geometry = refresh_geometry;
282 if self.share.is_none() {
283 self.bar_idle_since = Instant::now();
284 self.share = Some(ShareSession {
285 started: Instant::now(),
286 source: None,
287 geometry: None,
288 });
289 refresh_geometry = true;
290 }
291 let Some(session) = self.share.as_mut() else {
292 return;
293 };
294 session.source = source;
295 let shared_window = session
296 .source
297 .as_ref()
298 .filter(|source| source.kind == ShareKind::Window)
299 .map(|source| source.id as NativeHandle);
300 if refresh_geometry || shared_window.is_some() {
301 session.geometry = session
302 .source
303 .as_ref()
304 .and_then(|source| platform::share_geometry(source.kind, source.id));
305 }
306 let geometry = session.geometry;
307 let elapsed_seconds = session.started.elapsed().as_secs();
308 let Some(work) = geometry
309 .map(|geometry| geometry.work)
310 .or(self.work_area)
311 .or_else(|| display_work_area(cx))
312 else {
313 return;
314 };
315 let can_collapse = self
316 .windows
317 .get(&Role::Bar)
318 .is_some_and(|placed| placed.native.is_some());
319 let collapsed = can_collapse && bar_collapsed(self.pinned, self.bar_idle_since.elapsed());
320 if collapsed != self.bar_collapsed || elapsed_seconds != self.shown_second {
321 self.bar_collapsed = collapsed;
322 self.shown_second = elapsed_seconds;
323 cx.notify();
324 }
325 self.ensure_window(Role::Bar, bar_rect(work, collapsed), work.scale, true, cx);
326 match border_visibility(shared_window.is_some(), geometry.is_some()) {
327 BorderVisibility::Show => {
328 let thickness = border_thickness(work.scale);
329 let rects = geometry.map(|geometry| border_rects(geometry.target, thickness));
330 for (side, rect) in rects.into_iter().flatten().enumerate() {
331 if let Some(placed) = self.windows.get_mut(&Role::Border(side)) {
332 placed.anchor = shared_window;
333 placed.set_visible(true);
334 }
335 self.ensure_window(Role::Border(side), rect, work.scale, true, cx);
336 }
337 self.restack_borders(shared_window);
338 }
339 BorderVisibility::Hide => {
340 for side in 0..BORDER_SIDES {
341 if let Some(placed) = self.windows.get_mut(&Role::Border(side)) {
342 placed.set_visible(false);
343 }
344 }
345 }
346 BorderVisibility::Close => self.close_borders(cx),
347 }
348 }
349
350 fn end_share(&mut self, cx: &mut Context<Self>) {
351 if self.share.take().is_none() {
352 return;
353 }
354 self.bar_collapsed = false;
355 self.close(Role::Bar, cx);
356 self.close_borders(cx);
357 }
358
359 fn close_borders(&mut self, cx: &mut Context<Self>) {
360 for side in 0..BORDER_SIDES {
361 self.close(Role::Border(side), cx);
362 }
363 }
364
365 fn sync_pop_out(&mut self, cx: &mut Context<Self>) {
366 let wanted = self
367 .app
368 .read(cx)
369 .call
370 .as_ref()
371 .is_some_and(|call| call.share_stage.popped && call.model.screen_sharer.is_some());
372 match (wanted, self.pop_out) {
373 (true, None) => self.open_pop_out(cx),
374 (false, Some(handle)) => {
375 self.pop_out = None;
376 handle
377 .update(cx, |_, window, _| window.remove_window())
378 .ok();
379 }
380 (true, Some(handle)) => {
381 if handle.update(cx, |_, _, _| ()).is_err() {
382 self.pop_out = None;
383 self.app
384 .update(cx, |state, cx| state.return_stage_from_pop_out(cx));
385 }
386 }
387 (false, None) => {}
388 }
389 }
390
391 fn open_pop_out(&mut self, cx: &mut Context<Self>) {
392 if self.pop_out_opening {
393 return;
394 }
395 self.pop_out_opening = true;
396 let controller = cx.entity();
397 let app = self.app.clone();
398 let options = WindowOptions {
399 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
400 None,
401 size(px(POP_OUT_SIZE.0), px(POP_OUT_SIZE.1)),
402 cx,
403 ))),
404 titlebar: Some(TitlebarOptions {
405 title: Some(POP_OUT_TITLE.into()),
406 ..Default::default()
407 }),
408 ..Default::default()
409 };
410 // open_window draws right away, and the view reads the app entity while rendering.
411 cx.defer(move |cx| {
412 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
413 cx.new(|cx| SharePopOutView::new(app, window, cx))
414 });
415 controller.update(cx, |this, _| {
416 this.pop_out_opening = false;
417 this.pop_out = opened.ok().map(|(handle, _)| handle);
418 });
419 });
420 }
421
422 fn sync_mini(&mut self, cx: &mut Context<Self>) {
423 let in_call = self.app.read(cx).call.is_some();
424 let work = self.work_area.or_else(|| display_work_area(cx));
425 match work.filter(|_| mini_wanted(in_call, self.minimized)) {
426 Some(main_work) => {
427 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
428 let rect = mini_rect(work, self.mini_saved);
429 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
430 }
431 None => self.close(Role::Mini, cx),
432 }
433 }
434
435 fn track_mini_position(&mut self, cx: &mut Context<Self>) {
436 let Some(native) = self
437 .windows
438 .get(&Role::Mini)
439 .and_then(|placed| placed.native)
440 else {
441 return;
442 };
443 let Some(rect) = platform::window_rect(native) else {
444 return;
445 };
446 let position = (rect.left, rect.top);
447 let settled = self.mini_seen == Some(position);
448 self.mini_seen = Some(position);
449 if settled && self.mini_saved != Some(position) {
450 self.mini_saved = Some(position);
451 let _ = self
452 .app
453 .read(cx)
454 .store
455 .set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
456 }
457 }
458
459 fn restack_borders(&self, shared_window: Option<NativeHandle>) {
460 let Some(shared) = shared_window else {
461 return;
462 };
463 let group: Vec<NativeHandle> = (0..BORDER_SIDES)
464 .filter_map(|side| self.windows.get(&Role::Border(side))?.native)
465 .collect();
466 platform::stack_group_above(shared, &group);
467 }
468
469 fn ensure_window(
470 &mut self,
471 role: Role,
472 rect: ScreenRect,
473 scale: f32,
474 follow: bool,
475 cx: &mut Context<Self>,
476 ) {
477 match self.windows.get_mut(&role) {
478 Some(placed) => {
479 if placed.rect.is_none() || follow && placed.rect != Some(rect) {
480 placed.place(rect, cx);
481 }
482 }
483 None => self.open(role, rect, scale, cx),
484 }
485 }
486
487 fn close(&mut self, role: Role, cx: &mut Context<Self>) {
488 if let Some(placed) = self.windows.remove(&role) {
489 placed
490 .handle
491 .update(cx, |_, window, _| window.remove_window())
492 .ok();
493 }
494 }
495
496 fn open(&mut self, role: Role, rect: ScreenRect, scale: f32, cx: &mut Context<Self>) {
497 if !self.opening.insert(role) {
498 return;
499 }
500 let controller = cx.entity();
501 let options = overlay_options(role, rect, scale);
502 // open_window draws right away, and the views read this entity while rendering.
503 cx.defer(move |cx| {
504 let view_controller = controller.clone();
505 let opened = cx.open_window(options, move |window, cx| {
506 let view: AnyView = match role {
507 Role::Bar => cx.new(|cx| ShareBarView::new(view_controller, cx)).into(),
508 Role::Mini => cx.new(|cx| MiniWindowView::new(view_controller, cx)).into(),
509 Role::Border(_) => cx.new(|_| ShareBorderView).into(),
510 };
511 cx.new(|cx| base::Root::new(view, window, cx).bg(transparent_black()))
512 });
513 let placed = opened.ok().map(|handle| {
514 let handle = AnyWindowHandle::from(handle);
515 let native = handle
516 .update(cx, |_, window, _| platform::native_handle(window))
517 .ok()
518 .flatten();
519 if let Some(native) = native {
520 platform::prepare_toast_window(native);
521 platform::exclude_from_capture(native);
522 }
523 if matches!(role, Role::Border(_)) {
524 handle
525 .update(cx, |_, window, _| {
526 platform::make_window_click_through(window)
527 })
528 .ok();
529 }
530 Placed {
531 handle,
532 native,
533 rect: None,
534 anchor: None,
535 visible: true,
536 }
537 });
538 controller.update(cx, |this, _| {
539 this.opening.remove(&role);
540 if let Some(placed) = placed {
541 this.windows.insert(role, placed);
542 }
543 });
544 });
545 }
546}