leejunyoung5819wayland-android-remote

공개

Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)

651줄24 KB
1//! 호스트 GUI. winit 창 위에 wgpu로 직접 그리고, 입력·설정 UI는 egui로 같은 렌더 패스에 얹는다.
2//! 영상은 이후 같은 wgpu 디바이스에 텍스처로 올려 그린다.
3//!
4//! 창은 두 종류다. 크기가 고정된 메인 창(휴대폰 화면)과, 아이콘 열의 버튼으로 여는 독립 설정 창.
5//! 두 창은 wgpu 디바이스를 공유하고 egui 컨텍스트는 따로 쓴다.
6
7mod clipboard;
8mod conn;
9mod fonts;
10mod icons;
11mod input;
12#[cfg(test)]
13mod interaction_tests;
14mod keymap;
15mod layout;
16mod recent;
17#[cfg(test)]
18mod snapshots;
19mod video_render;
20mod view;
21
22use std::num::NonZeroU32;
23use std::sync::Arc;
24use std::time::{Duration, Instant};
25
26use egui::ViewportId;
27use egui_wgpu::winit::Painter;
28use egui_wgpu::{
29 RendererOptions, SurfaceConfig, WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew,
30 WgpuSetupExisting,
31};
32use egui_winit::winit;
33use winit::application::ApplicationHandler;
34use winit::dpi::LogicalSize;
35use winit::event::WindowEvent;
36use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
37use winit::window::{Window, WindowAttributes, WindowId};
38
39use wayland_android_remote::protocol::{Message, SystemAction};
40
41use conn::{ConnCommand, ConnHandle, Connector, video_request};
42use view::{Actions, View};
43
44/// 창 크기 조절이 멈추고 이만큼 지나면 휴대폰 화면 비율에 맞춘다.
45const SNAP_DELAY: Duration = Duration::from_millis(250);
46
47/// 창이 포커스를 얻은 뒤 클립보드를 다루기까지 기다리는 시간. Wayland 클립보드(smithay-clipboard)는
48/// 자기 스레드에서 키보드 포커스 진입을 따로 받으므로, 그 전에 쓰면 조용히 무시된다.
49const FOCUS_SYNC_DELAY: Duration = Duration::from_millis(150);
50
51/// 설정 창 처음 크기 (논리 픽셀).
52const SETTINGS_SIZE: (f32, f32) = (320.0, 380.0);
53
54/// 휴대폰 화면 비율 `aspect`에서 메인 창의 최소 안쪽 크기.
55fn min_window_size(aspect: f32) -> LogicalSize<f32> {
56 let w = layout::window_size(layout::min_viewport(aspect));
57 LogicalSize::new(w.x, w.y)
58}
59
60fn resize_direction(dir: layout::ResizeDir) -> winit::window::ResizeDirection {
61 use layout::ResizeDir as D;
62 use winit::window::ResizeDirection as W;
63 match dir {
64 D::North => W::North,
65 D::South => W::South,
66 D::East => W::East,
67 D::West => W::West,
68 D::NorthEast => W::NorthEast,
69 D::NorthWest => W::NorthWest,
70 D::SouthEast => W::SouthEast,
71 D::SouthWest => W::SouthWest,
72 }
73}
74
75/// 네트워크 스레드가 UI를 깨울 때 보내는 이벤트.
76#[derive(Debug, Clone, Copy)]
77struct Wake;
78
79/// 이벤트 루프를 만들고 창이 닫힐 때까지 실행한다.
80pub fn run(autoconnect: Option<String>) -> Result<(), Box<dyn std::error::Error>> {
81 let event_loop = EventLoop::<Wake>::with_user_event().build()?;
82 let proxy = event_loop.create_proxy();
83 let connector = Connector::new(Arc::new(move || {
84 let _ = proxy.send_event(Wake);
85 }))?;
86 let mut app = App::new(connector);
87 app.autoconnect = autoconnect;
88 event_loop.run_app(&mut app)?;
89 Ok(())
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq)]
93enum Kind {
94 Main,
95 Settings,
96}
97
98/// 창 하나에 딸린 그리기 상태.
99struct Gfx {
100 window: Arc<Window>,
101 ctx: egui::Context,
102 painter: Painter,
103 egui_winit: egui_winit::State,
104 next_repaint: Option<Instant>,
105}
106
107impl Gfx {
108 fn new(
109 event_loop: &ActiveEventLoop,
110 attrs: WindowAttributes,
111 setup: WgpuSetup,
112 ) -> Result<Self, Box<dyn std::error::Error>> {
113 let window = Arc::new(event_loop.create_window(attrs)?);
114 let ctx = egui::Context::default();
115 ctx.set_visuals(egui::Visuals::dark());
116 fonts::install_korean_font(&ctx);
117
118 let config = WgpuConfiguration {
119 // 프레임 큐를 1장으로 제한해 입력에서 화면까지의 지연을 줄인다.
120 surface: SurfaceConfig::LOW_LATENCY,
121 wgpu_setup: setup,
122 ..Default::default()
123 };
124 let mut painter = pollster::block_on(Painter::new(
125 ctx.clone(),
126 config,
127 false,
128 RendererOptions::default(),
129 ));
130 pollster::block_on(painter.set_window(ViewportId::ROOT, Some(window.clone())))?;
131
132 let egui_winit = egui_winit::State::new(
133 ctx.clone(),
134 ViewportId::ROOT,
135 event_loop,
136 Some(window.scale_factor() as f32),
137 window.theme(),
138 painter.max_texture_side(),
139 );
140 window.request_redraw();
141 Ok(Self {
142 window,
143 ctx,
144 painter,
145 egui_winit,
146 next_repaint: None,
147 })
148 }
149
150 /// 같은 wgpu 디바이스로 새 창을 그리도록 설정을 복제한다.
151 fn shared_setup(&self) -> Option<WgpuSetup> {
152 let rs = self.painter.render_state()?;
153 Some(WgpuSetup::Existing(WgpuSetupExisting {
154 instance: rs.instance.clone(),
155 adapter: rs.adapter.clone(),
156 device: rs.device.clone(),
157 queue: rs.queue.clone(),
158 }))
159 }
160
161 /// egui 한 프레임을 실행하고 그린다.
162 fn frame(&mut self, mut ui_fn: impl FnMut(&mut egui::Ui)) {
163 let raw_input = self.egui_winit.take_egui_input(&self.window);
164 let output = self.ctx.run_ui(raw_input, |ui| ui_fn(ui));
165 self.egui_winit
166 .handle_platform_output(&self.window, output.platform_output);
167 let primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point);
168 let mut textures = output.textures_delta;
169 self.painter.paint_and_update_textures(
170 ViewportId::ROOT,
171 output.pixels_per_point,
172 [0.0, 0.0, 0.0, 1.0],
173 &primitives,
174 &mut textures,
175 Vec::new(),
176 &self.window,
177 );
178
179 let delay = output
180 .viewport_output
181 .get(&ViewportId::ROOT)
182 .map_or(Duration::MAX, |v| v.repaint_delay);
183 if delay.is_zero() {
184 self.window.request_redraw();
185 } else {
186 self.next_repaint = Instant::now().checked_add(delay);
187 }
188 }
189}
190
191struct App {
192 view: View,
193 main: Option<Gfx>,
194 settings: Option<Gfx>,
195 connector: Connector,
196 conn: Option<ConnHandle>,
197 /// 시작 인자로 받은 접속 주소. 창이 뜬 뒤 한 번 연결한다.
198 autoconnect: Option<String>,
199 /// 마지막으로 맞춘 휴대폰 화면 크기와 비율. 창 크기 조절 후 비율 맞추기에 쓴다.
200 snapped_viewport: egui::Vec2,
201 snapped_aspect: f32,
202 /// 메인 창 크기가 마지막으로 바뀐 시각. 잠시 멈추면 비율에 맞춘다.
203 main_resized_at: Option<Instant>,
204 /// 현재 연결의 클립보드 동기화 상태. 연결할 때마다 새로 만든다.
205 clipboard: clipboard::ClipboardState,
206 /// 휴대폰에서 받았지만 메인 창에 포커스가 없어 아직 호스트 클립보드에 쓰지 못한 텍스트.
207 pending_host_clipboard: Option<String>,
208 main_focused: bool,
209 /// 메인 창이 포커스를 얻은 뒤 클립보드를 맞출 시각.
210 focus_sync_at: Option<Instant>,
211}
212
213impl App {
214 fn new(connector: Connector) -> Self {
215 Self {
216 view: View::new(),
217 main: None,
218 settings: None,
219 connector,
220 conn: None,
221 autoconnect: None,
222 snapped_viewport: layout::DEFAULT_VIEWPORT,
223 snapped_aspect: layout::DEFAULT_VIEWPORT.x / layout::DEFAULT_VIEWPORT.y,
224 main_resized_at: None,
225 clipboard: clipboard::ClipboardState::default(),
226 pending_host_clipboard: None,
227 main_focused: false,
228 focus_sync_at: None,
229 }
230 }
231
232 fn init_main(&self, event_loop: &ActiveEventLoop) -> Result<Gfx, Box<dyn std::error::Error>> {
233 let size = self.view.window_size();
234 let attrs = Window::default_attributes()
235 .with_title("Android Remote")
236 .with_decorations(false)
237 .with_resizable(true)
238 .with_inner_size(LogicalSize::new(size.x, size.y))
239 .with_min_inner_size(min_window_size(self.view.video_aspect()));
240 let mut setup = WgpuSetupCreateNew::from_display_handle(event_loop.owned_display_handle());
241 setup.power_preference = egui_wgpu::wgpu::PowerPreference::HighPerformance;
242 let gfx = Gfx::new(event_loop, attrs, WgpuSetup::CreateNew(setup))?;
243 if let Some(rs) = gfx.painter.render_state() {
244 let info = rs.adapter.get_info();
245 log::info!(
246 "GPU: {} ({:?}), 출력 형식 {:?}",
247 info.name,
248 info.backend,
249 rs.target_format
250 );
251 let pipeline = video_render::VideoPipeline::new(&rs.device, rs.target_format);
252 rs.renderer.write().callback_resources.insert(pipeline);
253 }
254 Ok(gfx)
255 }
256
257 fn open_settings(&mut self, event_loop: &ActiveEventLoop) {
258 if let Some(s) = &self.settings {
259 s.window.focus_window();
260 return;
261 }
262 let Some(setup) = self.main.as_ref().and_then(Gfx::shared_setup) else {
263 return;
264 };
265 let attrs = Window::default_attributes()
266 .with_title("Android Remote 설정")
267 .with_inner_size(LogicalSize::new(SETTINGS_SIZE.0, SETTINGS_SIZE.1))
268 .with_min_inner_size(LogicalSize::new(280.0, 300.0));
269 match Gfx::new(event_loop, attrs, setup) {
270 Ok(gfx) => self.settings = Some(gfx),
271 Err(e) => log::error!("설정 창을 열지 못했습니다: {e}"),
272 }
273 }
274
275 fn kind_of(&self, id: WindowId) -> Option<Kind> {
276 if self.main.as_ref().is_some_and(|g| g.window.id() == id) {
277 Some(Kind::Main)
278 } else if self.settings.as_ref().is_some_and(|g| g.window.id() == id) {
279 Some(Kind::Settings)
280 } else {
281 None
282 }
283 }
284
285 fn drain_conn_events(&mut self) {
286 let Some(conn) = &self.conn else { return };
287 let events: Vec<_> = conn.events.try_iter().collect();
288 for event in events {
289 match event {
290 conn::ConnEvent::Clipboard(text, sha) => self.on_phone_clipboard(text, sha),
291 conn::ConnEvent::Ended(reason) => {
292 self.view.on_conn_event(conn::ConnEvent::Ended(reason));
293 self.conn = None;
294 self.follow_video_aspect();
295 return;
296 }
297 event => self.view.on_conn_event(event),
298 }
299 }
300 // 연결 상태 이벤트를 먼저 반영해야 첫 프레임이 버려지지 않는다.
301 if let Some(frame) = self.conn.as_ref().and_then(|c| c.frames.take()) {
302 self.view.set_video_frame(frame);
303 self.follow_video_aspect();
304 }
305 }
306
307 /// 영상 비율이 바뀌면 창을 다시 맞춘다. 세로 ↔ 가로 회전이면 긴 변 길이를 유지해 바로 바꾸고,
308 /// 그 밖의 변화(해상도 변경 등)는 크기 조절이 끝난 것처럼 잠시 뒤 비율만 맞춘다.
309 fn follow_video_aspect(&mut self) {
310 let aspect = self.view.video_aspect();
311 if (aspect - self.snapped_aspect).abs() <= 0.005 {
312 return;
313 }
314 let Some(target) =
315 layout::rotate_viewport(self.snapped_viewport, self.snapped_aspect, aspect)
316 else {
317 self.main_resized_at = Some(Instant::now());
318 return;
319 };
320 self.snapped_viewport = target;
321 self.snapped_aspect = aspect;
322 self.main_resized_at = None;
323 let Some(main) = self.main.as_mut() else {
324 return;
325 };
326 let window = main.window.clone();
327 // 최소 크기를 먼저 바꿔야 가로 화면의 낮은 높이가 막히지 않는다.
328 window.set_min_inner_size(Some(min_window_size(aspect)));
329 let w = layout::window_size(target);
330 if let Some(applied) = window.request_inner_size(LogicalSize::new(w.x, w.y))
331 && let (Some(pw), Some(ph)) = (
332 NonZeroU32::new(applied.width),
333 NonZeroU32::new(applied.height),
334 )
335 {
336 main.painter.on_window_resized(ViewportId::ROOT, pw, ph);
337 }
338 window.request_redraw();
339 }
340
341 /// 휴대폰 클립보드를 호스트 클립보드에 쓴다. 창에 포커스가 없으면 포커스를 얻을 때까지 미룬다
342 /// (Wayland는 포커스 없는 앱의 클립보드 쓰기를 받지 않는다).
343 fn on_phone_clipboard(&mut self, text: String, sha: clipboard::Hash) {
344 let Some(text) = self.clipboard.receive(text, sha) else {
345 return;
346 };
347 if self.main_focused && self.focus_sync_at.is_none() {
348 self.write_host_clipboard(text);
349 } else {
350 self.pending_host_clipboard = Some(text);
351 }
352 }
353
354 fn write_host_clipboard(&mut self, text: String) {
355 if let Some(main) = self.main.as_mut() {
356 log::debug!("휴대폰 클립보드를 호스트에 씁니다 ({} 바이트)", text.len());
357 main.egui_winit.set_clipboard_text(text);
358 }
359 }
360
361 /// 메인 창에서 붙여넣기(Ctrl+V)를 눌렀을 때 휴대폰으로 보낼 메시지.
362 fn resolve_paste(&mut self) -> Message {
363 if let Some(text) = self.pending_host_clipboard.take() {
364 // 휴대폰에서 받은 내용이 가장 최근 것이다. 호스트에도 쓰고 휴대폰 자체 붙여넣기를 한다.
365 self.write_host_clipboard(text);
366 return Message::SystemAction(SystemAction::Paste);
367 }
368 let host = self
369 .main
370 .as_mut()
371 .and_then(|m| m.egui_winit.clipboard_text());
372 self.clipboard.paste(host.as_deref())
373 }
374
375 /// 메인 창이 포커스를 얻고 잠시 뒤: 미뤄 둔 휴대폰 클립보드를 쓰거나, 설정이 켜져 있으면
376 /// 호스트 클립보드를 휴대폰에 미리 넣어 둔다.
377 fn focus_sync(&mut self) {
378 if let Some(text) = self.pending_host_clipboard.take() {
379 self.write_host_clipboard(text);
380 return;
381 }
382 if !self.view.settings().sync_clipboard_on_focus || !self.view.captures_keyboard() {
383 return;
384 }
385 let Some(main) = self.main.as_mut() else {
386 return;
387 };
388 let host = main.egui_winit.clipboard_text();
389 if let (Some(msg), Some(conn)) = (self.clipboard.focus_push(host.as_deref()), &self.conn) {
390 conn.send(ConnCommand::Input(msg));
391 }
392 }
393
394 fn redraw(&mut self, kind: Kind, event_loop: &ActiveEventLoop) {
395 self.drain_conn_events();
396 let mut actions = Actions::default();
397 let view = &mut self.view;
398 match kind {
399 Kind::Main => {
400 if let Some(gfx) = self.main.as_mut() {
401 gfx.frame(|ui| view.ui(ui, &mut actions));
402 }
403 }
404 Kind::Settings => {
405 if let Some(gfx) = self.settings.as_mut() {
406 gfx.frame(|ui| view.settings_ui(ui, &mut actions));
407 }
408 }
409 }
410 self.apply(actions, event_loop);
411 }
412
413 fn apply(&mut self, actions: Actions, event_loop: &ActiveEventLoop) {
414 if actions.close {
415 event_loop.exit();
416 return;
417 }
418 if let Some(main) = &self.main {
419 let window = &main.window;
420 if let Some(dir) = actions.start_resize {
421 if let Err(e) = window.drag_resize_window(resize_direction(dir)) {
422 log::debug!("창 크기 조절 실패: {e}");
423 }
424 } else if actions.start_drag
425 && let Err(e) = window.drag_window()
426 {
427 log::debug!("창 이동 실패: {e}");
428 }
429 if actions.minimize {
430 window.set_minimized(true);
431 }
432 }
433 if actions.open_settings {
434 self.open_settings(event_loop);
435 }
436 if let Some(target) = actions.forget_device {
437 self.connector.forget_device(target);
438 }
439 if actions.disconnect {
440 self.conn = None;
441 self.view.reset_to_disconnected();
442 self.follow_video_aspect();
443 self.request_redraw_all();
444 }
445 if let Some(target) = actions.connect {
446 let s = self.view.settings();
447 let req = video_request(s.max_size, s.max_fps, s.bitrate_mbps);
448 self.conn = Some(self.connector.start(target, req, s.keep_screen_on));
449 self.clipboard = clipboard::ClipboardState::default();
450 self.pending_host_clipboard = None;
451 self.request_redraw_all();
452 }
453 if self.conn.is_some() {
454 if let Some(action) = actions.system_action {
455 self.send(ConnCommand::System(action));
456 }
457 for msg in actions.input {
458 // 입력 처리는 붙여넣기를 SYSTEM_ACTION(PASTE) 자리로 남긴다. 그 자리에서 호스트
459 // 클립보드를 읽어 바꿔 보내므로 앞뒤 키 입력과 순서가 유지된다.
460 let msg = match msg {
461 Message::SystemAction(SystemAction::Paste) => self.resolve_paste(),
462 other => other,
463 };
464 self.send(ConnCommand::Input(msg));
465 }
466 if actions.video_settings_changed {
467 let s = self.view.settings();
468 self.send(ConnCommand::RequestVideo(video_request(
469 s.max_size,
470 s.max_fps,
471 s.bitrate_mbps,
472 )));
473 }
474 }
475 }
476
477 /// 창 크기가 바뀔 때마다(가장자리를 끄는 중에도) 휴대폰 화면 비율에 맞는 크기로 바로 고친다.
478 ///
479 /// Wayland에서는 컴포지터가 제안한 크기 대신 앱이 다른 크기로 커밋할 수 있고, 컴포지터는
480 /// 끌고 있는 반대쪽 가장자리를 고정한 채 그 크기를 쓴다. X11에서는 창 관리자가 다시 맞춘다.
481 fn keep_main_aspect(&mut self) {
482 let Some(main) = self.main.as_mut() else {
483 return;
484 };
485 let window = main.window.clone();
486 let scale = window.scale_factor();
487 let size = window.inner_size().to_logical::<f32>(scale);
488 let current = layout::viewport_of(egui::vec2(size.width, size.height));
489 let aspect = self.view.video_aspect();
490 let target = layout::snap_viewport(self.snapped_viewport, current, aspect);
491 self.snapped_viewport = target;
492 self.snapped_aspect = aspect;
493 if (target - current).length() <= 1.5 {
494 return;
495 }
496 let w = layout::window_size(target);
497 if let Some(applied) = window.request_inner_size(LogicalSize::new(w.x, w.y))
498 && let (Some(pw), Some(ph)) = (
499 NonZeroU32::new(applied.width),
500 NonZeroU32::new(applied.height),
501 )
502 {
503 main.painter.on_window_resized(ViewportId::ROOT, pw, ph);
504 }
505 window.request_redraw();
506 }
507
508 /// 사용자가 창 크기를 바꾼 뒤 휴대폰 화면 비율에 맞게 창 크기를 다시 정한다.
509 fn snap_main_window(&mut self) {
510 let Some(main) = &self.main else { return };
511 let window = &main.window;
512 let size = window.inner_size().to_logical::<f32>(window.scale_factor());
513 let current = layout::viewport_of(egui::vec2(size.width, size.height));
514 let aspect = self.view.video_aspect();
515 let target = layout::snap_viewport(self.snapped_viewport, current, aspect);
516 self.snapped_viewport = target;
517 self.snapped_aspect = aspect;
518 if (target - current).length() > 1.5 {
519 let w = layout::window_size(target);
520 let _ = window.request_inner_size(LogicalSize::new(w.x, w.y));
521 }
522 }
523
524 fn send(&self, cmd: ConnCommand) {
525 if let Some(conn) = &self.conn {
526 conn.send(cmd);
527 }
528 }
529
530 fn request_redraw_all(&self) {
531 for gfx in [&self.main, &self.settings].into_iter().flatten() {
532 gfx.window.request_redraw();
533 }
534 }
535}
536
537impl ApplicationHandler<Wake> for App {
538 fn user_event(&mut self, _event_loop: &ActiveEventLoop, _event: Wake) {
539 // 연결 상태는 두 창 모두에 영향을 준다 (아이콘 활성화, 설정 안내 문구).
540 self.request_redraw_all();
541 }
542
543 fn resumed(&mut self, event_loop: &ActiveEventLoop) {
544 if self.main.is_some() {
545 return;
546 }
547 match self.init_main(event_loop) {
548 Ok(gfx) => {
549 self.main = Some(gfx);
550 if let Some(target) = self.autoconnect.take() {
551 let mut actions = Actions::default();
552 self.view.request_connect(&target, &mut actions);
553 self.apply(actions, event_loop);
554 }
555 }
556 Err(e) => {
557 log::error!("창 또는 GPU 초기화 실패: {e}");
558 event_loop.exit();
559 }
560 }
561 }
562
563 fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
564 let Some(kind) = self.kind_of(id) else { return };
565 let captures_keyboard = self.view.captures_keyboard();
566
567 match &event {
568 WindowEvent::CloseRequested => {
569 match kind {
570 Kind::Main => event_loop.exit(),
571 Kind::Settings => self.settings = None,
572 }
573 return;
574 }
575 WindowEvent::RedrawRequested => {
576 self.redraw(kind, event_loop);
577 return;
578 }
579 WindowEvent::Focused(focused) if kind == Kind::Main => {
580 self.main_focused = *focused;
581 self.focus_sync_at = focused.then(|| Instant::now() + FOCUS_SYNC_DELAY);
582 }
583 _ => {}
584 }
585
586 let gfx = match kind {
587 Kind::Main => self.main.as_mut(),
588 Kind::Settings => self.settings.as_mut(),
589 };
590 let Some(gfx) = gfx else { return };
591 if kind == Kind::Main {
592 // 연결 중에는 Ctrl+C/V/X를 egui-winit이 복사·붙여넣기 이벤트로 바꾸지 않고 키로 넘기게 한다.
593 // 그래야 클립보드가 비어도 Ctrl+V가 휴대폰에 전달된다.
594 gfx.egui_winit.set_clipboard_shortcuts(!captures_keyboard);
595 }
596 let response = gfx.egui_winit.on_window_event(&gfx.window, &event);
597 let repaint = response.repaint;
598 if let WindowEvent::Resized(size) = event
599 && let (Some(w), Some(h)) = (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
600 {
601 gfx.painter.on_window_resized(ViewportId::ROOT, w, h);
602 if kind == Kind::Main {
603 self.keep_main_aspect();
604 self.main_resized_at = Some(Instant::now());
605 }
606 }
607 if repaint && let Some(gfx) = self.main.as_ref().filter(|_| kind == Kind::Main) {
608 gfx.window.request_redraw();
609 } else if repaint
610 && let Some(gfx) = self.settings.as_ref().filter(|_| kind == Kind::Settings)
611 {
612 gfx.window.request_redraw();
613 }
614 }
615
616 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
617 let now = Instant::now();
618 let mut next: Option<Instant> = None;
619 if let Some(at) = self.focus_sync_at {
620 if at <= now {
621 self.focus_sync_at = None;
622 self.focus_sync();
623 } else {
624 next = Some(at);
625 }
626 }
627 if let Some(at) = self.main_resized_at {
628 let due = at + SNAP_DELAY;
629 if due <= now {
630 self.main_resized_at = None;
631 self.snap_main_window();
632 } else {
633 next = Some(next.map_or(due, |n| n.min(due)));
634 }
635 }
636 for gfx in [&mut self.main, &mut self.settings].into_iter().flatten() {
637 match gfx.next_repaint {
638 Some(at) if at <= now => {
639 gfx.next_repaint = None;
640 gfx.window.request_redraw();
641 }
642 Some(at) => next = Some(next.map_or(at, |n| n.min(at))),
643 None => {}
644 }
645 }
646 event_loop.set_control_flow(match next {
647 Some(at) => ControlFlow::WaitUntil(at),
648 None => ControlFlow::Wait,
649 });
650 }
651}