leejunyoung5819wayland-android-remote

공개

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

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