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