leejunyoung5819wayland-android-remote

공개

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

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