leejunyoung5819wayland-android-remote

공개

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

604줄20 KB
1//! 화면 그리기와 사용자 조작 처리 (기획서 4절). 창 조작은 [`Actions`]로 돌려주고
2//! 실제 winit 호출은 상위 [`super::App`]에서 한다.
3
4use std::net::SocketAddr;
5
6use egui::{
7 Align2, Button, Color32, FontId, Key, Rect, RichText, Sense, TextEdit, Ui, Vec2, pos2, vec2,
8};
9
10use wayland_android_remote::protocol::{AuthGrant, SystemAction, VideoCodec, VideoConfig};
11
12use super::conn::ConnEvent;
13use super::icons::{self, Icon};
14use super::layout::{self, DEFAULT_VIEWPORT};
15use super::recent::{RecentTargets, display_target, parse_target};
16
17const FRAME_COLOR: Color32 = Color32::BLACK;
18const SETTINGS_BG: Color32 = Color32::from_rgb(0x14, 0x14, 0x14);
19const ICON_COLOR: Color32 = Color32::from_rgb(0xb4, 0xb4, 0xb4);
20const ICON_HOVER: Color32 = Color32::WHITE;
21const ICON_DISABLED: Color32 = Color32::from_rgb(0x44, 0x44, 0x44);
22const DIM_TEXT: Color32 = Color32::from_rgb(0x8a, 0x8a, 0x8a);
23const INPUT_BG: Color32 = Color32::from_rgb(0x1c, 0x1c, 0x1c);
24const ERROR_TEXT: Color32 = Color32::from_rgb(0xe0, 0x6c, 0x6c);
25
26/// 한 프레임 동안 UI가 요청한 창 동작.
27#[derive(Debug, Default)]
28pub struct Actions {
29 pub start_drag: bool,
30 pub minimize: bool,
31 pub close: bool,
32 /// 설정 창을 열거나 앞으로 가져온다.
33 pub open_settings: bool,
34 /// 이 주소로 연결을 시작한다.
35 pub connect: Option<SocketAddr>,
36 /// 진행 중인 연결을 취소하거나 끊는다.
37 pub disconnect: bool,
38 /// 저장된 기기 지문을 지운다.
39 pub forget_device: Option<SocketAddr>,
40 pub system_action: Option<SystemAction>,
41 /// 설정 창에서 영상 설정이 바뀌었다.
42 pub video_settings_changed: bool,
43}
44
45#[derive(Debug, Clone)]
46enum Connection {
47 /// 검은 화면과 IP 입력창 (기획서 4.4).
48 Disconnected,
49 /// TLS 연결과 인증 진행 중.
50 Connecting {
51 target: SocketAddr,
52 confirm_code: Option<String>,
53 awaiting_approval: bool,
54 },
55 /// 인증 완료. 디코더가 붙기 전까지는 영상 정보와 수신 프레임 수만 표시한다.
56 Connected {
57 target: SocketAddr,
58 grant: AuthGrant,
59 video: Option<VideoConfig>,
60 frames: u64,
61 },
62}
63
64/// 설정 창의 설정값.
65#[derive(Debug, Clone)]
66pub struct StreamSettings {
67 pub max_size: u16,
68 pub max_fps: u8,
69 pub bitrate_mbps: u32,
70 sync_clipboard_on_focus: bool,
71 usb_adb_mode: bool,
72}
73
74impl Default for StreamSettings {
75 fn default() -> Self {
76 Self {
77 max_size: 1920,
78 max_fps: 60,
79 bitrate_mbps: 8,
80 sync_clipboard_on_focus: false,
81 usb_adb_mode: false,
82 }
83 }
84}
85
86pub struct View {
87 viewport_size: Vec2,
88 connection: Connection,
89 ip_input: String,
90 input_error: Option<String>,
91 /// 마지막 연결 실패가 인증서 지문 불일치였던 주소. 기록 지우기 버튼을 보여준다.
92 mismatch_target: Option<SocketAddr>,
93 focus_input: bool,
94 recent: RecentTargets,
95 settings: StreamSettings,
96}
97
98impl View {
99 pub fn new() -> Self {
100 Self {
101 viewport_size: DEFAULT_VIEWPORT,
102 connection: Connection::Disconnected,
103 ip_input: String::new(),
104 input_error: None,
105 mismatch_target: None,
106 focus_input: true,
107 recent: RecentTargets::load(),
108 settings: StreamSettings::default(),
109 }
110 }
111
112 pub fn settings(&self) -> &StreamSettings {
113 &self.settings
114 }
115
116 /// 네트워크 작업에서 온 상태 변화를 반영한다.
117 pub fn on_conn_event(&mut self, event: ConnEvent) {
118 match (&mut self.connection, event) {
119 (
120 Connection::Connecting { confirm_code, .. },
121 ConnEvent::Tls { confirm_code: code },
122 ) => *confirm_code = Some(code),
123 (
124 Connection::Connecting {
125 confirm_code,
126 awaiting_approval,
127 ..
128 },
129 ConnEvent::AwaitingApproval { confirm_code: code },
130 ) => {
131 *confirm_code = Some(code);
132 *awaiting_approval = true;
133 }
134 (Connection::Connecting { target, .. }, ConnEvent::Connected { grant }) => {
135 let target = *target;
136 if let Err(e) = self.recent.record(&display_target(target)) {
137 log::warn!("최근 접속 기록 저장 실패: {e}");
138 }
139 self.connection = Connection::Connected {
140 target,
141 grant,
142 video: None,
143 frames: 0,
144 };
145 }
146 (Connection::Connected { video, .. }, ConnEvent::VideoConfig(cfg)) => {
147 *video = Some(cfg);
148 }
149 (Connection::Connected { frames, .. }, ConnEvent::VideoFrames(n)) => *frames = n,
150 (_, ConnEvent::Ended(reason)) => {
151 self.mismatch_target = match &self.connection {
152 Connection::Connecting { target, .. }
153 if reason.contains("인증서가 다릅니다") =>
154 {
155 Some(*target)
156 }
157 _ => None,
158 };
159 self.connection = Connection::Disconnected;
160 self.input_error = Some(reason);
161 self.focus_input = true;
162 }
163 _ => {}
164 }
165 }
166
167 /// 현재 상태에 맞는 창 안쪽 크기 (논리 픽셀).
168 pub fn window_size(&self) -> Vec2 {
169 layout::window_size(self.viewport_size)
170 }
171
172 pub fn ui(&mut self, ui: &mut Ui, actions: &mut Actions) {
173 let screen = ui.max_rect();
174 let layout = layout::compute(screen);
175
176 ui.painter().rect_filled(screen, 0.0, FRAME_COLOR);
177
178 self.icon_rail(ui, layout.rail, actions);
179 self.nav_bar(ui, layout.nav_bar, actions);
180 self.mouse_back_button(ui, actions);
181 title_bar(ui, layout.title_bar, actions);
182 ui.painter()
183 .rect_filled(layout.viewport, 0.0, Color32::BLACK);
184
185 match self.connection.clone() {
186 Connection::Disconnected => self.disconnected_screen(ui, layout.viewport, actions),
187 Connection::Connecting {
188 target,
189 confirm_code,
190 awaiting_approval,
191 } => connecting_screen(
192 ui,
193 layout.viewport,
194 target,
195 confirm_code.as_deref(),
196 awaiting_approval,
197 actions,
198 ),
199 Connection::Connected {
200 target,
201 grant,
202 video,
203 frames,
204 } => connected_screen(ui, layout.viewport, target, grant, video.as_ref(), frames),
205 }
206 }
207
208 /// 왼쪽 세로 아이콘 열. 배경과 테두리 없이 아이콘만 그린다.
209 fn icon_rail(&mut self, ui: &mut Ui, rail: Rect, actions: &mut Actions) {
210 // 버튼보다 먼저 등록해 버튼이 아닌 빈 곳에서만 창 이동이 걸리게 한다.
211 drag_area(ui, rail, "rail_drag", actions);
212 let active = !matches!(self.connection, Connection::Disconnected);
213
214 let top = [
215 (Icon::Settings, "설정", true),
216 (
217 Icon::Screenshot,
218 "스크린샷 (영상 디코딩 구현 후 사용 가능)",
219 false,
220 ),
221 ];
222 for (i, (icon, tip, enabled)) in top.into_iter().enumerate() {
223 let rect = layout::rail_slot(rail, i, false);
224 if icon_button(ui, rect, icon, tip, enabled).clicked() && icon == Icon::Settings {
225 actions.open_settings = true;
226 }
227 }
228
229 let rect = layout::rail_slot(rail, 0, true);
230 if icon_button(ui, rect, Icon::Disconnect, "연결 끊기", active).clicked() {
231 actions.disconnect = true;
232 }
233 }
234
235 /// 휴대폰 화면 아래 내비게이션 줄. 휴대폰과 같은 순서로 뒤로·홈·최근 앱을 둔다.
236 fn nav_bar(&mut self, ui: &mut Ui, nav_bar: Rect, actions: &mut Actions) {
237 drag_area(ui, nav_bar, "nav_drag", actions);
238 let connected = matches!(self.connection, Connection::Connected { .. });
239 let buttons = [
240 (Icon::Back, "뒤로", SystemAction::Back),
241 (Icon::Home, "홈", SystemAction::Home),
242 (Icon::Recents, "최근 앱", SystemAction::Recents),
243 ];
244 for (rect, (icon, tip, action)) in layout::nav_slots(nav_bar).into_iter().zip(buttons) {
245 if icon_button(ui, rect, icon, tip, connected).clicked() {
246 actions.system_action = Some(action);
247 }
248 }
249 }
250
251 /// 마우스 옆 버튼 중 뒤로 버튼(아래쪽, Linux BTN_SIDE)을 누르면 휴대폰 뒤로가기를 보낸다.
252 /// 옆 버튼이 없는 마우스는 내비게이션 줄의 ◁를 쓴다.
253 fn mouse_back_button(&mut self, ui: &mut Ui, actions: &mut Actions) {
254 let connected = matches!(self.connection, Connection::Connected { .. });
255 if connected && ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Extra1)) {
256 actions.system_action = Some(SystemAction::Back);
257 }
258 }
259
260 /// 설정 창 내용. 별도 창에서 그린다.
261 pub fn settings_ui(&mut self, ui: &mut Ui, actions: &mut Actions) {
262 ui.painter().rect_filled(ui.max_rect(), 0.0, SETTINGS_BG);
263 let connected = matches!(self.connection, Connection::Connected { .. });
264 let before = (
265 self.settings.max_size,
266 self.settings.max_fps,
267 self.settings.bitrate_mbps,
268 );
269 let width = ui.available_width();
270 egui::Frame::new().inner_margin(16.0).show(ui, |ui| {
271 ui.spacing_mut().item_spacing.y = 10.0;
272 let s = &mut self.settings;
273
274 ui.label(RichText::new("해상도").color(DIM_TEXT));
275 egui::ComboBox::from_id_salt("max_size")
276 .selected_text(size_label(s.max_size))
277 .width(width - 32.0)
278 .show_ui(ui, |ui| {
279 for v in [0, 2400, 1920, 1600, 1280, 1024] {
280 ui.selectable_value(&mut s.max_size, v, size_label(v));
281 }
282 });
283
284 ui.label(RichText::new("FPS").color(DIM_TEXT));
285 ui.horizontal(|ui| {
286 for v in [30, 60, 90, 120] {
287 ui.selectable_value(&mut s.max_fps, v, v.to_string());
288 }
289 });
290
291 ui.label(RichText::new("비트레이트").color(DIM_TEXT));
292 ui.add(egui::Slider::new(&mut s.bitrate_mbps, 2..=40).suffix(" Mbps"));
293
294 ui.separator();
295 ui.checkbox(
296 &mut s.sync_clipboard_on_focus,
297 "창 포커스 시 클립보드 동기화",
298 );
299 ui.checkbox(&mut s.usb_adb_mode, "USB ADB 모드");
300
301 if !connected {
302 ui.label(
303 RichText::new("영상 설정은 연결 후 기기에 바로 적용됩니다").color(DIM_TEXT),
304 );
305 }
306 });
307 let after = (
308 self.settings.max_size,
309 self.settings.max_fps,
310 self.settings.bitrate_mbps,
311 );
312 if connected && before != after {
313 actions.video_settings_changed = true;
314 }
315 }
316
317 fn disconnected_screen(&mut self, ui: &mut Ui, viewport: Rect, actions: &mut Actions) {
318 let center = viewport.center();
319 let input_rect = Rect::from_center_size(center, vec2(220.0, 30.0));
320
321 let edit = TextEdit::singleline(&mut self.ip_input)
322 .hint_text("IP 주소")
323 .align(Align2::CENTER_CENTER)
324 .background_color(INPUT_BG)
325 .text_color(Color32::WHITE)
326 .font(FontId::proportional(16.0))
327 .margin(vec2(8.0, 6.0));
328 let resp = ui.put(input_rect, edit);
329 if std::mem::take(&mut self.focus_input) {
330 resp.request_focus();
331 }
332 if resp.changed() {
333 self.input_error = None;
334 }
335
336 let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
337 if enter {
338 let input = self.ip_input.clone();
339 self.try_connect(&input, actions);
340 }
341
342 let mut y = input_rect.max.y + 8.0;
343 if let Some(err) = &self.input_error {
344 ui.painter().text(
345 pos2(center.x, y),
346 Align2::CENTER_TOP,
347 err,
348 FontId::proportional(13.0),
349 ERROR_TEXT,
350 );
351 y += 22.0;
352 }
353 if let Some(target) = self.mismatch_target {
354 let r = Rect::from_center_size(pos2(center.x, y + 12.0), vec2(220.0, 24.0));
355 if ui.put(r, Button::new("기기 기록 지우기")).clicked() {
356 actions.forget_device = Some(target);
357 self.mismatch_target = None;
358 self.input_error = None;
359 }
360 y += 34.0;
361 }
362
363 if resp.has_focus() || self.ip_input.is_empty() {
364 let mut picked = None;
365 for item in self.recent.items() {
366 let r = Rect::from_center_size(pos2(center.x, y + 12.0), vec2(220.0, 24.0));
367 let b = Button::new(RichText::new(item).color(DIM_TEXT)).frame(false);
368 if ui.put(r, b).clicked() {
369 picked = Some(item.clone());
370 }
371 y += 26.0;
372 }
373 if let Some(item) = picked {
374 self.ip_input = item.clone();
375 self.try_connect(&item, actions);
376 }
377 }
378 }
379
380 fn try_connect(&mut self, input: &str, actions: &mut Actions) {
381 match parse_target(input) {
382 Ok(target) => {
383 self.ip_input = display_target(target);
384 self.input_error = None;
385 self.mismatch_target = None;
386 self.connection = Connection::Connecting {
387 target,
388 confirm_code: None,
389 awaiting_approval: false,
390 };
391 actions.connect = Some(target);
392 }
393 Err(msg) => {
394 self.input_error = Some(msg.to_owned());
395 self.focus_input = true;
396 }
397 }
398 }
399
400 /// 사용자가 끊었을 때 IP 입력 화면으로 돌아간다.
401 pub fn reset_to_disconnected(&mut self) {
402 self.connection = Connection::Disconnected;
403 self.focus_input = true;
404 }
405}
406
407fn connecting_screen(
408 ui: &mut Ui,
409 viewport: Rect,
410 target: SocketAddr,
411 confirm_code: Option<&str>,
412 awaiting_approval: bool,
413 actions: &mut Actions,
414) {
415 let c = viewport.center();
416 let p = ui.painter();
417 let title = if awaiting_approval {
418 "휴대폰 승인 대기 중 (취소: Esc)"
419 } else {
420 "연결 중 (취소: Esc)"
421 };
422 p.text(
423 c - vec2(0.0, 18.0),
424 Align2::CENTER_CENTER,
425 title,
426 FontId::proportional(15.0),
427 Color32::WHITE,
428 );
429 if let Some(code) = confirm_code.filter(|_| awaiting_approval) {
430 p.text(
431 c + vec2(0.0, 14.0),
432 Align2::CENTER_CENTER,
433 spaced(code),
434 FontId::monospace(26.0),
435 Color32::WHITE,
436 );
437 p.text(
438 c + vec2(0.0, 44.0),
439 Align2::CENTER_CENTER,
440 "휴대폰에 같은 코드가 보일 때만 허용하세요",
441 FontId::proportional(12.0),
442 DIM_TEXT,
443 );
444 }
445 p.text(
446 c + vec2(0.0, 72.0),
447 Align2::CENTER_CENTER,
448 display_target(target),
449 FontId::proportional(12.0),
450 DIM_TEXT,
451 );
452 if ui.input(|i| i.key_pressed(Key::Escape)) {
453 actions.disconnect = true;
454 }
455}
456
457fn connected_screen(
458 ui: &mut Ui,
459 viewport: Rect,
460 target: SocketAddr,
461 grant: AuthGrant,
462 video: Option<&VideoConfig>,
463 frames: u64,
464) {
465 let c = viewport.center();
466 let p = ui.painter();
467 let grant = match grant {
468 AuthGrant::Once => " (이번만 허용)",
469 _ => "",
470 };
471 p.text(
472 c - vec2(0.0, 12.0),
473 Align2::CENTER_CENTER,
474 format!("{} 연결됨{grant}", display_target(target)),
475 FontId::proportional(14.0),
476 Color32::WHITE,
477 );
478 let detail = match video {
479 Some(v) => format!(
480 "{} {}x{} {}fps · 수신 프레임 {frames}",
481 codec_name(v.codec),
482 v.width,
483 v.height,
484 v.fps
485 ),
486 None => "영상 설정 대기 중".to_owned(),
487 };
488 p.text(
489 c + vec2(0.0, 12.0),
490 Align2::CENTER_CENTER,
491 detail,
492 FontId::proportional(12.0),
493 DIM_TEXT,
494 );
495}
496
497fn codec_name(codec: VideoCodec) -> &'static str {
498 match codec {
499 VideoCodec::H264 => "H.264",
500 VideoCodec::H265 => "H.265",
501 VideoCodec::Av1 => "AV1",
502 }
503}
504
505/// "123456" -> "123 456"
506fn spaced(code: &str) -> String {
507 if code.len() == 6 && code.is_ascii() {
508 format!("{} {}", &code[..3], &code[3..])
509 } else {
510 code.to_owned()
511 }
512}
513
514/// 빈 공간을 누른 채 움직이면 창을 옮긴다.
515fn drag_area(ui: &mut Ui, rect: Rect, id: &str, actions: &mut Actions) {
516 if ui
517 .interact(rect, egui::Id::unique(id), Sense::drag())
518 .drag_started()
519 {
520 actions.start_drag = true;
521 }
522}
523
524fn icon_button(ui: &mut Ui, rect: Rect, icon: Icon, tip: &str, enabled: bool) -> egui::Response {
525 // 드래그도 버튼이 가져가야 아래쪽 창 이동 영역이 클릭을 가로채지 않는다.
526 let sense = if enabled {
527 Sense::click() | Sense::drag()
528 } else {
529 Sense::hover()
530 };
531 let resp = ui
532 .interact(rect, egui::Id::unique(("icon_button", tip)), sense)
533 .on_hover_text(tip);
534 let color = match (enabled, resp.hovered()) {
535 (false, _) => ICON_DISABLED,
536 (true, true) => ICON_HOVER,
537 (true, false) => ICON_COLOR,
538 };
539 icons::paint(ui.painter(), rect, icon, color);
540 resp
541}
542
543fn title_bar(ui: &mut Ui, rect: Rect, actions: &mut Actions) {
544 let btn = vec2(rect.height() + 6.0, rect.height());
545 let close_rect = Rect::from_min_size(pos2(rect.max.x - btn.x, rect.min.y), btn);
546 let min_rect = close_rect.translate(vec2(-btn.x, 0.0));
547 let drag_rect = Rect::from_min_max(rect.min, pos2(min_rect.min.x, rect.max.y));
548
549 drag_area(ui, drag_rect, "title_drag", actions);
550
551 if title_button(ui, min_rect, "–", Color32::from_gray(0x33)).clicked() {
552 actions.minimize = true;
553 }
554 if title_button(ui, close_rect, "×", Color32::from_rgb(0xc4, 0x2b, 0x1c)).clicked() {
555 actions.close = true;
556 }
557}
558
559fn title_button(ui: &mut Ui, rect: Rect, text: &str, hover_bg: Color32) -> egui::Response {
560 let resp = ui.interact(
561 rect,
562 egui::Id::unique(("title_button", text)),
563 Sense::click(),
564 );
565 if resp.hovered() {
566 ui.painter().rect_filled(rect, 0.0, hover_bg);
567 }
568 ui.painter().text(
569 rect.center(),
570 Align2::CENTER_CENTER,
571 text,
572 FontId::proportional(14.0),
573 Color32::from_gray(0xc8),
574 );
575 resp
576}
577
578fn size_label(v: u16) -> String {
579 if v == 0 {
580 "원본".to_owned()
581 } else {
582 format!("{v}p")
583 }
584}
585
586#[cfg(test)]
587impl View {
588 /// 테스트용: 설정 파일을 읽고 쓰지 않는 View.
589 pub fn for_test() -> Self {
590 Self {
591 recent: RecentTargets::in_memory(),
592 ..Self::new()
593 }
594 }
595
596 /// 테스트용: 연결 시작 상태로 바꾼다.
597 pub fn start_connecting_for_test(&mut self, target: SocketAddr) {
598 self.connection = Connection::Connecting {
599 target,
600 confirm_code: None,
601 awaiting_approval: false,
602 };
603 }
604}