leejunyoung5819wayland-android-remote

공개

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

호스트 GUI 골격과 프로토콜 메시지 코덱 추가

- winit + wgpu(Vulkan) + egui 기반 호스트 창: 얇은 제목 표시줄, 왼쪽 토글과 사이드 메뉴, 미연결 화면의 IP 입력과 최근 접속 목록, 승인 대기 화면
- 모든 제어 메시지 페이로드와 영상 패킷 헤더의 인코딩/디코딩 및 테스트
- 개발 환경 설치 문서(docs/dev-setup.md)
작성자
LeeJunyoung
작성 시각
커밋
76097ade1e18ad4dfdb3bb5d2fe1f86c35ca5b56
부모
f1702c2
이 시점의 파일 보기

변경된 파일 12개

+943-7
수정Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정Cargo.toml+6-0
@@ -11,3 +11,9 @@ path = "src/main.rs"
1111
1212[dependencies]
1313bytes = "1.12.2"
14추가: egui = "0.37.0"
15추가: egui-wgpu = { version = "0.37.0", features = ["winit", "wayland", "x11"] }
16추가: egui-winit = "0.37.0"
17추가: env_logger = "0.11.12"
18추가: log = "0.4.35"
19추가: pollster = "1.0.3"
수정README.md+3-1
@@ -8,8 +8,10 @@ Ubuntu(Wayland/X11)에서 Android 기기 화면을 실시간으로 미러링하
88
99| 경로 | 내용 |
1010|---|---|
11삭제: | `src/`, `tests/` | 호스트 클라이언트 (Rust). 현재는 제어 채널 프레이밍(`src/protocol`)만 구현되어 있습니다. |
11추가: | `src/protocol/` | 제어 채널 프레이밍과 메시지 페이로드 인코딩/디코딩 (Rust 라이브러리) |
12추가: | `src/ui/` | 호스트 GUI. winit 창에 wgpu(Vulkan)로 직접 그리고, 설정·입력 UI는 egui로 같은 렌더 패스에 그립니다. |
1213| `android/` | Android 동반 앱과 shell 권한 데몬 (Kotlin, Gradle). 데몬은 동반 앱 APK 안에 함께 들어가며 `app_process`로 실행됩니다. |
14추가: | `docs/dev-setup.md` | 개발 환경 설치 방법 |
1315
1416## 연결 구조 요약
1517
추가docs/dev-setup.md+80-0
@@ -0,0 +1,80 @@
1추가: # 개발 환경 설치 (Ubuntu 26.04)
2추가:
3추가: 기준 PC: NVIDIA RTX 5080 / RTX 5060 Ti (드라이버 595), Intel UHD 630, Wayland 세션.
4추가:
5추가: ## 1. 시스템 패키지
6추가:
7추가: ```bash
8추가: sudo apt update
9추가: ```
10추가:
11추가: ```bash
12추가: sudo apt install -y openjdk-25-jdk-headless android-sdk-platform-tools-common clang libclang-dev libavcodec-dev libavformat-dev libavutil-dev libswscale-dev libavfilter-dev libavdevice-dev libva-dev vainfo nvidia-vaapi-driver vulkan-tools
13추가: ```
14추가:
15추가: | 패키지 | 용도 |
16추가: |---|---|
17추가: | `openjdk-25-jdk-headless` | Android 빌드용 `javac` (이미 설치된 Java 25 런타임과 같은 버전) |
18추가: | `android-sdk-platform-tools-common` | USB로 연결한 폰을 adb가 인식하도록 하는 udev 규칙 |
19추가: | `clang`, `libclang-dev` | `ffmpeg-next` 바인딩 생성(bindgen) |
20추가: | `libav*-dev` | 영상 디코딩 (FFmpeg 8) |
21추가: | `libva-dev`, `vainfo`, `nvidia-vaapi-driver` | VA-API 하드웨어 디코딩과 확인 도구 |
22추가: | `vulkan-tools` | `vulkaninfo`로 wgpu가 쓸 Vulkan 드라이버 확인 |
23추가:
24추가: ## 2. Android SDK
25추가:
26추가: ```bash
27추가: mkdir -p ~/Android/Sdk/cmdline-tools
28추가: ```
29추가:
30추가: ```bash
31추가: curl -fL -o /tmp/cmdline-tools.zip https://dl.google.com/android/repository/commandlinetools-linux-16111833_latest.zip
32추가: ```
33추가:
34추가: ```bash
35추가: echo "e025545c62a8e64c7559119566a569fb1dec5f60 /tmp/cmdline-tools.zip" | sha1sum -c -
36추가: ```
37추가:
38추가: ```bash
39추가: unzip -q /tmp/cmdline-tools.zip -d ~/Android/Sdk/cmdline-tools && mv ~/Android/Sdk/cmdline-tools/cmdline-tools ~/Android/Sdk/cmdline-tools/latest
40추가: ```
41추가:
42추가: 환경 변수를 `~/.profile`에 추가하고 현재 셸에 적용한다.
43추가:
44추가: ```bash
45추가: cat >> ~/.profile <<'EOF'
46추가: export ANDROID_HOME="$HOME/Android/Sdk"
47추가: export PATH="$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH"
48추가: EOF
49추가: ```
50추가:
51추가: ```bash
52추가: source ~/.profile
53추가: ```
54추가:
55추가: SDK 라이선스를 확인하고 동의한다(직접 읽고 `y` 입력).
56추가:
57추가: ```bash
58추가: sdkmanager --licenses
59추가: ```
60추가:
61추가: ```bash
62추가: sdkmanager "platform-tools" "platforms;android-36" "build-tools;36.1.0"
63추가: ```
64추가:
65추가: ## 3. 확인
66추가:
67추가: ```bash
68추가: javac -version && adb version && vainfo 2>&1 | grep -i 'driver version' && vulkaninfo --summary 2>/dev/null | grep -i devicename
69추가: ```
70추가:
71추가: ```bash
72추가: cd android && ./gradlew assembleDebug
73추가: ```
74추가:
75추가: ## 테스트 기기 준비 (Galaxy S21+, Android 15)
76추가:
77추가: 1. 설정 > 휴대전화 정보 > 소프트웨어 정보 > 빌드번호를 7번 눌러 개발자 옵션을 켠다.
78추가: 2. 개발자 옵션에서 USB 디버깅과 무선 디버깅을 켠다.
79추가: 3. 설정 > 보안 및 개인정보 보호 > 자동 차단(Auto Blocker)이 켜져 있으면 끈다.
80추가: 4. USB로 연결한 뒤 `adb devices`로 기기가 `device` 상태로 보이는지 확인한다.
수정src/main.rs+7-5
@@ -1,7 +1,9 @@
1추가: mod ui;
2추가:
13fn main() {
2삭제: println!(
3삭제: "android-remote {} (protocol v{}): 아직 구현 전입니다.",
4삭제: env!("CARGO_PKG_VERSION"),
5삭제: wayland_android_remote::protocol::VERSION
6삭제: );
4추가: env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
5추가: if let Err(e) = ui::run() {
6추가: log::error!("{e}");
7추가: std::process::exit(1);
8추가: }
79}
추가src/protocol/messages.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정src/protocol/mod.rs+28-1
@@ -5,9 +5,17 @@
55//! 여러 프레임이 한 번에 도착하는 경우를 모두 처리한다.
66
77mod frame;
8추가: mod messages;
89mod msg_type;
910
1011pub use frame::{Frame, FrameDecoder, FrameHeader, encode_frame};
12추가: pub use messages::{
13추가: AuthChallenge, AuthGrant, AuthHello, AuthResponse, AuthResult, AuthResultCode, AuthStatus,
14추가: ChannelAttach, ChannelKind, ClipboardMime, ClipboardOrigin, ClipboardSync, CodecMask,
15추가: ErrorMessage, KeyAction, KeyEvent, MAX_HOSTNAME_LEN, MAX_VIDEO_DATA_LEN, Message, ScrollEvent,
16추가: SystemAction, TextInput, TouchAction, TouchEvent, VIDEO_HEADER_LEN, VideoCodec, VideoConfig,
17추가: VideoConfigRequest, VideoPacketHeader, auth_signing_message, check_empty, error_code,
18추가: };
1119pub use msg_type::MsgType;
1220
1321/// 프로토콜 식별자 (ASCII 'A', 'R').
@@ -27,13 +35,25 @@ pub mod flags {
2735 pub const COMPRESSED: u16 = 0x0002;
2836}
2937
30삭제: /// 프레임 디코딩 중 발생하는 오류. 발생하면 스트림 동기가 깨진 것이므로 연결을 끊는다.
38추가: /// 프레임·페이로드 디코딩 중 발생하는 오류.
39추가: ///
40추가: /// 헤더 오류는 스트림 동기가 깨진 것이므로 연결을 끊는다. 페이로드 오류는 프레임 경계는
41추가: /// 유지되므로 ERROR 응답 후 계속할지 호출 측이 정한다.
3142#[derive(Debug, Clone, PartialEq, Eq)]
3243pub enum ProtocolError {
3344 BadMagic(u16),
3445 UnsupportedVersion(u8),
3546 UnknownMsgType(u8),
3647 PayloadTooLarge(u32),
48추가: /// 페이로드 길이·코드 값·UTF-8 등이 메시지 규격에 맞지 않음.
49추가: InvalidPayload {
50추가: msg_type: MsgType,
51추가: reason: &'static str,
52추가: },
53추가: /// 비디오 채널 패킷 헤더가 규격에 맞지 않음.
54추가: InvalidVideoHeader(&'static str),
55추가: /// 비디오 패킷 `data_len`이 [`MAX_VIDEO_DATA_LEN`]을 넘음.
56추가: VideoDataTooLarge(u32),
3757}
3858
3959impl std::fmt::Display for ProtocolError {
@@ -45,6 +65,13 @@ impl std::fmt::Display for ProtocolError {
4565 Self::PayloadTooLarge(n) => {
4666 write!(f, "payload_len {n}이 상한 {MAX_PAYLOAD_LEN}을 넘음")
4767 }
68추가: Self::InvalidPayload { msg_type, reason } => {
69추가: write!(f, "잘못된 {msg_type:?} 페이로드: {reason}")
70추가: }
71추가: Self::InvalidVideoHeader(reason) => write!(f, "잘못된 비디오 패킷 헤더: {reason}"),
72추가: Self::VideoDataTooLarge(n) => {
73추가: write!(f, "비디오 data_len {n}이 상한 {MAX_VIDEO_DATA_LEN}을 넘음")
74추가: }
4875 }
4976 }
5077}
추가src/ui/fonts.rs+46-0
@@ -0,0 +1,46 @@
1추가: //! 한글 표시용 시스템 폰트 등록. egui 기본 폰트에는 한글 글리프가 없다.
2추가:
3추가: use std::process::Command;
4추가: use std::sync::Arc;
5추가:
6추가: use egui::{FontData, FontDefinitions, FontFamily};
7추가:
8추가: const FALLBACK_PATH: &str = "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc";
9추가:
10추가: /// fontconfig에서 한국어 sans 폰트를 찾아 모든 글꼴 계열의 대체 폰트로 추가한다.
11추가: pub fn install_korean_font(ctx: &egui::Context) {
12추가: let (path, index) = fc_match_korean().unwrap_or_else(|| (FALLBACK_PATH.to_owned(), 0));
13추가: let bytes = match std::fs::read(&path) {
14추가: Ok(b) => b,
15추가: Err(e) => {
16추가: log::warn!("한글 폰트를 읽지 못했습니다 ({path}): {e}");
17추가: return;
18추가: }
19추가: };
20추가:
21추가: let mut data = FontData::from_owned(bytes);
22추가: data.index = index;
23추가:
24추가: let mut fonts = FontDefinitions::default();
25추가: fonts.font_data.insert("korean".to_owned(), Arc::new(data));
26추가: for family in [FontFamily::Proportional, FontFamily::Monospace] {
27추가: fonts
28추가: .families
29추가: .entry(family)
30추가: .or_default()
31추가: .push("korean".to_owned());
32추가: }
33추가: ctx.set_fonts(fonts);
34추가: }
35추가:
36추가: fn fc_match_korean() -> Option<(String, u32)> {
37추가: let out = Command::new("fc-match")
38추가: .args(["-f", "%{file}\n%{index}", "sans-serif:lang=ko"])
39추가: .output()
40추가: .ok()?;
41추가: let text = String::from_utf8(out.stdout).ok()?;
42추가: let mut lines = text.lines();
43추가: let path = lines.next()?.trim().to_owned();
44추가: let index = lines.next()?.trim().parse().ok()?;
45추가: (!path.is_empty()).then_some((path, index))
46추가: }
추가src/ui/layout.rs+79-0
@@ -0,0 +1,79 @@
1추가: //! 창 각 영역의 크기와 위치 (기획서 4.1 ~ 4.3). 단위는 논리 픽셀.
2추가:
3추가: use egui::{Rect, Vec2, pos2, vec2};
4추가:
5추가: /// 왼쪽 풀-하이트 토글 버튼 너비.
6추가: pub const TOGGLE_W: f32 = 14.0;
7추가: /// 펼쳤을 때 사이드 메뉴 너비.
8추가: pub const PANEL_W: f32 = 232.0;
9추가: /// 얇은 상단 제목 표시줄 높이.
10추가: pub const TITLE_H: f32 = 22.0;
11추가: /// 뷰포트를 감싸는 검은 테두리 두께.
12추가: pub const BORDER: f32 = 4.0;
13추가: /// 연결 전 기본 뷰포트 크기. Galaxy S21+ 화면 비율(1080x2400, 9:20)에 맞춘다.
14추가: pub const DEFAULT_VIEWPORT: Vec2 = vec2(360.0, 800.0);
15추가:
16추가: /// 한 프레임의 영역 배치.
17추가: #[derive(Debug, Clone, Copy)]
18추가: pub struct Layout {
19추가: pub toggle: Rect,
20추가: pub panel: Option<Rect>,
21추가: pub title_bar: Rect,
22추가: pub viewport: Rect,
23추가: }
24추가:
25추가: /// 뷰포트 크기와 사이드 메뉴 상태로 창 안쪽 크기를 계산한다.
26추가: pub fn window_size(viewport: Vec2, panel_open: bool) -> Vec2 {
27추가: let panel = if panel_open { PANEL_W } else { 0.0 };
28추가: vec2(
29추가: TOGGLE_W + panel + BORDER * 2.0 + viewport.x,
30추가: TITLE_H + viewport.y + BORDER,
31추가: )
32추가: }
33추가:
34추가: /// 창 전체 영역을 [토글][사이드 메뉴][제목 표시줄 + 뷰포트] 순서로 나눈다.
35추가: pub fn compute(screen: Rect, panel_open: bool) -> Layout {
36추가: let toggle = Rect::from_min_size(screen.min, vec2(TOGGLE_W, screen.height()));
37추가: let mut x = toggle.max.x;
38추가:
39추가: let panel = panel_open.then(|| {
40추가: let r = Rect::from_min_max(pos2(x, screen.min.y), pos2(x + PANEL_W, screen.max.y));
41추가: x = r.max.x;
42추가: r
43추가: });
44추가:
45추가: let title_bar = Rect::from_min_max(pos2(x, screen.min.y), pos2(screen.max.x, TITLE_H));
46추가: let viewport = Rect::from_min_max(
47추가: pos2(x + BORDER, title_bar.max.y),
48추가: pos2(screen.max.x - BORDER, screen.max.y - BORDER),
49추가: );
50추가:
51추가: Layout {
52추가: toggle,
53추가: panel,
54추가: title_bar,
55추가: viewport,
56추가: }
57추가: }
58추가:
59추가: #[cfg(test)]
60추가: mod tests {
61추가: use super::*;
62추가:
63추가: #[test]
64추가: fn viewport_keeps_requested_size() {
65추가: for open in [false, true] {
66추가: let size = window_size(DEFAULT_VIEWPORT, open);
67추가: let layout = compute(Rect::from_min_size(pos2(0.0, 0.0), size), open);
68추가: assert_eq!(layout.viewport.size(), DEFAULT_VIEWPORT);
69추가: assert_eq!(layout.panel.is_some(), open);
70추가: }
71추가: }
72추가:
73추가: #[test]
74추가: fn opening_panel_adds_only_panel_width() {
75추가: let closed = window_size(DEFAULT_VIEWPORT, false);
76추가: let open = window_size(DEFAULT_VIEWPORT, true);
77추가: assert_eq!(open - closed, vec2(PANEL_W, 0.0));
78추가: }
79추가: }
추가src/ui/mod.rs+230-0
@@ -0,0 +1,230 @@
1추가: //! 호스트 GUI. winit 창 위에 wgpu로 직접 그리고, 설정·입력 UI는 egui로 같은 렌더 패스에 얹는다.
2추가: //! 영상은 이후 같은 wgpu 디바이스에 텍스처로 올려 그린다.
3추가:
4추가: mod fonts;
5추가: mod layout;
6추가: mod recent;
7추가: mod view;
8추가:
9추가: use std::num::NonZeroU32;
10추가: use std::sync::Arc;
11추가: use std::time::{Duration, Instant};
12추가:
13추가: use egui::ViewportId;
14추가: use egui_wgpu::winit::Painter;
15추가: use egui_wgpu::{RendererOptions, SurfaceConfig, WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew};
16추가: use egui_winit::winit;
17추가: use winit::application::ApplicationHandler;
18추가: use winit::dpi::{LogicalSize, PhysicalPosition};
19추가: use winit::event::WindowEvent;
20추가: use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
21추가: use winit::window::{Window, WindowId};
22추가:
23추가: use view::{Actions, View};
24추가:
25추가: /// 이벤트 루프를 만들고 창이 닫힐 때까지 실행한다.
26추가: pub fn run() -> Result<(), Box<dyn std::error::Error>> {
27추가: let event_loop = EventLoop::new()?;
28추가: let mut app = App::new();
29추가: event_loop.run_app(&mut app)?;
30추가: Ok(())
31추가: }
32추가:
33추가: struct Gfx {
34추가: window: Arc<Window>,
35추가: painter: Painter,
36추가: egui_winit: egui_winit::State,
37추가: }
38추가:
39추가: struct App {
40추가: ctx: egui::Context,
41추가: view: View,
42추가: gfx: Option<Gfx>,
43추가: next_repaint: Option<Instant>,
44추가: }
45추가:
46추가: impl App {
47추가: fn new() -> Self {
48추가: let ctx = egui::Context::default();
49추가: ctx.set_visuals(egui::Visuals::dark());
50추가: fonts::install_korean_font(&ctx);
51추가: Self {
52추가: ctx,
53추가: view: View::new(),
54추가: gfx: None,
55추가: next_repaint: None,
56추가: }
57추가: }
58추가:
59추가: fn init_gfx(&self, event_loop: &ActiveEventLoop) -> Result<Gfx, Box<dyn std::error::Error>> {
60추가: let size = self.view.window_size();
61추가: let attrs = Window::default_attributes()
62추가: .with_title("Android Remote")
63추가: .with_decorations(false)
64추가: .with_resizable(false)
65추가: .with_inner_size(LogicalSize::new(size.x, size.y));
66추가: let window = Arc::new(event_loop.create_window(attrs)?);
67추가:
68추가: let mut setup = WgpuSetupCreateNew::from_display_handle(event_loop.owned_display_handle());
69추가: setup.power_preference = egui_wgpu::wgpu::PowerPreference::HighPerformance;
70추가: let config = WgpuConfiguration {
71추가: // 프레임 큐를 1장으로 제한해 입력에서 화면까지의 지연을 줄인다.
72추가: surface: SurfaceConfig::LOW_LATENCY,
73추가: wgpu_setup: WgpuSetup::CreateNew(setup),
74추가: ..Default::default()
75추가: };
76추가: let mut painter = pollster::block_on(Painter::new(
77추가: self.ctx.clone(),
78추가: config,
79추가: false,
80추가: RendererOptions::default(),
81추가: ));
82추가: pollster::block_on(painter.set_window(ViewportId::ROOT, Some(window.clone())))?;
83추가: if let Some(rs) = painter.render_state() {
84추가: let info = rs.adapter.get_info();
85추가: log::info!("GPU: {} ({:?})", info.name, info.backend);
86추가: }
87추가:
88추가: let egui_winit = egui_winit::State::new(
89추가: self.ctx.clone(),
90추가: ViewportId::ROOT,
91추가: event_loop,
92추가: Some(window.scale_factor() as f32),
93추가: window.theme(),
94추가: painter.max_texture_side(),
95추가: );
96추가:
97추가: Ok(Gfx {
98추가: window,
99추가: painter,
100추가: egui_winit,
101추가: })
102추가: }
103추가:
104추가: fn redraw(&mut self, event_loop: &ActiveEventLoop) {
105추가: let Some(gfx) = self.gfx.as_mut() else {
106추가: return;
107추가: };
108추가: let raw_input = gfx.egui_winit.take_egui_input(&gfx.window);
109추가: let mut actions = Actions::default();
110추가: let view = &mut self.view;
111추가: let output = self.ctx.run_ui(raw_input, |ui| view.ui(ui, &mut actions));
112추가:
113추가: gfx.egui_winit
114추가: .handle_platform_output(&gfx.window, output.platform_output);
115추가: let primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point);
116추가: let mut textures = output.textures_delta;
117추가: gfx.painter.paint_and_update_textures(
118추가: ViewportId::ROOT,
119추가: output.pixels_per_point,
120추가: [0.0, 0.0, 0.0, 1.0],
121추가: &primitives,
122추가: &mut textures,
123추가: Vec::new(),
124추가: &gfx.window,
125추가: );
126추가:
127추가: let delay = output
128추가: .viewport_output
129추가: .get(&ViewportId::ROOT)
130추가: .map_or(Duration::MAX, |v| v.repaint_delay);
131추가: if delay.is_zero() {
132추가: gfx.window.request_redraw();
133추가: } else {
134추가: self.next_repaint = Instant::now().checked_add(delay);
135추가: }
136추가:
137추가: self.apply(actions, event_loop);
138추가: }
139추가:
140추가: fn apply(&mut self, actions: Actions, event_loop: &ActiveEventLoop) {
141추가: let Some(gfx) = &self.gfx else { return };
142추가: let window = &gfx.window;
143추가: if actions.close {
144추가: event_loop.exit();
145추가: return;
146추가: }
147추가: if actions.start_drag
148추가: && let Err(e) = window.drag_window()
149추가: {
150추가: log::debug!("창 이동 실패: {e}");
151추가: }
152추가: if actions.minimize {
153추가: window.set_minimized(true);
154추가: }
155추가: if let Some(open) = actions.panel_toggled {
156추가: let size = self.view.window_size();
157추가: // X11에서는 창을 왼쪽으로 옮겨 뷰포트 위치를 유지한다. Wayland는 클라이언트가
158추가: // 창 위치를 정할 수 없어 오른쪽으로 넓어진다.
159추가: if let Ok(pos) = window.outer_position() {
160추가: let dx = (layout::PANEL_W as f64 * window.scale_factor()).round() as i32;
161추가: let x = if open { pos.x - dx } else { pos.x + dx };
162추가: window.set_outer_position(PhysicalPosition::new(x, pos.y));
163추가: }
164추가: let _ = window.request_inner_size(LogicalSize::new(size.x, size.y));
165추가: window.request_redraw();
166추가: }
167추가: }
168추가: }
169추가:
170추가: impl ApplicationHandler for App {
171추가: fn resumed(&mut self, event_loop: &ActiveEventLoop) {
172추가: if self.gfx.is_some() {
173추가: return;
174추가: }
175추가: match self.init_gfx(event_loop) {
176추가: Ok(gfx) => {
177추가: gfx.window.request_redraw();
178추가: self.gfx = Some(gfx);
179추가: }
180추가: Err(e) => {
181추가: log::error!("창 또는 GPU 초기화 실패: {e}");
182추가: event_loop.exit();
183추가: }
184추가: }
185추가: }
186추가:
187추가: fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
188추가: let Some(gfx) = self.gfx.as_mut() else {
189추가: return;
190추가: };
191추가: let response = gfx.egui_winit.on_window_event(&gfx.window, &event);
192추가:
193추가: match event {
194추가: WindowEvent::CloseRequested => {
195추가: event_loop.exit();
196추가: return;
197추가: }
198추가: WindowEvent::Resized(size) => {
199추가: if let (Some(w), Some(h)) =
200추가: (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
201추가: {
202추가: gfx.painter.on_window_resized(ViewportId::ROOT, w, h);
203추가: }
204추가: }
205추가: WindowEvent::RedrawRequested => {
206추가: self.redraw(event_loop);
207추가: return;
208추가: }
209추가: _ => {}
210추가: }
211추가:
212추가: if response.repaint {
213추가: gfx.window.request_redraw();
214추가: }
215추가: }
216추가:
217추가: fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
218추가: match self.next_repaint {
219추가: Some(at) if at <= Instant::now() => {
220추가: self.next_repaint = None;
221추가: if let Some(gfx) = &self.gfx {
222추가: gfx.window.request_redraw();
223추가: }
224추가: event_loop.set_control_flow(ControlFlow::Wait);
225추가: }
226추가: Some(at) => event_loop.set_control_flow(ControlFlow::WaitUntil(at)),
227추가: None => event_loop.set_control_flow(ControlFlow::Wait),
228추가: }
229추가: }
230추가: }
추가src/ui/recent.rs+147-0
@@ -0,0 +1,147 @@
1추가: //! 접속 주소 파싱과 최근 접속 IP 기록 (기획서 4.4).
2추가:
3추가: use std::fs;
4추가: use std::io;
5추가: use std::net::{IpAddr, SocketAddr};
6추가: use std::path::PathBuf;
7추가:
8추가: /// 데몬 기본 포트 (기획서 5.4).
9추가: pub const DEFAULT_PORT: u16 = 27200;
10추가: /// 최근 접속 기록 최대 개수.
11추가: const MAX_RECENT: usize = 8;
12추가:
13추가: /// 'IP' 또는 'IP:포트' 입력을 소켓 주소로 바꾼다. IPv6는 '[::1]:27200' 형식도 받는다.
14추가: pub fn parse_target(input: &str) -> Result<SocketAddr, &'static str> {
15추가: let s = input.trim();
16추가: if s.is_empty() {
17추가: return Err("IP 주소를 입력하세요");
18추가: }
19추가: if let Ok(addr) = s.parse::<SocketAddr>() {
20추가: if addr.port() == 0 {
21추가: return Err("포트 번호가 올바르지 않습니다");
22추가: }
23추가: return Ok(addr);
24추가: }
25추가: if let Ok(ip) = s.parse::<IpAddr>() {
26추가: return Ok(SocketAddr::new(ip, DEFAULT_PORT));
27추가: }
28추가: Err("IP 주소 형식이 올바르지 않습니다")
29추가: }
30추가:
31추가: /// 기본 포트면 IP만, 아니면 'IP:포트'로 표시한다.
32추가: pub fn display_target(addr: SocketAddr) -> String {
33추가: if addr.port() == DEFAULT_PORT {
34추가: addr.ip().to_string()
35추가: } else {
36추가: addr.to_string()
37추가: }
38추가: }
39추가:
40추가: /// 최근 접속에 성공한 주소 목록. 가장 최근 것이 맨 앞이다.
41추가: #[derive(Debug, Default)]
42추가: pub struct RecentTargets {
43추가: items: Vec<String>,
44추가: path: Option<PathBuf>,
45추가: }
46추가:
47추가: impl RecentTargets {
48추가: /// `~/.config/android-remote/recent_ips`에서 읽는다. 파일이 없으면 빈 목록이다.
49추가: pub fn load() -> Self {
50추가: let path = config_dir().map(|d| d.join("recent_ips"));
51추가: let items = path
52추가: .as_ref()
53추가: .and_then(|p| fs::read_to_string(p).ok())
54추가: .map(|s| parse_lines(&s))
55추가: .unwrap_or_default();
56추가: Self { items, path }
57추가: }
58추가:
59추가: pub fn items(&self) -> &[String] {
60추가: &self.items
61추가: }
62추가:
63추가: /// 접속 성공한 주소를 맨 앞에 넣고 파일에 저장한다.
64추가: #[expect(dead_code, reason = "AUTH_RESULT(OK) 수신 처리를 구현할 때 호출한다")]
65추가: pub fn record(&mut self, target: &str) -> io::Result<()> {
66추가: push_front_dedup(&mut self.items, target);
67추가: let Some(path) = &self.path else {
68추가: return Ok(());
69추가: };
70추가: if let Some(dir) = path.parent() {
71추가: fs::create_dir_all(dir)?;
72추가: }
73추가: fs::write(path, self.items.join("\n") + "\n")
74추가: }
75추가: }
76추가:
77추가: fn parse_lines(s: &str) -> Vec<String> {
78추가: let mut items = Vec::new();
79추가: for line in s.lines().map(str::trim).filter(|l| !l.is_empty()) {
80추가: if parse_target(line).is_ok() && !items.iter().any(|i| i == line) {
81추가: items.push(line.to_owned());
82추가: }
83추가: }
84추가: items.truncate(MAX_RECENT);
85추가: items
86추가: }
87추가:
88추가: fn push_front_dedup(items: &mut Vec<String>, target: &str) {
89추가: items.retain(|i| i != target);
90추가: items.insert(0, target.to_owned());
91추가: items.truncate(MAX_RECENT);
92추가: }
93추가:
94추가: /// `$XDG_CONFIG_HOME/android-remote` 또는 `~/.config/android-remote`.
95추가: pub fn config_dir() -> Option<PathBuf> {
96추가: let base = std::env::var_os("XDG_CONFIG_HOME")
97추가: .filter(|v| !v.is_empty())
98추가: .map(PathBuf::from)
99추가: .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
100추가: Some(base.join("android-remote"))
101추가: }
102추가:
103추가: #[cfg(test)]
104추가: mod tests {
105추가: use super::*;
106추가:
107추가: #[test]
108추가: fn parses_ip_with_default_port() {
109추가: let addr = parse_target(" 192.168.0.12 ").unwrap();
110추가: assert_eq!(addr, "192.168.0.12:27200".parse().unwrap());
111추가: assert_eq!(display_target(addr), "192.168.0.12");
112추가: }
113추가:
114추가: #[test]
115추가: fn parses_ip_with_port() {
116추가: let addr = parse_target("100.64.1.2:5000").unwrap();
117추가: assert_eq!(addr.port(), 5000);
118추가: assert_eq!(display_target(addr), "100.64.1.2:5000");
119추가: assert_eq!(parse_target("[fd00::1]:27200").unwrap().port(), 27200);
120추가: }
121추가:
122추가: #[test]
123추가: fn rejects_bad_input() {
124추가: assert!(parse_target("").is_err());
125추가: assert!(parse_target("phone.local").is_err());
126추가: assert!(parse_target("192.168.0.300").is_err());
127추가: assert!(parse_target("10.0.0.1:0").is_err());
128추가: }
129추가:
130추가: #[test]
131추가: fn recent_list_dedups_and_caps() {
132추가: let mut items = Vec::new();
133추가: for i in 0..10 {
134추가: push_front_dedup(&mut items, &format!("10.0.0.{i}"));
135추가: }
136추가: push_front_dedup(&mut items, "10.0.0.5");
137추가: assert_eq!(items.len(), MAX_RECENT);
138추가: assert_eq!(items[0], "10.0.0.5");
139추가: assert_eq!(items.iter().filter(|i| *i == "10.0.0.5").count(), 1);
140추가: }
141추가:
142추가: #[test]
143추가: fn load_skips_invalid_lines() {
144추가: let items = parse_lines("10.0.0.1\n\nnot-an-ip\n10.0.0.1\n10.0.0.2:5000\n");
145추가: assert_eq!(items, vec!["10.0.0.1", "10.0.0.2:5000"]);
146추가: }
147추가: }
추가src/ui/view.rs+317-0
@@ -0,0 +1,317 @@
1추가: //! 화면 그리기와 사용자 조작 처리 (기획서 4절). 창 조작은 [`Actions`]로 돌려주고
2추가: //! 실제 winit 호출은 상위 [`super::App`]에서 한다.
3추가:
4추가: use std::net::SocketAddr;
5추가:
6추가: use egui::{
7추가: Align2, Button, Color32, FontId, Key, Rect, RichText, Sense, TextEdit, Ui, UiBuilder, Vec2,
8추가: pos2, vec2,
9추가: };
10추가:
11추가: use super::layout::{self, DEFAULT_VIEWPORT, Layout};
12추가: use super::recent::{RecentTargets, display_target, parse_target};
13추가:
14추가: const FRAME_COLOR: Color32 = Color32::BLACK;
15추가: const PANEL_BG: Color32 = Color32::from_rgb(0x14, 0x14, 0x14);
16추가: const DIM_TEXT: Color32 = Color32::from_rgb(0x8a, 0x8a, 0x8a);
17추가: const INPUT_BG: Color32 = Color32::from_rgb(0x1c, 0x1c, 0x1c);
18추가: const ERROR_TEXT: Color32 = Color32::from_rgb(0xe0, 0x6c, 0x6c);
19추가:
20추가: /// 한 프레임 동안 UI가 요청한 창 동작.
21추가: #[derive(Debug, Default)]
22추가: pub struct Actions {
23추가: pub start_drag: bool,
24추가: pub minimize: bool,
25추가: pub close: bool,
26추가: /// 사이드 메뉴 열림 상태가 바뀌었다. 값은 새 상태다.
27추가: pub panel_toggled: Option<bool>,
28추가: }
29추가:
30추가: #[derive(Debug, Clone, PartialEq)]
31추가: enum Connection {
32추가: /// 검은 화면과 IP 입력창 (기획서 4.4).
33추가: Disconnected,
34추가: /// 휴대폰 승인 대기. 네트워크 연결은 아직 구현 전이다.
35추가: Connecting { target: SocketAddr },
36추가: }
37추가:
38추가: /// 사이드 메뉴 설정값 (기획서 4.3). 아직 기기로 전송하지는 않는다.
39추가: #[derive(Debug, Clone)]
40추가: struct StreamSettings {
41추가: max_size: u16,
42추가: max_fps: u8,
43추가: bitrate_mbps: u32,
44추가: sync_clipboard_on_focus: bool,
45추가: usb_adb_mode: bool,
46추가: }
47추가:
48추가: impl Default for StreamSettings {
49추가: fn default() -> Self {
50추가: Self {
51추가: max_size: 1920,
52추가: max_fps: 60,
53추가: bitrate_mbps: 8,
54추가: sync_clipboard_on_focus: false,
55추가: usb_adb_mode: false,
56추가: }
57추가: }
58추가: }
59추가:
60추가: pub struct View {
61추가: panel_open: bool,
62추가: viewport_size: Vec2,
63추가: connection: Connection,
64추가: ip_input: String,
65추가: input_error: Option<String>,
66추가: focus_input: bool,
67추가: recent: RecentTargets,
68추가: settings: StreamSettings,
69추가: }
70추가:
71추가: impl View {
72추가: pub fn new() -> Self {
73추가: Self {
74추가: panel_open: false,
75추가: viewport_size: DEFAULT_VIEWPORT,
76추가: connection: Connection::Disconnected,
77추가: ip_input: String::new(),
78추가: input_error: None,
79추가: focus_input: true,
80추가: recent: RecentTargets::load(),
81추가: settings: StreamSettings::default(),
82추가: }
83추가: }
84추가:
85추가: /// 현재 상태에 맞는 창 안쪽 크기 (논리 픽셀).
86추가: pub fn window_size(&self) -> Vec2 {
87추가: layout::window_size(self.viewport_size, self.panel_open)
88추가: }
89추가:
90추가: pub fn ui(&mut self, ui: &mut Ui, actions: &mut Actions) {
91추가: let screen = ui.max_rect();
92추가: let layout = layout::compute(screen, self.panel_open);
93추가:
94추가: ui.painter().rect_filled(screen, 0.0, FRAME_COLOR);
95추가:
96추가: self.toggle_button(ui, &layout, actions);
97추가: if let Some(panel) = layout.panel {
98추가: self.side_panel(ui, panel);
99추가: }
100추가: title_bar(ui, layout.title_bar, actions);
101추가: ui.painter()
102추가: .rect_filled(layout.viewport, 0.0, Color32::BLACK);
103추가:
104추가: match self.connection.clone() {
105추가: Connection::Disconnected => self.disconnected_screen(ui, layout.viewport),
106추가: Connection::Connecting { target } => {
107추가: self.connecting_screen(ui, layout.viewport, target)
108추가: }
109추가: }
110추가: }
111추가:
112추가: fn toggle_button(&mut self, ui: &mut Ui, layout: &Layout, actions: &mut Actions) {
113추가: let resp = ui.interact(layout.toggle, egui::Id::unique("toggle"), Sense::click());
114추가: let color = if resp.hovered() {
115추가: Color32::from_gray(0x2a)
116추가: } else {
117추가: FRAME_COLOR
118추가: };
119추가: ui.painter().rect_filled(layout.toggle, 0.0, color);
120추가: let symbol = if self.panel_open { ">" } else { "<" };
121추가: ui.painter().text(
122추가: layout.toggle.center(),
123추가: Align2::CENTER_CENTER,
124추가: symbol,
125추가: FontId::monospace(13.0),
126추가: DIM_TEXT,
127추가: );
128추가: if resp.clicked() {
129추가: self.panel_open = !self.panel_open;
130추가: actions.panel_toggled = Some(self.panel_open);
131추가: }
132추가: }
133추가:
134추가: fn side_panel(&mut self, ui: &mut Ui, rect: Rect) {
135추가: ui.painter().rect_filled(rect, 0.0, PANEL_BG);
136추가: let connected = false;
137추가: let inner = rect.shrink2(vec2(14.0, 16.0));
138추가: ui.scope_builder(UiBuilder::new().max_rect(inner), |ui| {
139추가: ui.spacing_mut().item_spacing.y = 10.0;
140추가: let s = &mut self.settings;
141추가:
142추가: ui.label(RichText::new("해상도").color(DIM_TEXT));
143추가: egui::ComboBox::from_id_salt("max_size")
144추가: .selected_text(size_label(s.max_size))
145추가: .width(inner.width())
146추가: .show_ui(ui, |ui| {
147추가: for v in [0, 2400, 1920, 1600, 1280, 1024] {
148추가: ui.selectable_value(&mut s.max_size, v, size_label(v));
149추가: }
150추가: });
151추가:
152추가: ui.label(RichText::new("FPS").color(DIM_TEXT));
153추가: ui.horizontal(|ui| {
154추가: for v in [30, 60, 90, 120] {
155추가: ui.selectable_value(&mut s.max_fps, v, v.to_string());
156추가: }
157추가: });
158추가:
159추가: ui.label(RichText::new("비트레이트").color(DIM_TEXT));
160추가: ui.add(egui::Slider::new(&mut s.bitrate_mbps, 2..=40).suffix(" Mbps"));
161추가:
162추가: ui.separator();
163추가: ui.checkbox(
164추가: &mut s.sync_clipboard_on_focus,
165추가: "창 포커스 시 클립보드 동기화",
166추가: );
167추가: ui.checkbox(&mut s.usb_adb_mode, "USB ADB 모드");
168추가:
169추가: ui.separator();
170추가: ui.add_enabled_ui(connected, |ui| {
171추가: ui.horizontal(|ui| {
172추가: for label in ["Back", "Home", "Recents"] {
173추가: // 연결 후 SYSTEM_ACTION으로 전송한다.
174추가: let _ = ui.button(label);
175추가: }
176추가: });
177추가: });
178추가: });
179추가: }
180추가:
181추가: fn disconnected_screen(&mut self, ui: &mut Ui, viewport: Rect) {
182추가: let center = viewport.center();
183추가: let input_rect = Rect::from_center_size(center, vec2(220.0, 30.0));
184추가:
185추가: let edit = TextEdit::singleline(&mut self.ip_input)
186추가: .hint_text("IP 주소")
187추가: .align(Align2::CENTER_CENTER)
188추가: .background_color(INPUT_BG)
189추가: .text_color(Color32::WHITE)
190추가: .font(FontId::proportional(16.0))
191추가: .margin(vec2(8.0, 6.0));
192추가: let resp = ui.put(input_rect, edit);
193추가: if std::mem::take(&mut self.focus_input) {
194추가: resp.request_focus();
195추가: }
196추가: if resp.changed() {
197추가: self.input_error = None;
198추가: }
199추가:
200추가: let enter = resp.lost_focus() && ui.input(|i| i.key_pressed(Key::Enter));
201추가: if enter {
202추가: let input = self.ip_input.clone();
203추가: self.try_connect(&input);
204추가: }
205추가:
206추가: let mut y = input_rect.max.y + 8.0;
207추가: if let Some(err) = &self.input_error {
208추가: ui.painter().text(
209추가: pos2(center.x, y),
210추가: Align2::CENTER_TOP,
211추가: err,
212추가: FontId::proportional(13.0),
213추가: ERROR_TEXT,
214추가: );
215추가: y += 22.0;
216추가: }
217추가:
218추가: if resp.has_focus() || self.ip_input.is_empty() {
219추가: let mut picked = None;
220추가: for item in self.recent.items() {
221추가: let r = Rect::from_center_size(pos2(center.x, y + 12.0), vec2(220.0, 24.0));
222추가: let b = Button::new(RichText::new(item).color(DIM_TEXT)).frame(false);
223추가: if ui.put(r, b).clicked() {
224추가: picked = Some(item.clone());
225추가: }
226추가: y += 26.0;
227추가: }
228추가: if let Some(item) = picked {
229추가: self.ip_input = item.clone();
230추가: self.try_connect(&item);
231추가: }
232추가: }
233추가: }
234추가:
235추가: fn try_connect(&mut self, input: &str) {
236추가: match parse_target(input) {
237추가: Ok(target) => {
238추가: self.ip_input = display_target(target);
239추가: self.input_error = None;
240추가: self.connection = Connection::Connecting { target };
241추가: }
242추가: Err(msg) => {
243추가: self.input_error = Some(msg.to_owned());
244추가: self.focus_input = true;
245추가: }
246추가: }
247추가: }
248추가:
249추가: fn connecting_screen(&mut self, ui: &mut Ui, viewport: Rect, target: SocketAddr) {
250추가: let c = viewport.center();
251추가: let p = ui.painter();
252추가: p.text(
253추가: c - vec2(0.0, 14.0),
254추가: Align2::CENTER_CENTER,
255추가: "휴대폰 승인 대기 중 (취소: Esc)",
256추가: FontId::proportional(15.0),
257추가: Color32::WHITE,
258추가: );
259추가: p.text(
260추가: c + vec2(0.0, 14.0),
261추가: Align2::CENTER_CENTER,
262추가: format!("{} · 확인 코드 ------", display_target(target)),
263추가: FontId::proportional(13.0),
264추가: DIM_TEXT,
265추가: );
266추가: if ui.input(|i| i.key_pressed(Key::Escape)) {
267추가: self.connection = Connection::Disconnected;
268추가: self.focus_input = true;
269추가: }
270추가: }
271추가: }
272추가:
273추가: fn title_bar(ui: &mut Ui, rect: Rect, actions: &mut Actions) {
274추가: let btn = vec2(rect.height() + 6.0, rect.height());
275추가: let close_rect = Rect::from_min_size(pos2(rect.max.x - btn.x, rect.min.y), btn);
276추가: let min_rect = close_rect.translate(vec2(-btn.x, 0.0));
277추가: let drag_rect = Rect::from_min_max(rect.min, pos2(min_rect.min.x, rect.max.y));
278추가:
279추가: let drag = ui.interact(drag_rect, egui::Id::unique("title_drag"), Sense::drag());
280추가: if drag.drag_started() {
281추가: actions.start_drag = true;
282추가: }
283추가:
284추가: if title_button(ui, min_rect, "–", Color32::from_gray(0x33)).clicked() {
285추가: actions.minimize = true;
286추가: }
287추가: if title_button(ui, close_rect, "×", Color32::from_rgb(0xc4, 0x2b, 0x1c)).clicked() {
288추가: actions.close = true;
289추가: }
290추가: }
291추가:
292추가: fn title_button(ui: &mut Ui, rect: Rect, text: &str, hover_bg: Color32) -> egui::Response {
293추가: let resp = ui.interact(
294추가: rect,
295추가: egui::Id::unique(("title_button", text)),
296추가: Sense::click(),
297추가: );
298추가: if resp.hovered() {
299추가: ui.painter().rect_filled(rect, 0.0, hover_bg);
300추가: }
301추가: ui.painter().text(
302추가: rect.center(),
303추가: Align2::CENTER_CENTER,
304추가: text,
305추가: FontId::proportional(14.0),
306추가: Color32::from_gray(0xc8),
307추가: );
308추가: resp
309추가: }
310추가:
311추가: fn size_label(v: u16) -> String {
312추가: if v == 0 {
313추가: "원본".to_owned()
314추가: } else {
315추가: format!("{v}p")
316추가: }
317추가: }