BlueGit

ict rusty-teams

Files

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

overlay.rs

overlay.rs 17.7 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 self.rect = Some(rect);
41 let Some(native) = self.native else {
42 return;
43 };
44 match self.anchor {
45 Some(anchor) => platform::place_above(
46 native,
47 anchor,
48 rect.left,
49 rect.top,
50 rect.width(),
51 rect.height(),
52 ),
53 None => platform::place(native, rect.left, rect.top, rect.width(), rect.height()),
54 }
55 // WM_SIZE arrives while the app is borrowed, so GPUI drops its own resize report.
56 self.handle
57 .update(cx, |_, window, cx| window.bounds_changed(cx))
58 .ok();
59 }
60
61 fn set_visible(&mut self, visible: bool) {
62 let Some(native) = self.native else {
63 return;
64 };
65 if self.visible == visible {
66 return;
67 }
68 self.visible = visible;
69 if visible {
70 platform::show_window_inactive(native);
71 } else {
72 platform::hide_window(native);
73 }
74 }
75
76 fn restack(&self) {
77 if let (Some(native), Some(anchor)) = (self.native, self.anchor) {
78 platform::stack_above(native, anchor);
79 }
80 }
81}
82
83struct ShareSession {
84 started: Instant,
85 source: Option<ShareSource>,
86 geometry: Option<ShareGeometry>,
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 ticks: u32,
107}
108
109fn display_work_area(cx: &App) -> Option<WorkArea> {
110 let bounds = cx.primary_display()?.bounds();
111 let left = f32::from(bounds.origin.x) as i32;
112 let top = f32::from(bounds.origin.y) as i32;
113 Some(WorkArea {
114 left,
115 top,
116 right: left + f32::from(bounds.size.width) as i32,
117 bottom: top + f32::from(bounds.size.height) as i32,
118 scale: 1.,
119 })
120}
121
122fn overlay_options(role: Role, rect: ScreenRect, scale: f32) -> WindowOptions {
123 let bounds = Bounds::new(
124 point(px(rect.left as f32 / scale), px(rect.top as f32 / scale)),
125 size(
126 px(rect.width() as f32 / scale),
127 px(rect.height() as f32 / scale),
128 ),
129 );
130 WindowOptions {
131 window_bounds: Some(WindowBounds::Windowed(bounds)),
132 titlebar: None,
133 focus: false,
134 show: true,
135 kind: WindowKind::PopUp,
136 is_movable: role == Role::Mini,
137 is_resizable: false,
138 is_minimizable: false,
139 window_background: match role {
140 Role::Border(_) => WindowBackgroundAppearance::Opaque,
141 Role::Bar | Role::Mini => WindowBackgroundAppearance::Transparent,
142 },
143 ..Default::default()
144 }
145}
146
147impl CallWindows {
148 pub fn new(app: Entity<AppState>, window: &mut Window, cx: &mut Context<Self>) -> Self {
149 let mini_saved = app
150 .read(cx)
151 .store
152 .meta(MINI_POSITION_KEY)
153 .ok()
154 .flatten()
155 .and_then(|text| parse_position(&text));
156 let windows = CallWindows {
157 app,
158 main_window: window.window_handle(),
159 main_native: platform::native_handle(window),
160 work_area: None,
161 minimized: false,
162 windows: HashMap::new(),
163 opening: HashSet::new(),
164 share: None,
165 pop_out: None,
166 pop_out_opening: false,
167 pinned: false,
168 bar_idle_since: Instant::now(),
169 bar_collapsed: false,
170 shown_second: 0,
171 mini_saved,
172 mini_seen: None,
173 ticks: 0,
174 };
175 cx.spawn(async move |this, cx| {
176 let mut pause = TICK;
177 loop {
178 cx.background_executor().timer(pause).await;
179 match this.update(cx, |windows, cx| windows.tick(cx)) {
180 Ok(next_pause) => pause = next_pause,
181 Err(_) => break,
182 }
183 }
184 })
185 .detach();
186 windows
187 }
188
189 pub fn app(&self) -> &Entity<AppState> {
190 &self.app
191 }
192
193 pub fn pinned(&self) -> bool {
194 self.pinned
195 }
196
197 pub fn bar_collapsed(&self) -> bool {
198 self.bar_collapsed
199 }
200
201 pub fn share_text(&self) -> String {
202 let Some(session) = &self.share else {
203 return String::new();
204 };
205 let what = match session.source.as_ref().map(|source| source.kind) {
206 Some(ShareKind::Window) => "window",
207 _ => "screen",
208 };
209 format!(
210 "Sharing {what} {}",
211 format_elapsed(session.started.elapsed())
212 )
213 }
214
215 pub fn toggle_pin(&mut self, cx: &mut Context<Self>) {
216 self.pinned = !self.pinned;
217 self.bar_idle_since = Instant::now();
218 cx.notify();
219 }
220
221 pub fn wake_bar(&mut self, cx: &mut Context<Self>) {
222 self.bar_idle_since = Instant::now();
223 if self.bar_collapsed {
224 self.bar_collapsed = false;
225 cx.notify();
226 }
227 }
228
229 pub fn return_to_call(&mut self, cx: &mut Context<Self>) {
230 if let Some(native) = self.main_native {
231 platform::restore_and_raise(native);
232 }
233 self.main_window
234 .update(cx, |_, window, _| window.activate_window())
235 .ok();
236 self.app.update(cx, |state, cx| state.show_call(true, cx));
237 }
238
239 fn idle(&self, cx: &App) -> bool {
240 self.app.read(cx).call.is_none()
241 && self.share.is_none()
242 && self.windows.is_empty()
243 && self.opening.is_empty()
244 }
245
246 fn tick(&mut self, cx: &mut Context<Self>) -> Duration {
247 if self.idle(cx) {
248 return IDLE_TICK;
249 }
250 self.ticks = self.ticks.wrapping_add(1);
251 let slow = self.ticks % SLOW_TICK_EVERY == 0;
252 self.refresh_main_window();
253 self.sync_share(slow, cx);
254 self.sync_pop_out(cx);
255 self.sync_mini(cx);
256 if slow {
257 self.track_mini_position(cx);
258 }
259 TICK
260 }
261
262 fn refresh_main_window(&mut self) {
263 let Some(native) = self.main_native else {
264 return;
265 };
266 self.minimized = platform::window_minimized(native);
267 if !self.minimized {
268 self.work_area = platform::work_area(native).or(self.work_area);
269 }
270 }
271
272 fn local_share(&self, cx: &App) -> Option<Option<ShareSource>> {
273 let model = &self.app.read(cx).call.as_ref()?.model;
274 let label = model.local_share.as_ref()?;
275 Some(
276 model
277 .share_sources
278 .iter()
279 .find(|source| &source.label() == label)
280 .cloned(),
281 )
282 }
283
284 fn sync_share(&mut self, refresh_geometry: bool, cx: &mut Context<Self>) {
285 let Some(source) = self.local_share(cx) else {
286 self.end_share(cx);
287 return;
288 };
289 let mut refresh_geometry = refresh_geometry;
290 if self.share.is_none() {
291 self.bar_idle_since = Instant::now();
292 self.share = Some(ShareSession {
293 started: Instant::now(),
294 source: None,
295 geometry: None,
296 });
297 refresh_geometry = true;
298 }
299 let Some(session) = self.share.as_mut() else {
300 return;
301 };
302 session.source = source;
303 let shared_window = session
304 .source
305 .as_ref()
306 .filter(|source| source.kind == ShareKind::Window)
307 .map(|source| source.id as NativeHandle);
308 if refresh_geometry || shared_window.is_some() {
309 session.geometry = session
310 .source
311 .as_ref()
312 .and_then(|source| platform::share_geometry(source.kind, source.id));
313 }
314 let geometry = session.geometry;
315 let elapsed_seconds = session.started.elapsed().as_secs();
316 let Some(work) = geometry
317 .map(|geometry| geometry.work)
318 .or(self.work_area)
319 .or_else(|| display_work_area(cx))
320 else {
321 return;
322 };
323 let can_collapse = self
324 .windows
325 .get(&Role::Bar)
326 .is_some_and(|placed| placed.native.is_some());
327 let collapsed = can_collapse && bar_collapsed(self.pinned, self.bar_idle_since.elapsed());
328 if collapsed != self.bar_collapsed || elapsed_seconds != self.shown_second {
329 self.bar_collapsed = collapsed;
330 self.shown_second = elapsed_seconds;
331 cx.notify();
332 }
333 self.ensure_window(Role::Bar, bar_rect(work, collapsed), work.scale, true, cx);
334 match border_visibility(shared_window.is_some(), geometry.is_some()) {
335 BorderVisibility::Show => {
336 let thickness = border_thickness(work.scale);
337 let rects = geometry.map(|geometry| border_rects(geometry.target, thickness));
338 for (side, rect) in rects.into_iter().flatten().enumerate() {
339 if let Some(placed) = self.windows.get_mut(&Role::Border(side)) {
340 placed.anchor = shared_window;
341 placed.set_visible(true);
342 }
343 self.ensure_window(Role::Border(side), rect, work.scale, true, cx);
344 if let Some(placed) = self.windows.get(&Role::Border(side)) {
345 placed.restack();
346 }
347 }
348 }
349 BorderVisibility::Hide => {
350 for side in 0..BORDER_SIDES {
351 if let Some(placed) = self.windows.get_mut(&Role::Border(side)) {
352 placed.set_visible(false);
353 }
354 }
355 }
356 BorderVisibility::Close => self.close_borders(cx),
357 }
358 }
359
360 fn end_share(&mut self, cx: &mut Context<Self>) {
361 if self.share.take().is_none() {
362 return;
363 }
364 self.bar_collapsed = false;
365 self.close(Role::Bar, cx);
366 self.close_borders(cx);
367 }
368
369 fn close_borders(&mut self, cx: &mut Context<Self>) {
370 for side in 0..BORDER_SIDES {
371 self.close(Role::Border(side), cx);
372 }
373 }
374
375 fn sync_pop_out(&mut self, cx: &mut Context<Self>) {
376 let wanted = self
377 .app
378 .read(cx)
379 .call
380 .as_ref()
381 .is_some_and(|call| call.share_stage.popped && call.model.screen_sharer.is_some());
382 match (wanted, self.pop_out) {
383 (true, None) => self.open_pop_out(cx),
384 (false, Some(handle)) => {
385 self.pop_out = None;
386 handle
387 .update(cx, |_, window, _| window.remove_window())
388 .ok();
389 }
390 (true, Some(handle)) => {
391 if handle.update(cx, |_, _, _| ()).is_err() {
392 self.pop_out = None;
393 self.app
394 .update(cx, |state, cx| state.return_stage_from_pop_out(cx));
395 }
396 }
397 (false, None) => {}
398 }
399 }
400
401 fn open_pop_out(&mut self, cx: &mut Context<Self>) {
402 if self.pop_out_opening {
403 return;
404 }
405 self.pop_out_opening = true;
406 let controller = cx.entity();
407 let app = self.app.clone();
408 let options = WindowOptions {
409 window_bounds: Some(WindowBounds::Windowed(Bounds::centered(
410 None,
411 size(px(POP_OUT_SIZE.0), px(POP_OUT_SIZE.1)),
412 cx,
413 ))),
414 titlebar: Some(TitlebarOptions {
415 title: Some(POP_OUT_TITLE.into()),
416 ..Default::default()
417 }),
418 ..Default::default()
419 };
420 // open_window draws right away, and the view reads the app entity while rendering.
421 cx.defer(move |cx| {
422 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
423 cx.new(|cx| SharePopOutView::new(app, window, cx))
424 });
425 controller.update(cx, |this, _| {
426 this.pop_out_opening = false;
427 this.pop_out = opened.ok().map(|(handle, _)| handle);
428 });
429 });
430 }
431
432 fn sync_mini(&mut self, cx: &mut Context<Self>) {
433 let in_call = self.app.read(cx).call.is_some();
434 let work = self.work_area.or_else(|| display_work_area(cx));
435 match work.filter(|_| mini_wanted(in_call, self.minimized)) {
436 Some(main_work) => {
437 let work = mini_work_area(main_work, self.mini_saved, platform::work_area_at);
438 let rect = mini_rect(work, self.mini_saved);
439 self.ensure_window(Role::Mini, rect, work.scale, false, cx);
440 }
441 None => self.close(Role::Mini, cx),
442 }
443 }
444
445 fn track_mini_position(&mut self, cx: &mut Context<Self>) {
446 let Some(native) = self
447 .windows
448 .get(&Role::Mini)
449 .and_then(|placed| placed.native)
450 else {
451 return;
452 };
453 let Some(rect) = platform::window_rect(native) else {
454 return;
455 };
456 let position = (rect.left, rect.top);
457 let settled = self.mini_seen == Some(position);
458 self.mini_seen = Some(position);
459 if settled && self.mini_saved != Some(position) {
460 self.mini_saved = Some(position);
461 let _ = self
462 .app
463 .read(cx)
464 .store
465 .set_meta(MINI_POSITION_KEY, &format_position(position.0, position.1));
466 }
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}