BlueGit

ict rusty-teams

Files

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

overlay.rs

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