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