leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! 화면 그리기와 사용자 조작 처리 (기획서 4절). 창 조작은 [`Actions`]로 돌려주고 |
| 2 | //! 실제 winit 호출은 상위 [`super::App`]에서 한다. |
| 3 | |
| 4 | use std::net::SocketAddr; |
| 5 | |
| 6 | use egui::{ |
| 7 | Align2, Button, Color32, FontId, Key, Rect, RichText, Sense, TextEdit, Ui, Vec2, pos2, vec2, |
| 8 | }; |
| 9 | |
| 10 | use wayland_android_remote::protocol::{AuthGrant, Message, SystemAction, VideoCodec, VideoConfig}; |
| 11 | |
| 12 | use super::conn::ConnEvent; |
| 13 | use super::icons::{self, Icon}; |
| 14 | use super::input::{InputState, VideoTarget}; |
| 15 | use super::layout::{self, DEFAULT_VIEWPORT}; |
| 16 | use super::recent::{RecentTargets, display_target, parse_target}; |
| 17 | use super::video_render::{VideoCallback, YuvFrame}; |
| 18 | |
| 19 | const FRAME_COLOR: Color32 = Color32::BLACK; |
| 20 | const SETTINGS_BG: Color32 = Color32::from_rgb(0x14, 0x14, 0x14); |
| 21 | const ICON_COLOR: Color32 = Color32::from_rgb(0xb4, 0xb4, 0xb4); |
| 22 | const ICON_HOVER: Color32 = Color32::WHITE; |
| 23 | const ICON_DISABLED: Color32 = Color32::from_rgb(0x44, 0x44, 0x44); |
| 24 | const DIM_TEXT: Color32 = Color32::from_rgb(0x8a, 0x8a, 0x8a); |
| 25 | const INPUT_BG: Color32 = Color32::from_rgb(0x1c, 0x1c, 0x1c); |
| 26 | const ERROR_TEXT: Color32 = Color32::from_rgb(0xe0, 0x6c, 0x6c); |
| 27 | const SWITCH_SIZE: Vec2 = vec2(36.0, 20.0); |
| 28 | const SWITCH_OFF: Color32 = Color32::from_rgb(0x3a, 0x3a, 0x3a); |
| 29 | const SWITCH_OFF_HOVER: Color32 = Color32::from_rgb(0x48, 0x48, 0x48); |
| 30 | |
| 31 | /// 한 프레임 동안 UI가 요청한 창 동작. |
| 32 | #[derive(Debug, Default)] |
| 33 | pub struct Actions { |
| 34 | pub start_drag: bool, |
| 35 | /// 창 가장자리를 눌렀다. 이 방향으로 창 크기 조절을 시작한다. |
| 36 | pub start_resize: Option<layout::ResizeDir>, |
| 37 | pub minimize: bool, |
| 38 | pub close: bool, |
| 39 | /// 설정 창을 열거나 앞으로 가져온다. |
| 40 | pub open_settings: bool, |
| 41 | /// 이 주소로 연결을 시작한다. |
| 42 | pub connect: Option<SocketAddr>, |
| 43 | /// 진행 중인 연결을 취소하거나 끊는다. |
| 44 | pub disconnect: bool, |
| 45 | /// 저장된 기기 지문을 지운다. |
| 46 | pub forget_device: Option<SocketAddr>, |
| 47 | pub system_action: Option<SystemAction>, |
| 48 | /// 설정 창에서 영상 설정이 바뀌었다. |
| 49 | pub video_settings_changed: bool, |
| 50 | /// 휴대폰으로 보낼 입력 메시지. 만든 순서대로 보낸다. |
| 51 | pub input: Vec<Message>, |
| 52 | } |
| 53 | |
| 54 | #[derive(Debug, Clone)] |
| 55 | enum Connection { |
| 56 | /// 검은 화면과 IP 입력창 (기획서 4.4). |
| 57 | Disconnected, |
| 58 | /// TLS 연결과 인증 진행 중. |
| 59 | Connecting { |
| 60 | target: SocketAddr, |
| 61 | confirm_code: Option<String>, |
| 62 | awaiting_approval: bool, |
| 63 | }, |
| 64 | /// 인증 완료. 디코더가 붙기 전까지는 영상 정보와 수신 프레임 수만 표시한다. |
| 65 | Connected { |
| 66 | target: SocketAddr, |
| 67 | grant: AuthGrant, |
| 68 | video: Option<VideoConfig>, |
| 69 | frames: u64, |
| 70 | }, |
| 71 | } |
| 72 | |
| 73 | /// 설정 창의 설정값. |
| 74 | #[derive(Debug, Clone)] |
| 75 | pub struct StreamSettings { |
| 76 | pub max_size: u16, |
| 77 | pub max_fps: u8, |
| 78 | pub bitrate_mbps: u32, |
| 79 | /// 메인 창이 포커스를 얻으면 호스트 클립보드를 휴대폰에 미리 넣어 둔다. |
| 80 | pub sync_clipboard_on_focus: bool, |
| 81 | /// 연결 중에도 휴대폰 실제 화면을 켜 둔다. 끄면(기본) 미러링은 계속하고 휴대폰 화면만 끈다. |
| 82 | pub keep_screen_on: bool, |
| 83 | usb_adb_mode: bool, |
| 84 | } |
| 85 | |
| 86 | impl Default for StreamSettings { |
| 87 | fn default() -> Self { |
| 88 | Self { |
| 89 | max_size: 1920, |
| 90 | max_fps: 60, |
| 91 | bitrate_mbps: 8, |
| 92 | sync_clipboard_on_focus: false, |
| 93 | keep_screen_on: false, |
| 94 | usb_adb_mode: false, |
| 95 | } |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | pub struct View { |
| 100 | viewport_size: Vec2, |
| 101 | connection: Connection, |
| 102 | ip_input: String, |
| 103 | input_error: Option<String>, |
| 104 | /// 마지막 연결 실패가 인증서 지문 불일치였던 주소. 기록 지우기 버튼을 보여준다. |
| 105 | mismatch_target: Option<SocketAddr>, |
| 106 | focus_input: bool, |
| 107 | recent: RecentTargets, |
| 108 | settings: StreamSettings, |
| 109 | /// 최신 영상 프레임과 번호. 있으면 휴대폰 화면 영역에 영상을 그린다. |
| 110 | video_frame: Option<(u64, std::sync::Arc<YuvFrame>)>, |
| 111 | video_seq: u64, |
| 112 | input: InputState, |
| 113 | } |
| 114 | |
| 115 | impl View { |
| 116 | pub fn new() -> Self { |
| 117 | Self { |
| 118 | viewport_size: DEFAULT_VIEWPORT, |
| 119 | connection: Connection::Disconnected, |
| 120 | ip_input: String::new(), |
| 121 | input_error: None, |
| 122 | mismatch_target: None, |
| 123 | focus_input: true, |
| 124 | recent: RecentTargets::load(), |
| 125 | settings: StreamSettings::default(), |
| 126 | video_frame: None, |
| 127 | video_seq: 0, |
| 128 | input: InputState::default(), |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | /// 디코더가 만든 최신 프레임. 다음 그리기에서 GPU로 올린다. |
| 133 | pub fn set_video_frame(&mut self, frame: std::sync::Arc<YuvFrame>) { |
| 134 | if matches!(self.connection, Connection::Connected { .. }) { |
| 135 | self.video_seq += 1; |
| 136 | self.video_frame = Some((self.video_seq, frame)); |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | pub fn settings(&self) -> &StreamSettings { |
| 141 | &self.settings |
| 142 | } |
| 143 | |
| 144 | /// 네트워크 작업에서 온 상태 변화를 반영한다. |
| 145 | pub fn on_conn_event(&mut self, event: ConnEvent) { |
| 146 | match (&mut self.connection, event) { |
| 147 | ( |
| 148 | Connection::Connecting { confirm_code, .. }, |
| 149 | ConnEvent::Tls { confirm_code: code }, |
| 150 | ) => *confirm_code = Some(code), |
| 151 | ( |
| 152 | Connection::Connecting { |
| 153 | confirm_code, |
| 154 | awaiting_approval, |
| 155 | .. |
| 156 | }, |
| 157 | ConnEvent::AwaitingApproval { confirm_code: code }, |
| 158 | ) => { |
| 159 | *confirm_code = Some(code); |
| 160 | *awaiting_approval = true; |
| 161 | } |
| 162 | (Connection::Connecting { target, .. }, ConnEvent::Connected { grant }) => { |
| 163 | let target = *target; |
| 164 | if let Err(e) = self.recent.record(&display_target(target)) { |
| 165 | log::warn!("최근 접속 기록 저장 실패: {e}"); |
| 166 | } |
| 167 | self.connection = Connection::Connected { |
| 168 | target, |
| 169 | grant, |
| 170 | video: None, |
| 171 | frames: 0, |
| 172 | }; |
| 173 | } |
| 174 | (Connection::Connected { video, .. }, ConnEvent::VideoConfig(cfg)) => { |
| 175 | *video = Some(cfg); |
| 176 | } |
| 177 | (Connection::Connected { frames, .. }, ConnEvent::VideoFrames(n)) => *frames = n, |
| 178 | (_, ConnEvent::Ended(reason)) => { |
| 179 | self.mismatch_target = match &self.connection { |
| 180 | Connection::Connecting { target, .. } |
| 181 | if reason.contains("인증서가 다릅니다") => |
| 182 | { |
| 183 | Some(*target) |
| 184 | } |
| 185 | _ => None, |
| 186 | }; |
| 187 | self.connection = Connection::Disconnected; |
| 188 | self.video_frame = None; |
| 189 | self.input_error = Some(reason); |
| 190 | self.focus_input = true; |
| 191 | } |
| 192 | _ => {} |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | /// 연결되어 메인 창 키보드 입력을 휴대폰으로 보내는 중인지. |
| 197 | pub fn captures_keyboard(&self) -> bool { |
| 198 | matches!(self.connection, Connection::Connected { .. }) |
| 199 | } |
| 200 | |
| 201 | /// 터치·휠을 받을 영상 영역. 연결되고 영상 설정과 그린 프레임이 있을 때만 있다. |
| 202 | fn video_target(&self, viewport: Rect) -> Option<VideoTarget> { |
| 203 | let Connection::Connected { |
| 204 | video: Some(cfg), .. |
| 205 | } = &self.connection |
| 206 | else { |
| 207 | return None; |
| 208 | }; |
| 209 | let (_, frame) = self.video_frame.as_ref()?; |
| 210 | Some(VideoTarget { |
| 211 | rect: video_rect(viewport, frame), |
| 212 | width: cfg.width, |
| 213 | height: cfg.height, |
| 214 | }) |
| 215 | } |
| 216 | |
| 217 | /// 휴대폰 화면 비율(너비/높이). 영상을 받기 전에는 기본 비율을 쓴다. |
| 218 | pub fn video_aspect(&self) -> f32 { |
| 219 | match &self.video_frame { |
| 220 | Some((_, f)) if f.height > 0 => f.width as f32 / f.height as f32, |
| 221 | _ => DEFAULT_VIEWPORT.x / DEFAULT_VIEWPORT.y, |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | /// 현재 상태에 맞는 창 안쪽 크기 (논리 픽셀). |
| 226 | pub fn window_size(&self) -> Vec2 { |
| 227 | layout::window_size(self.viewport_size) |
| 228 | } |
| 229 | |
| 230 | pub fn ui(&mut self, ui: &mut Ui, actions: &mut Actions) { |
| 231 | let screen = ui.max_rect(); |
| 232 | let layout = layout::compute(screen); |
| 233 | |
| 234 | ui.painter().rect_filled(screen, 0.0, FRAME_COLOR); |
| 235 | |
| 236 | let keyboard = self.captures_keyboard(); |
| 237 | if keyboard { |
| 238 | // 연결 중에는 Tab·화살표가 휴대폰으로 가야 한다. egui는 begin_pass에서 이 키로 |
| 239 | // 포커스 이동 방향을 정하고 위젯이 등록될 때 포커스를 옮기므로, 위젯을 그리기 전에 |
| 240 | // 방향을 지우고 남은 포커스도 놓아 아이콘 버튼이 Enter·Space로 눌리지 않게 한다. |
| 241 | ui.memory_mut(|m| { |
| 242 | m.move_focus(egui::FocusDirection::None); |
| 243 | if let Some(id) = m.focused() { |
| 244 | m.surrender_focus(id); |
| 245 | } |
| 246 | }); |
| 247 | } |
| 248 | let phone = self.video_target(layout.viewport); |
| 249 | let events = ui.input(|i| i.events.clone()); |
| 250 | self.input |
| 251 | .process(&events, keyboard, phone, &mut actions.input); |
| 252 | if keyboard && ui.input(|i| i.focused) { |
| 253 | request_ime(ui, phone.map_or(layout.viewport, |t| t.rect)); |
| 254 | } |
| 255 | |
| 256 | self.icon_rail(ui, layout.rail, actions); |
| 257 | self.nav_bar(ui, layout.nav_bar, actions); |
| 258 | self.mouse_back_button(ui, actions); |
| 259 | title_bar(ui, layout.title_bar, actions); |
| 260 | ui.painter() |
| 261 | .rect_filled(layout.viewport, 0.0, Color32::BLACK); |
| 262 | |
| 263 | match self.connection.clone() { |
| 264 | Connection::Disconnected => self.disconnected_screen(ui, layout.viewport, actions), |
| 265 | Connection::Connecting { |
| 266 | target, |
| 267 | confirm_code, |
| 268 | awaiting_approval, |
| 269 | } => connecting_screen( |
| 270 | ui, |
| 271 | layout.viewport, |
| 272 | target, |
| 273 | confirm_code.as_deref(), |
| 274 | awaiting_approval, |
| 275 | actions, |
| 276 | ), |
| 277 | Connection::Connected { |
| 278 | target, |
| 279 | grant, |
| 280 | video, |
| 281 | frames, |
| 282 | } => match self.video_frame.clone() { |
| 283 | Some((seq, frame)) => draw_video(ui, layout.viewport, seq, frame), |
| 284 | None => { |
| 285 | connected_screen(ui, layout.viewport, target, grant, video.as_ref(), frames) |
| 286 | } |
| 287 | }, |
| 288 | } |
| 289 | |
| 290 | if keyboard { |
| 291 | let rect = phone.map_or(layout.viewport, |t| t.rect); |
| 292 | draw_preedit(ui, rect, self.input.preedit()); |
| 293 | } |
| 294 | |
| 295 | // 가장자리 크기 조절은 다른 위젯보다 우선한다. 휴대폰 화면과는 겹치지 않는다. |
| 296 | resize_handles(ui, screen, actions); |
| 297 | } |
| 298 | |
| 299 | /// 왼쪽 세로 아이콘 열. 배경과 테두리 없이 아이콘만 그린다. |
| 300 | fn icon_rail(&mut self, ui: &mut Ui, rail: Rect, actions: &mut Actions) { |
| 301 | // 버튼보다 먼저 등록해 버튼이 아닌 빈 곳에서만 창 이동이 걸리게 한다. |
| 302 | drag_area(ui, rail, "rail_drag", actions); |
| 303 | let active = !matches!(self.connection, Connection::Disconnected); |
| 304 | let connected = matches!(self.connection, Connection::Connected { .. }); |
| 305 | |
| 306 | let top = [ |
| 307 | (Icon::Settings, "설정", true), |
| 308 | ( |
| 309 | Icon::Screenshot, |
| 310 | "스크린샷 (영상 디코딩 구현 후 사용 가능)", |
| 311 | false, |
| 312 | ), |
| 313 | (Icon::Rotate, "화면 회전", connected), |
| 314 | ]; |
| 315 | for (i, (icon, tip, enabled)) in top.into_iter().enumerate() { |
| 316 | let rect = layout::rail_slot(rail, i, false); |
| 317 | if !icon_button(ui, rect, icon, tip, enabled).clicked() { |
| 318 | continue; |
| 319 | } |
| 320 | match icon { |
| 321 | Icon::Settings => actions.open_settings = true, |
| 322 | Icon::Rotate => actions.system_action = Some(SystemAction::Rotate), |
| 323 | _ => {} |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | let rect = layout::rail_slot(rail, 0, true); |
| 328 | if icon_button(ui, rect, Icon::Disconnect, "연결 끊기", active).clicked() { |
| 329 | actions.disconnect = true; |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | /// 휴대폰 화면 아래 내비게이션 줄. 휴대폰과 같은 순서로 뒤로·홈·최근 앱을 둔다. |
| 334 | fn nav_bar(&mut self, ui: &mut Ui, nav_bar: Rect, actions: &mut Actions) { |
| 335 | drag_area(ui, nav_bar, "nav_drag", actions); |
| 336 | let connected = matches!(self.connection, Connection::Connected { .. }); |
| 337 | let buttons = [ |
| 338 | (Icon::Back, "뒤로", SystemAction::Back), |
| 339 | (Icon::Home, "홈", SystemAction::Home), |
| 340 | (Icon::Recents, "최근 앱", SystemAction::Recents), |
| 341 | ]; |
| 342 | for (rect, (icon, tip, action)) in layout::nav_slots(nav_bar).into_iter().zip(buttons) { |
| 343 | if icon_button(ui, rect, icon, tip, connected).clicked() { |
| 344 | actions.system_action = Some(action); |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | /// 마우스 옆 버튼 중 뒤로 버튼(아래쪽, Linux BTN_SIDE)을 누르면 휴대폰 뒤로가기를 보낸다. |
| 350 | /// 옆 버튼이 없는 마우스는 내비게이션 줄의 ◁를 쓴다. |
| 351 | fn mouse_back_button(&mut self, ui: &mut Ui, actions: &mut Actions) { |
| 352 | let connected = matches!(self.connection, Connection::Connected { .. }); |
| 353 | if connected && ui.input(|i| i.pointer.button_pressed(egui::PointerButton::Extra1)) { |
| 354 | actions.system_action = Some(SystemAction::Back); |
| 355 | } |
| 356 | } |
| 357 | |
| 358 | /// 설정 창 내용. 별도 창에서 그린다. |
| 359 | pub fn settings_ui(&mut self, ui: &mut Ui, actions: &mut Actions) { |
| 360 | ui.painter().rect_filled(ui.max_rect(), 0.0, SETTINGS_BG); |
| 361 | let connected = matches!(self.connection, Connection::Connected { .. }); |
| 362 | let active = !matches!(self.connection, Connection::Disconnected); |
| 363 | let before = ( |
| 364 | self.settings.max_size, |
| 365 | self.settings.max_fps, |
| 366 | self.settings.bitrate_mbps, |
| 367 | ); |
| 368 | let width = ui.available_width(); |
| 369 | egui::Frame::new().inner_margin(16.0).show(ui, |ui| { |
| 370 | ui.spacing_mut().item_spacing.y = 10.0; |
| 371 | let s = &mut self.settings; |
| 372 | |
| 373 | ui.label(RichText::new("해상도").color(DIM_TEXT)); |
| 374 | egui::ComboBox::from_id_salt("max_size") |
| 375 | .selected_text(size_label(s.max_size)) |
| 376 | .width(width - 32.0) |
| 377 | .show_ui(ui, |ui| { |
| 378 | for v in [0, 2400, 1920, 1600, 1280, 1024] { |
| 379 | ui.selectable_value(&mut s.max_size, v, size_label(v)); |
| 380 | } |
| 381 | }); |
| 382 | |
| 383 | ui.label(RichText::new("FPS").color(DIM_TEXT)); |
| 384 | ui.horizontal(|ui| { |
| 385 | for v in [30, 60, 90, 120] { |
| 386 | ui.selectable_value(&mut s.max_fps, v, v.to_string()); |
| 387 | } |
| 388 | }); |
| 389 | |
| 390 | ui.label(RichText::new("비트레이트").color(DIM_TEXT)); |
| 391 | ui.add(egui::Slider::new(&mut s.bitrate_mbps, 2..=40).suffix(" Mbps")); |
| 392 | |
| 393 | ui.separator(); |
| 394 | if toggle_switch(ui, &mut s.keep_screen_on, "휴대폰 화면 켜 두기").changed() && active |
| 395 | { |
| 396 | // 연결 직후에는 연결 작업이 설정값을 보낸다. 그 뒤 바꾸면 바로 알린다. |
| 397 | actions.system_action = Some(if s.keep_screen_on { |
| 398 | SystemAction::ScreenOn |
| 399 | } else { |
| 400 | SystemAction::ScreenOff |
| 401 | }); |
| 402 | } |
| 403 | ui.checkbox( |
| 404 | &mut s.sync_clipboard_on_focus, |
| 405 | "창 포커스 시 클립보드 동기화", |
| 406 | ); |
| 407 | ui.checkbox(&mut s.usb_adb_mode, "USB ADB 모드"); |
| 408 | |
| 409 | if !connected { |
| 410 | ui.label( |
| 411 | RichText::new("영상 설정은 연결 후 기기에 바로 적용됩니다").color(DIM_TEXT), |
| 412 | ); |
| 413 | } |
| 414 | }); |
| 415 | let after = ( |
| 416 | self.settings.max_size, |
| 417 | self.settings.max_fps, |
| 418 | self.settings.bitrate_mbps, |
| 419 | ); |
| 420 | if connected && before != after { |
| 421 | actions.video_settings_changed = true; |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | fn disconnected_screen(&mut self, ui: &mut Ui, viewport: Rect, actions: &mut Actions) { |
| 426 | let center = viewport.center(); |
| 427 | let input_rect = Rect::from_center_size(center, vec2(220.0, 30.0)); |
| 428 | |
| 429 | let edit = TextEdit::singleline(&mut self.ip_input) |
| 430 | .hint_text("IP 주소") |
| 431 | .align(Align2::CENTER_CENTER) |
| 432 | .background_color(INPUT_BG) |
| 433 | .text_color(Color32::WHITE) |
| 434 | .font(FontId::proportional(16.0)) |
| 435 | .margin(vec2(8.0, 6.0)); |
| 436 | let resp = ui.put(input_rect, edit); |
| 437 | if std::mem::take(&mut self.focus_input) { |
| 438 | resp.request_focus(); |
| 439 | } |
| 440 | if resp.changed() { |
| 441 | self.input_error = None; |
| 442 | } |
| 443 | |
| 444 | let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter)); |
| 445 | if enter { |
| 446 | let input = self.ip_input.clone(); |
| 447 | self.try_connect(&input, actions); |
| 448 | } |
| 449 | |
| 450 | let mut y = input_rect.max.y + 8.0; |
| 451 | if let Some(err) = &self.input_error { |
| 452 | ui.painter().text( |
| 453 | pos2(center.x, y), |
| 454 | Align2::CENTER_TOP, |
| 455 | err, |
| 456 | FontId::proportional(13.0), |
| 457 | ERROR_TEXT, |
| 458 | ); |
| 459 | y += 22.0; |
| 460 | } |
| 461 | if let Some(target) = self.mismatch_target { |
| 462 | let r = Rect::from_center_size(pos2(center.x, y + 12.0), vec2(220.0, 24.0)); |
| 463 | if ui.put(r, Button::new("기기 기록 지우기")).clicked() { |
| 464 | actions.forget_device = Some(target); |
| 465 | self.mismatch_target = None; |
| 466 | self.input_error = None; |
| 467 | } |
| 468 | y += 34.0; |
| 469 | } |
| 470 | |
| 471 | if resp.has_focus() || self.ip_input.is_empty() { |
| 472 | let mut picked = None; |
| 473 | for item in self.recent.items() { |
| 474 | let r = Rect::from_center_size(pos2(center.x, y + 12.0), vec2(220.0, 24.0)); |
| 475 | let b = Button::new(RichText::new(item).color(DIM_TEXT)).frame(false); |
| 476 | if ui.put(r, b).clicked() { |
| 477 | picked = Some(item.clone()); |
| 478 | } |
| 479 | y += 26.0; |
| 480 | } |
| 481 | if let Some(item) = picked { |
| 482 | self.ip_input = item.clone(); |
| 483 | self.try_connect(&item, actions); |
| 484 | } |
| 485 | } |
| 486 | } |
| 487 | |
| 488 | fn try_connect(&mut self, input: &str, actions: &mut Actions) { |
| 489 | match parse_target(input) { |
| 490 | Ok(target) => { |
| 491 | self.ip_input = display_target(target); |
| 492 | self.input_error = None; |
| 493 | self.mismatch_target = None; |
| 494 | self.connection = Connection::Connecting { |
| 495 | target, |
| 496 | confirm_code: None, |
| 497 | awaiting_approval: false, |
| 498 | }; |
| 499 | actions.connect = Some(target); |
| 500 | } |
| 501 | Err(msg) => { |
| 502 | self.input_error = Some(msg.to_owned()); |
| 503 | self.focus_input = true; |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// IP 입력창에 주소를 넣고 Enter를 누른 것과 같다. 시작 인자 연결에 쓴다. |
| 509 | pub fn request_connect(&mut self, input: &str, actions: &mut Actions) { |
| 510 | self.ip_input = input.to_owned(); |
| 511 | self.try_connect(input, actions); |
| 512 | } |
| 513 | |
| 514 | /// 사용자가 끊었을 때 IP 입력 화면으로 돌아간다. |
| 515 | pub fn reset_to_disconnected(&mut self) { |
| 516 | self.video_frame = None; |
| 517 | self.connection = Connection::Disconnected; |
| 518 | self.focus_input = true; |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | fn connecting_screen( |
| 523 | ui: &mut Ui, |
| 524 | viewport: Rect, |
| 525 | target: SocketAddr, |
| 526 | confirm_code: Option<&str>, |
| 527 | awaiting_approval: bool, |
| 528 | actions: &mut Actions, |
| 529 | ) { |
| 530 | let c = viewport.center(); |
| 531 | let p = ui.painter(); |
| 532 | let title = if awaiting_approval { |
| 533 | "휴대폰 승인 대기 중 (취소: Esc)" |
| 534 | } else { |
| 535 | "연결 중 (취소: Esc)" |
| 536 | }; |
| 537 | p.text( |
| 538 | c - vec2(0.0, 18.0), |
| 539 | Align2::CENTER_CENTER, |
| 540 | title, |
| 541 | FontId::proportional(15.0), |
| 542 | Color32::WHITE, |
| 543 | ); |
| 544 | if let Some(code) = confirm_code.filter(|_| awaiting_approval) { |
| 545 | p.text( |
| 546 | c + vec2(0.0, 14.0), |
| 547 | Align2::CENTER_CENTER, |
| 548 | spaced(code), |
| 549 | FontId::monospace(26.0), |
| 550 | Color32::WHITE, |
| 551 | ); |
| 552 | p.text( |
| 553 | c + vec2(0.0, 44.0), |
| 554 | Align2::CENTER_CENTER, |
| 555 | "휴대폰에 같은 코드가 보일 때만 허용하세요", |
| 556 | FontId::proportional(12.0), |
| 557 | DIM_TEXT, |
| 558 | ); |
| 559 | } |
| 560 | p.text( |
| 561 | c + vec2(0.0, 72.0), |
| 562 | Align2::CENTER_CENTER, |
| 563 | display_target(target), |
| 564 | FontId::proportional(12.0), |
| 565 | DIM_TEXT, |
| 566 | ); |
| 567 | if ui.input(|i| i.key_pressed(Key::Escape)) { |
| 568 | actions.disconnect = true; |
| 569 | } |
| 570 | } |
| 571 | |
| 572 | fn connected_screen( |
| 573 | ui: &mut Ui, |
| 574 | viewport: Rect, |
| 575 | target: SocketAddr, |
| 576 | grant: AuthGrant, |
| 577 | video: Option<&VideoConfig>, |
| 578 | frames: u64, |
| 579 | ) { |
| 580 | let c = viewport.center(); |
| 581 | let p = ui.painter(); |
| 582 | let grant = match grant { |
| 583 | AuthGrant::Once => " (이번만 허용)", |
| 584 | _ => "", |
| 585 | }; |
| 586 | p.text( |
| 587 | c - vec2(0.0, 12.0), |
| 588 | Align2::CENTER_CENTER, |
| 589 | format!("{} 연결됨{grant}", display_target(target)), |
| 590 | FontId::proportional(14.0), |
| 591 | Color32::WHITE, |
| 592 | ); |
| 593 | let detail = match video { |
| 594 | Some(v) => format!( |
| 595 | "{} {}x{} {}fps · 수신 프레임 {frames}", |
| 596 | codec_name(v.codec), |
| 597 | v.width, |
| 598 | v.height, |
| 599 | v.fps |
| 600 | ), |
| 601 | None => "영상 설정 대기 중".to_owned(), |
| 602 | }; |
| 603 | p.text( |
| 604 | c + vec2(0.0, 12.0), |
| 605 | Align2::CENTER_CENTER, |
| 606 | detail, |
| 607 | FontId::proportional(12.0), |
| 608 | DIM_TEXT, |
| 609 | ); |
| 610 | } |
| 611 | |
| 612 | /// 영상을 휴대폰 화면 영역에 종횡비를 유지해 맞춰 그린다. |
| 613 | fn draw_video(ui: &mut Ui, viewport: Rect, seq: u64, frame: std::sync::Arc<YuvFrame>) { |
| 614 | let rect = video_rect(viewport, &frame); |
| 615 | ui.painter().add(egui_wgpu::Callback::new_paint_callback( |
| 616 | rect, |
| 617 | VideoCallback { frame, seq }, |
| 618 | )); |
| 619 | } |
| 620 | |
| 621 | /// 프레임이 그려지는 사각형. 입력 좌표 변환도 같은 사각형을 쓴다. |
| 622 | fn video_rect(viewport: Rect, frame: &YuvFrame) -> Rect { |
| 623 | fit_rect(viewport, frame.width as f32 / frame.height.max(1) as f32) |
| 624 | } |
| 625 | |
| 626 | /// IME 조합 글자를 표시할 위치 (영상 아래쪽 가운데). |
| 627 | fn preedit_anchor(rect: Rect) -> egui::Pos2 { |
| 628 | pos2(rect.center().x, rect.max.y - 28.0) |
| 629 | } |
| 630 | |
| 631 | /// 휴대폰 화면에 키보드 입력 중일 때 winit에 IME를 켜 달라고 매 프레임 요청한다. |
| 632 | /// IME 후보 창은 조합 글자 표시 위치 근처에 뜨게 한다. |
| 633 | fn request_ime(ui: &mut Ui, rect: Rect) { |
| 634 | let anchor = preedit_anchor(rect); |
| 635 | let cursor_rect = Rect::from_min_size(anchor - vec2(0.0, 10.0), vec2(1.0, 20.0)); |
| 636 | ui.output_mut(|o| { |
| 637 | o.ime = Some(egui::output::IMEOutput { |
| 638 | purpose: egui::IMEPurpose::Normal, |
| 639 | rect, |
| 640 | cursor_rect, |
| 641 | should_interrupt_composition: false, |
| 642 | }); |
| 643 | }); |
| 644 | } |
| 645 | |
| 646 | /// IME로 조합 중인 글자를 영상 아래쪽에 작게 띄운다. 확정된 글자만 휴대폰으로 보낸다. |
| 647 | fn draw_preedit(ui: &mut Ui, rect: Rect, preedit: &str) { |
| 648 | if preedit.is_empty() { |
| 649 | return; |
| 650 | } |
| 651 | let painter = ui.painter(); |
| 652 | let galley = painter.layout_no_wrap( |
| 653 | preedit.to_owned(), |
| 654 | FontId::proportional(18.0), |
| 655 | Color32::WHITE, |
| 656 | ); |
| 657 | let bg = Rect::from_center_size(preedit_anchor(rect), galley.size() + vec2(16.0, 8.0)); |
| 658 | painter.rect_filled(bg, 6.0, Color32::from_black_alpha(200)); |
| 659 | painter.galley(bg.min + vec2(8.0, 4.0), galley, Color32::WHITE); |
| 660 | } |
| 661 | |
| 662 | /// `outer` 안에 종횡비 `aspect`(너비/높이)를 유지하는 가장 큰 사각형을 가운데 정렬로 구한다. |
| 663 | fn fit_rect(outer: Rect, aspect: f32) -> Rect { |
| 664 | let outer_aspect = outer.width() / outer.height(); |
| 665 | let size = if aspect > outer_aspect { |
| 666 | vec2(outer.width(), outer.width() / aspect) |
| 667 | } else { |
| 668 | vec2(outer.height() * aspect, outer.height()) |
| 669 | }; |
| 670 | Rect::from_center_size(outer.center(), size) |
| 671 | } |
| 672 | |
| 673 | fn codec_name(codec: VideoCodec) -> &'static str { |
| 674 | match codec { |
| 675 | VideoCodec::H264 => "H.264", |
| 676 | VideoCodec::H265 => "H.265", |
| 677 | VideoCodec::Av1 => "AV1", |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | /// "123456" -> "123 456" |
| 682 | fn spaced(code: &str) -> String { |
| 683 | if code.len() == 6 && code.is_ascii() { |
| 684 | format!("{} {}", &code[..3], &code[3..]) |
| 685 | } else { |
| 686 | code.to_owned() |
| 687 | } |
| 688 | } |
| 689 | |
| 690 | /// 창 가장자리에 마우스를 올리면 크기 조절 커서를 보이고, 누르면 크기 조절을 시작한다. |
| 691 | fn resize_handles(ui: &mut Ui, screen: Rect, actions: &mut Actions) { |
| 692 | use layout::ResizeDir as D; |
| 693 | let Some(pos) = ui.input(|i| i.pointer.hover_pos()) else { |
| 694 | return; |
| 695 | }; |
| 696 | let Some(dir) = layout::resize_dir(screen, pos) else { |
| 697 | return; |
| 698 | }; |
| 699 | ui.ctx().set_cursor_icon(match dir { |
| 700 | D::North => egui::CursorIcon::ResizeNorth, |
| 701 | D::South => egui::CursorIcon::ResizeSouth, |
| 702 | D::East => egui::CursorIcon::ResizeEast, |
| 703 | D::West => egui::CursorIcon::ResizeWest, |
| 704 | D::NorthEast => egui::CursorIcon::ResizeNorthEast, |
| 705 | D::NorthWest => egui::CursorIcon::ResizeNorthWest, |
| 706 | D::SouthEast => egui::CursorIcon::ResizeSouthEast, |
| 707 | D::SouthWest => egui::CursorIcon::ResizeSouthWest, |
| 708 | }); |
| 709 | if ui.input(|i| i.pointer.primary_pressed()) { |
| 710 | actions.start_resize = Some(dir); |
| 711 | } |
| 712 | } |
| 713 | |
| 714 | /// 빈 공간을 누른 채 움직이면 창을 옮긴다. |
| 715 | fn drag_area(ui: &mut Ui, rect: Rect, id: &str, actions: &mut Actions) { |
| 716 | if ui |
| 717 | .interact(rect, egui::Id::unique(id), Sense::drag()) |
| 718 | .drag_started() |
| 719 | { |
| 720 | actions.start_drag = true; |
| 721 | } |
| 722 | } |
| 723 | |
| 724 | fn icon_button(ui: &mut Ui, rect: Rect, icon: Icon, tip: &str, enabled: bool) -> egui::Response { |
| 725 | // 드래그도 버튼이 가져가야 아래쪽 창 이동 영역이 클릭을 가로채지 않는다. |
| 726 | let sense = if enabled { |
| 727 | Sense::click() | Sense::drag() |
| 728 | } else { |
| 729 | Sense::hover() |
| 730 | }; |
| 731 | let resp = ui |
| 732 | .interact(rect, egui::Id::unique(("icon_button", tip)), sense) |
| 733 | .on_hover_text(tip); |
| 734 | let color = match (enabled, resp.hovered()) { |
| 735 | (false, _) => ICON_DISABLED, |
| 736 | (true, true) => ICON_HOVER, |
| 737 | (true, false) => ICON_COLOR, |
| 738 | }; |
| 739 | icons::paint(ui.painter(), rect, icon, color); |
| 740 | resp |
| 741 | } |
| 742 | |
| 743 | /// 왼쪽에 라벨, 오른쪽 끝에 켬/끔 스위치를 둔 한 줄. 줄 어디를 눌러도 바뀐다. |
| 744 | fn toggle_switch(ui: &mut Ui, on: &mut bool, label: &str) -> egui::Response { |
| 745 | let height = ui.spacing().interact_size.y.max(20.0); |
| 746 | let (rect, mut resp) = |
| 747 | ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::click()); |
| 748 | if resp.clicked() { |
| 749 | *on = !*on; |
| 750 | resp.mark_changed(); |
| 751 | } |
| 752 | resp.widget_info(|| { |
| 753 | egui::WidgetInfo::selected(egui::Role::Switch, ui.is_enabled(), *on, label) |
| 754 | }); |
| 755 | if !ui.is_rect_visible(rect) { |
| 756 | return resp; |
| 757 | } |
| 758 | |
| 759 | // 라벨 색은 체크박스 라벨과 맞춘다. |
| 760 | let visuals = ui.style().interact(&resp); |
| 761 | let text_color = visuals.text_color(); |
| 762 | ui.painter().text( |
| 763 | rect.left_center(), |
| 764 | Align2::LEFT_CENTER, |
| 765 | label, |
| 766 | egui::TextStyle::Body.resolve(ui.style()), |
| 767 | text_color, |
| 768 | ); |
| 769 | |
| 770 | let track = Rect::from_center_size( |
| 771 | pos2(rect.max.x - SWITCH_SIZE.x / 2.0, rect.center().y), |
| 772 | SWITCH_SIZE, |
| 773 | ); |
| 774 | let t = ui.ctx().animate_bool_responsive(resp.id, *on); |
| 775 | let off_bg = if resp.hovered() { |
| 776 | SWITCH_OFF_HOVER |
| 777 | } else { |
| 778 | SWITCH_OFF |
| 779 | }; |
| 780 | let bg = lerp_color(off_bg, ui.visuals().selection.bg_fill, t); |
| 781 | let radius = track.height() / 2.0; |
| 782 | ui.painter().rect_filled(track, radius, bg); |
| 783 | let knob_r = radius - 3.0; |
| 784 | let knob_x = egui::lerp((track.min.x + radius)..=(track.max.x - radius), t); |
| 785 | let knob_color = if *on || resp.hovered() { |
| 786 | Color32::WHITE |
| 787 | } else { |
| 788 | visuals.fg_stroke.color.gamma_multiply(0.9) |
| 789 | }; |
| 790 | ui.painter() |
| 791 | .circle_filled(pos2(knob_x, track.center().y), knob_r, knob_color); |
| 792 | resp |
| 793 | } |
| 794 | |
| 795 | fn lerp_color(a: Color32, b: Color32, t: f32) -> Color32 { |
| 796 | let mix = |x: u8, y: u8| egui::lerp(f32::from(x)..=f32::from(y), t).round() as u8; |
| 797 | Color32::from_rgb(mix(a.r(), b.r()), mix(a.g(), b.g()), mix(a.b(), b.b())) |
| 798 | } |
| 799 | |
| 800 | fn title_bar(ui: &mut Ui, rect: Rect, actions: &mut Actions) { |
| 801 | let btn = vec2(rect.height() + 6.0, rect.height()); |
| 802 | let close_rect = Rect::from_min_size(pos2(rect.max.x - btn.x, rect.min.y), btn); |
| 803 | let min_rect = close_rect.translate(vec2(-btn.x, 0.0)); |
| 804 | let drag_rect = Rect::from_min_max(rect.min, pos2(min_rect.min.x, rect.max.y)); |
| 805 | |
| 806 | drag_area(ui, drag_rect, "title_drag", actions); |
| 807 | |
| 808 | if title_button(ui, min_rect, "–", Color32::from_gray(0x33)).clicked() { |
| 809 | actions.minimize = true; |
| 810 | } |
| 811 | if title_button(ui, close_rect, "×", Color32::from_rgb(0xc4, 0x2b, 0x1c)).clicked() { |
| 812 | actions.close = true; |
| 813 | } |
| 814 | } |
| 815 | |
| 816 | fn title_button(ui: &mut Ui, rect: Rect, text: &str, hover_bg: Color32) -> egui::Response { |
| 817 | let resp = ui.interact( |
| 818 | rect, |
| 819 | egui::Id::unique(("title_button", text)), |
| 820 | Sense::click(), |
| 821 | ); |
| 822 | if resp.hovered() { |
| 823 | ui.painter().rect_filled(rect, 0.0, hover_bg); |
| 824 | } |
| 825 | ui.painter().text( |
| 826 | rect.center(), |
| 827 | Align2::CENTER_CENTER, |
| 828 | text, |
| 829 | FontId::proportional(14.0), |
| 830 | Color32::from_gray(0xc8), |
| 831 | ); |
| 832 | resp |
| 833 | } |
| 834 | |
| 835 | fn size_label(v: u16) -> String { |
| 836 | if v == 0 { |
| 837 | "원본".to_owned() |
| 838 | } else { |
| 839 | format!("{v}p") |
| 840 | } |
| 841 | } |
| 842 | |
| 843 | #[cfg(test)] |
| 844 | impl View { |
| 845 | /// 테스트용: 설정 파일을 읽고 쓰지 않는 View. |
| 846 | pub fn for_test() -> Self { |
| 847 | Self { |
| 848 | recent: RecentTargets::in_memory(), |
| 849 | ..Self::new() |
| 850 | } |
| 851 | } |
| 852 | |
| 853 | pub fn settings_mut_for_test(&mut self) -> &mut StreamSettings { |
| 854 | &mut self.settings |
| 855 | } |
| 856 | |
| 857 | /// 테스트용: 연결 시작 상태로 바꾼다. |
| 858 | pub fn start_connecting_for_test(&mut self, target: SocketAddr) { |
| 859 | self.connection = Connection::Connecting { |
| 860 | target, |
| 861 | confirm_code: None, |
| 862 | awaiting_approval: false, |
| 863 | }; |
| 864 | } |
| 865 | } |