leejunyoung5819wayland-android-remote

공개

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

230줄7.5 KB
1//! 호스트 GUI. winit 창 위에 wgpu로 직접 그리고, 설정·입력 UI는 egui로 같은 렌더 패스에 얹는다.
2//! 영상은 이후 같은 wgpu 디바이스에 텍스처로 올려 그린다.
3
4mod fonts;
5mod layout;
6mod recent;
7mod view;
8
9use std::num::NonZeroU32;
10use std::sync::Arc;
11use std::time::{Duration, Instant};
12
13use egui::ViewportId;
14use egui_wgpu::winit::Painter;
15use egui_wgpu::{RendererOptions, SurfaceConfig, WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew};
16use egui_winit::winit;
17use winit::application::ApplicationHandler;
18use winit::dpi::{LogicalSize, PhysicalPosition};
19use winit::event::WindowEvent;
20use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
21use winit::window::{Window, WindowId};
22
23use view::{Actions, View};
24
25/// 이벤트 루프를 만들고 창이 닫힐 때까지 실행한다.
26pub fn run() -> Result<(), Box<dyn std::error::Error>> {
27 let event_loop = EventLoop::new()?;
28 let mut app = App::new();
29 event_loop.run_app(&mut app)?;
30 Ok(())
31}
32
33struct Gfx {
34 window: Arc<Window>,
35 painter: Painter,
36 egui_winit: egui_winit::State,
37}
38
39struct App {
40 ctx: egui::Context,
41 view: View,
42 gfx: Option<Gfx>,
43 next_repaint: Option<Instant>,
44}
45
46impl App {
47 fn new() -> Self {
48 let ctx = egui::Context::default();
49 ctx.set_visuals(egui::Visuals::dark());
50 fonts::install_korean_font(&ctx);
51 Self {
52 ctx,
53 view: View::new(),
54 gfx: None,
55 next_repaint: None,
56 }
57 }
58
59 fn init_gfx(&self, event_loop: &ActiveEventLoop) -> Result<Gfx, Box<dyn std::error::Error>> {
60 let size = self.view.window_size();
61 let attrs = Window::default_attributes()
62 .with_title("Android Remote")
63 .with_decorations(false)
64 .with_resizable(false)
65 .with_inner_size(LogicalSize::new(size.x, size.y));
66 let window = Arc::new(event_loop.create_window(attrs)?);
67
68 let mut setup = WgpuSetupCreateNew::from_display_handle(event_loop.owned_display_handle());
69 setup.power_preference = egui_wgpu::wgpu::PowerPreference::HighPerformance;
70 let config = WgpuConfiguration {
71 // 프레임 큐를 1장으로 제한해 입력에서 화면까지의 지연을 줄인다.
72 surface: SurfaceConfig::LOW_LATENCY,
73 wgpu_setup: WgpuSetup::CreateNew(setup),
74 ..Default::default()
75 };
76 let mut painter = pollster::block_on(Painter::new(
77 self.ctx.clone(),
78 config,
79 false,
80 RendererOptions::default(),
81 ));
82 pollster::block_on(painter.set_window(ViewportId::ROOT, Some(window.clone())))?;
83 if let Some(rs) = painter.render_state() {
84 let info = rs.adapter.get_info();
85 log::info!("GPU: {} ({:?})", info.name, info.backend);
86 }
87
88 let egui_winit = egui_winit::State::new(
89 self.ctx.clone(),
90 ViewportId::ROOT,
91 event_loop,
92 Some(window.scale_factor() as f32),
93 window.theme(),
94 painter.max_texture_side(),
95 );
96
97 Ok(Gfx {
98 window,
99 painter,
100 egui_winit,
101 })
102 }
103
104 fn redraw(&mut self, event_loop: &ActiveEventLoop) {
105 let Some(gfx) = self.gfx.as_mut() else {
106 return;
107 };
108 let raw_input = gfx.egui_winit.take_egui_input(&gfx.window);
109 let mut actions = Actions::default();
110 let view = &mut self.view;
111 let output = self.ctx.run_ui(raw_input, |ui| view.ui(ui, &mut actions));
112
113 gfx.egui_winit
114 .handle_platform_output(&gfx.window, output.platform_output);
115 let primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point);
116 let mut textures = output.textures_delta;
117 gfx.painter.paint_and_update_textures(
118 ViewportId::ROOT,
119 output.pixels_per_point,
120 [0.0, 0.0, 0.0, 1.0],
121 &primitives,
122 &mut textures,
123 Vec::new(),
124 &gfx.window,
125 );
126
127 let delay = output
128 .viewport_output
129 .get(&ViewportId::ROOT)
130 .map_or(Duration::MAX, |v| v.repaint_delay);
131 if delay.is_zero() {
132 gfx.window.request_redraw();
133 } else {
134 self.next_repaint = Instant::now().checked_add(delay);
135 }
136
137 self.apply(actions, event_loop);
138 }
139
140 fn apply(&mut self, actions: Actions, event_loop: &ActiveEventLoop) {
141 let Some(gfx) = &self.gfx else { return };
142 let window = &gfx.window;
143 if actions.close {
144 event_loop.exit();
145 return;
146 }
147 if actions.start_drag
148 && let Err(e) = window.drag_window()
149 {
150 log::debug!("창 이동 실패: {e}");
151 }
152 if actions.minimize {
153 window.set_minimized(true);
154 }
155 if let Some(open) = actions.panel_toggled {
156 let size = self.view.window_size();
157 // X11에서는 창을 왼쪽으로 옮겨 뷰포트 위치를 유지한다. Wayland는 클라이언트가
158 // 창 위치를 정할 수 없어 오른쪽으로 넓어진다.
159 if let Ok(pos) = window.outer_position() {
160 let dx = (layout::PANEL_W as f64 * window.scale_factor()).round() as i32;
161 let x = if open { pos.x - dx } else { pos.x + dx };
162 window.set_outer_position(PhysicalPosition::new(x, pos.y));
163 }
164 let _ = window.request_inner_size(LogicalSize::new(size.x, size.y));
165 window.request_redraw();
166 }
167 }
168}
169
170impl ApplicationHandler for App {
171 fn resumed(&mut self, event_loop: &ActiveEventLoop) {
172 if self.gfx.is_some() {
173 return;
174 }
175 match self.init_gfx(event_loop) {
176 Ok(gfx) => {
177 gfx.window.request_redraw();
178 self.gfx = Some(gfx);
179 }
180 Err(e) => {
181 log::error!("창 또는 GPU 초기화 실패: {e}");
182 event_loop.exit();
183 }
184 }
185 }
186
187 fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
188 let Some(gfx) = self.gfx.as_mut() else {
189 return;
190 };
191 let response = gfx.egui_winit.on_window_event(&gfx.window, &event);
192
193 match event {
194 WindowEvent::CloseRequested => {
195 event_loop.exit();
196 return;
197 }
198 WindowEvent::Resized(size) => {
199 if let (Some(w), Some(h)) =
200 (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
201 {
202 gfx.painter.on_window_resized(ViewportId::ROOT, w, h);
203 }
204 }
205 WindowEvent::RedrawRequested => {
206 self.redraw(event_loop);
207 return;
208 }
209 _ => {}
210 }
211
212 if response.repaint {
213 gfx.window.request_redraw();
214 }
215 }
216
217 fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
218 match self.next_repaint {
219 Some(at) if at <= Instant::now() => {
220 self.next_repaint = None;
221 if let Some(gfx) = &self.gfx {
222 gfx.window.request_redraw();
223 }
224 event_loop.set_control_flow(ControlFlow::Wait);
225 }
226 Some(at) => event_loop.set_control_flow(ControlFlow::WaitUntil(at)),
227 None => event_loop.set_control_flow(ControlFlow::Wait),
228 }
229 }
230}