leejunyoung5819wayland-android-remote

공개

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

호스트 연결 계층, 가짜 기기, 아이콘 열 UI 추가

- 기기 연결: TLS 1.3(ring, AES-128-GCM/ChaCha20), 인증서 지문 고정(TOFU)과 6자리 확인 코드, Ed25519 PC 인증(Nonce+인증서 지문 서명), 세션 재개로 여는 영상 채널
- 테스트용 가짜 기기 서버(examples/fake_device.rs)와 통합 테스트
- GUI: 휴대폰 화면 고정, 왼쪽 아이콘 열(설정·스크린샷·연결 끊기), 화면 아래 내비게이션 줄(뒤로·홈·최근 앱), 독립 설정 창
- 아이콘 열·내비게이션 줄 빈 공간 드래그로 창 이동, 마우스 뒤로 옆 버튼을 BACK으로 전송
- 마우스 조작 시뮬레이션 테스트와 오프스크린 화면 스냅샷
작성자
LeeJunyoung
작성 시각
커밋
91377fd01ccdaa89b1b689030cd375945ccff3bf
부모
76097ad
이 시점의 파일 보기

변경된 파일 27개

+1,924-155

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

수정Cargo.lock

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

Raw로 열기
수정Cargo.toml+11-0
@@ -11,9 +11,20 @@ path = "src/main.rs"
1111
1212[dependencies]
1313bytes = "1.12.2"
14추가: ed25519-dalek = "3.0.0"
1415egui = "0.37.0"
1516egui-wgpu = { version = "0.37.0", features = ["winit", "wayland", "x11"] }
1617egui-winit = "0.37.0"
1718env_logger = "0.11.12"
19추가: getrandom = "0.4.3"
1820log = "0.4.35"
1921pollster = "1.0.3"
22추가: rustls = { version = "0.23.46", default-features = false, features = ["ring", "std", "logging"] }
23추가: sha2 = "0.11.1"
24추가: tokio = { version = "1.54.1", features = ["rt-multi-thread", "net", "io-util", "time", "sync", "macros"] }
25추가: tokio-rustls = { version = "0.26.6", default-features = false, features = ["ring", "logging"] }
26추가:
27추가: [dev-dependencies]
28추가: egui_kittest = { version = "0.37.0", features = ["wgpu", "snapshot"] }
29추가: image = { version = "0.25", default-features = false, features = ["png"] }
30추가: rcgen = { version = "0.14.10", default-features = false, features = ["ring", "pem"] }
수정README.md+10-0
@@ -41,3 +41,13 @@ cargo run
4141cd android
4242./gradlew assembleDebug
4343```
44추가:
45추가: ### 휴대폰 없이 테스트하기
46추가:
47추가: `examples/fake_device.rs`는 기기 데몬과 같은 프로토콜(TLS 1.3, Ed25519 인증, 영상 채널)로 응답하는 가짜 기기입니다. 영상 데이터는 디코딩할 수 없는 더미 바이트입니다.
48추가:
49추가: ```bash
50추가: cargo run --example fake_device -- --policy always --delay-ms 3000
51추가: ```
52추가:
53추가: 다른 터미널에서 `cargo run`으로 호스트를 띄우고 IP 입력창에 `127.0.0.1`을 입력합니다. 승인 정책은 `always`, `once`, `reject`, `never` 중에서 고릅니다.
추가examples/fake_device.rs+81-0
@@ -0,0 +1,81 @@
1추가: //! 가짜 기기 서버 실행기 (수동 GUI 테스트용).
2추가: //!
3추가: //! `cargo run --example fake_device -- [--bind 0.0.0.0:27200] [--policy always|once|reject|never] [--delay-ms 3000]`
4추가:
5추가: #[path = "../tests/common/fake_device.rs"]
6추가: mod fake_device;
7추가:
8추가: use std::net::SocketAddr;
9추가: use std::time::Duration;
10추가:
11추가: use fake_device::{FakeDevice, FakeDeviceConfig, PendingPolicy};
12추가: use wayland_android_remote::protocol::fingerprint_hex;
13추가:
14추가: const USAGE: &str =
15추가: "사용법: fake_device [--bind ADDR:PORT] [--policy always|once|reject|never] [--delay-ms N]";
16추가:
17추가: fn fail(msg: &str) -> ! {
18추가: eprintln!("{msg}\n{USAGE}");
19추가: std::process::exit(2);
20추가: }
21추가:
22추가: #[tokio::main]
23추가: async fn main() {
24추가: env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
25추가:
26추가: let mut bind: SocketAddr = "127.0.0.1:27200".parse().unwrap();
27추가: let mut policy = "always".to_owned();
28추가: let mut delay_ms: u64 = 3000;
29추가:
30추가: let mut args = std::env::args().skip(1);
31추가: while let Some(arg) = args.next() {
32추가: let mut value = || {
33추가: args.next()
34추가: .unwrap_or_else(|| fail(&format!("{arg} 값 없음")))
35추가: };
36추가: match arg.as_str() {
37추가: "--bind" => {
38추가: bind = value()
39추가: .parse()
40추가: .unwrap_or_else(|_| fail("--bind 주소 형식 오류"))
41추가: }
42추가: "--policy" => policy = value(),
43추가: "--delay-ms" => {
44추가: delay_ms = value()
45추가: .parse()
46추가: .unwrap_or_else(|_| fail("--delay-ms 숫자 오류"))
47추가: }
48추가: "-h" | "--help" => {
49추가: println!("{USAGE}");
50추가: return;
51추가: }
52추가: other => fail(&format!("알 수 없는 인자: {other}")),
53추가: }
54추가: }
55추가:
56추가: let after = Duration::from_millis(delay_ms);
57추가: let pending = match policy.as_str() {
58추가: "always" => PendingPolicy::ApproveAlways { after },
59추가: "once" => PendingPolicy::ApproveOnce { after },
60추가: "reject" => PendingPolicy::Reject { after },
61추가: "never" => PendingPolicy::NeverAnswer,
62추가: other => fail(&format!("알 수 없는 정책: {other}")),
63추가: };
64추가:
65추가: let config = FakeDeviceConfig {
66추가: pending,
67추가: ..FakeDeviceConfig::default()
68추가: };
69추가: let device = FakeDevice::start(bind, config)
70추가: .await
71추가: .unwrap_or_else(|e| fail(&format!("시작 실패: {e}")));
72추가:
73추가: println!("가짜 기기 수신 중: {}", device.addr());
74추가: println!("인증서 SHA-256: {}", fingerprint_hex(&device.cert_sha256()));
75추가: println!("확인 코드: {}", device.confirm_code());
76추가: println!("승인 정책: {pending:?} (화이트리스트는 메모리에만 유지)");
77추가:
78추가: // tokio signal 기능이 없으므로 Ctrl-C로 프로세스가 끝날 때까지 대기한다.
79추가: std::future::pending::<()>().await;
80추가: device.shutdown();
81추가: }
추가src/config.rs+12-0
@@ -0,0 +1,12 @@
1추가: //! 호스트 설정 파일 위치.
2추가:
3추가: use std::path::PathBuf;
4추가:
5추가: /// `$XDG_CONFIG_HOME/android-remote` 또는 `~/.config/android-remote`.
6추가: pub fn config_dir() -> Option<PathBuf> {
7추가: let base = std::env::var_os("XDG_CONFIG_HOME")
8추가: .filter(|v| !v.is_empty())
9추가: .map(PathBuf::from)
10추가: .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))?;
11추가: Some(base.join("android-remote"))
12추가: }
수정src/lib.rs+2-0
@@ -2,4 +2,6 @@
22//!
33//! Ubuntu(Wayland/X11)에서 Android 기기 화면을 미러링하고 마우스·키보드로 원격 제어한다.
44
5추가: pub mod config;
6추가: pub mod net;
57pub mod protocol;
추가src/net/client.rs+307-0
@@ -0,0 +1,307 @@
1추가: //! 기기 접속과 인증 (기획서 7.6 "세션 수립 순서").
2추가:
3추가: use std::net::SocketAddr;
4추가: use std::sync::Arc;
5추가: use std::time::Duration;
6추가:
7추가: use bytes::Bytes;
8추가: use rustls::client::ClientSessionMemoryCache;
9추가: use rustls::pki_types::ServerName;
10추가: use tokio::io::{AsyncReadExt, AsyncWriteExt};
11추가: use tokio::net::TcpStream;
12추가: use tokio::time::timeout;
13추가: use tokio_rustls::TlsConnector;
14추가: use tokio_rustls::client::TlsStream;
15추가:
16추가: use super::framed::{FramedError, FramedStream};
17추가: use super::identity::HostIdentity;
18추가: use super::tls::{PinnedVerifier, client_config};
19추가: use crate::protocol::{
20추가: AuthGrant, AuthHello, AuthResponse, AuthResultCode, AuthStatus, ChannelAttach, ChannelKind,
21추가: Message, VIDEO_HEADER_LEN, VideoPacketHeader, auth_signing_message, confirm_code,
22추가: };
23추가:
24추가: /// 기기와 주고받는 TLS 스트림.
25추가: pub type DeviceStream = TlsStream<TcpStream>;
26추가:
27추가: #[derive(Debug, Clone, Copy)]
28추가: pub struct ConnectOptions {
29추가: /// TCP 접속과 TLS 핸드셰이크 제한 시간.
30추가: pub connect_timeout: Duration,
31추가: /// 승인 대기가 없는 인증 단계 하나의 제한 시간.
32추가: pub step_timeout: Duration,
33추가: /// 휴대폰 승인 대기 제한 시간. 기기는 60초에 TIMEOUT을 보내므로 그보다 조금 길게 둔다.
34추가: pub approval_timeout: Duration,
35추가: }
36추가:
37추가: impl Default for ConnectOptions {
38추가: fn default() -> Self {
39추가: Self {
40추가: connect_timeout: Duration::from_secs(5),
41추가: step_timeout: Duration::from_secs(10),
42추가: approval_timeout: Duration::from_secs(65),
43추가: }
44추가: }
45추가: }
46추가:
47추가: /// 접속 진행 상황. UI가 대기 화면에 확인 코드를 보여줄 때 쓴다.
48추가: #[derive(Debug, Clone, PartialEq, Eq)]
49추가: pub enum ConnectEvent {
50추가: /// TLS 연결 완료. `pinned`가 false면 처음 보는 기기다.
51추가: TlsEstablished {
52추가: fingerprint: [u8; 32],
53추가: confirm_code: String,
54추가: pinned: bool,
55추가: },
56추가: /// 처음 접속하는 PC라 휴대폰 승인 팝업을 기다린다.
57추가: AwaitingApproval { confirm_code: String },
58추가: }
59추가:
60추가: #[derive(Debug)]
61추가: pub enum ConnectError {
62추가: Io(std::io::Error),
63추가: Tls(std::io::Error),
64추가: Timeout(&'static str),
65추가: /// 저장된 지문과 다른 인증서를 받았다 (기획서 5.5 "지문 불일치").
66추가: FingerprintMismatch {
67추가: expected: [u8; 32],
68추가: actual: [u8; 32],
69추가: },
70추가: /// 기기가 AUTH_CHALLENGE 단계에서 거부했다.
71추가: ChallengeRejected,
72추가: /// AUTH_RESULT가 OK가 아니다.
73추가: AuthFailed(AuthResultCode),
74추가: Protocol(FramedError),
75추가: Unexpected(&'static str),
76추가: }
77추가:
78추가: impl std::fmt::Display for ConnectError {
79추가: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80추가: match self {
81추가: Self::Io(e) => write!(f, "접속 실패: {e}"),
82추가: Self::Tls(e) => write!(f, "TLS 연결 실패: {e}"),
83추가: Self::Timeout(step) => write!(f, "{step} 시간 초과"),
84추가: Self::FingerprintMismatch { .. } => {
85추가: f.write_str("저장된 기기와 인증서가 다릅니다. 기기를 초기화했다면 기기 기록을 지운 뒤 다시 연결하세요")
86추가: }
87추가: Self::ChallengeRejected => f.write_str("기기가 연결을 거부했습니다"),
88추가: Self::AuthFailed(code) => match code {
89추가: AuthResultCode::Rejected => f.write_str("연결이 거부되었습니다"),
90추가: AuthResultCode::Timeout => f.write_str("승인 대기 시간이 지났습니다"),
91추가: AuthResultCode::SignatureInvalid => f.write_str("PC 서명 검증에 실패했습니다"),
92추가: AuthResultCode::Revoked => f.write_str("이 PC의 권한이 철회되었습니다"),
93추가: AuthResultCode::Ok => f.write_str("인증 실패"),
94추가: },
95추가: Self::Protocol(e) => write!(f, "{e}"),
96추가: Self::Unexpected(what) => write!(f, "예상하지 못한 응답: {what}"),
97추가: }
98추가: }
99추가: }
100추가:
101추가: impl std::error::Error for ConnectError {}
102추가:
103추가: impl From<FramedError> for ConnectError {
104추가: fn from(e: FramedError) -> Self {
105추가: Self::Protocol(e)
106추가: }
107추가: }
108추가:
109추가: /// 인증이 끝난 기기 세션.
110추가: pub struct Session {
111추가: pub target: SocketAddr,
112추가: /// 기기 TLS 인증서 지문.
113추가: pub fingerprint: [u8; 32],
114추가: pub grant: AuthGrant,
115추가: pub daemon_version: u32,
116추가: session_token: [u8; 32],
117추가: sessions: Arc<ClientSessionMemoryCache>,
118추가: control: FramedStream<DeviceStream>,
119추가: }
120추가:
121추가: /// 기기에 접속해 TLS 1.3 핸드셰이크와 Ed25519 인증을 마친다.
122추가: ///
123추가: /// `pinned`는 이 IP에 저장된 기기 지문이다. 결과의 `grant`가 [`AuthGrant::Always`]이면
124추가: /// 호출 측이 `fingerprint`를 [`super::KnownDevices`]에 저장한다.
125추가: pub async fn connect(
126추가: target: SocketAddr,
127추가: identity: &HostIdentity,
128추가: pinned: Option<[u8; 32]>,
129추가: options: ConnectOptions,
130추가: mut on_event: impl FnMut(ConnectEvent),
131추가: ) -> Result<Session, ConnectError> {
132추가: let sessions = Arc::new(ClientSessionMemoryCache::new(8));
133추가: let verifier = PinnedVerifier::new(pinned);
134추가: let tls = timeout(
135추가: options.connect_timeout,
136추가: open_tls(target, verifier.clone(), sessions.clone()),
137추가: )
138추가: .await
139추가: .map_err(|_| ConnectError::Timeout("연결"))?;
140추가:
141추가: let stream = match tls {
142추가: Ok(s) => s,
143추가: Err(e) => {
144추가: return Err(match (pinned, verifier.seen()) {
145추가: (Some(expected), Some(actual)) if expected != actual => {
146추가: ConnectError::FingerprintMismatch { expected, actual }
147추가: }
148추가: _ => e,
149추가: });
150추가: }
151추가: };
152추가: let fingerprint = verifier
153추가: .seen()
154추가: .ok_or(ConnectError::Unexpected("기기 인증서를 받지 못함"))?;
155추가: let code = confirm_code(&fingerprint);
156추가: on_event(ConnectEvent::TlsEstablished {
157추가: fingerprint,
158추가: confirm_code: code.clone(),
159추가: pinned: pinned.is_some(),
160추가: });
161추가:
162추가: let mut control = FramedStream::new(stream);
163추가: control
164추가: .send(&Message::AuthHello(AuthHello {
165추가: public_key: identity.public_key(),
166추가: hostname: identity.hostname().to_owned(),
167추가: }))
168추가: .await?;
169추가:
170추가: let challenge = match read(&mut control, options.step_timeout, "인증 요청").await? {
171추가: Message::AuthChallenge(c) => c,
172추가: _ => return Err(ConnectError::Unexpected("AUTH_CHALLENGE 대신 다른 메시지")),
173추가: };
174추가: let wait = match challenge.status {
175추가: AuthStatus::Approved => options.step_timeout,
176추가: AuthStatus::PendingUser => {
177추가: on_event(ConnectEvent::AwaitingApproval { confirm_code: code });
178추가: options.approval_timeout
179추가: }
180추가: AuthStatus::Rejected => return Err(ConnectError::ChallengeRejected),
181추가: };
182추가:
183추가: let signature = identity.sign(&auth_signing_message(&challenge.nonce, &fingerprint));
184추가: control
185추가: .send(&Message::AuthResponse(AuthResponse { signature }))
186추가: .await?;
187추가:
188추가: let result = match read(&mut control, wait, "휴대폰 승인").await? {
189추가: Message::AuthResult(r) => r,
190추가: _ => return Err(ConnectError::Unexpected("AUTH_RESULT 대신 다른 메시지")),
191추가: };
192추가: if result.result != AuthResultCode::Ok {
193추가: return Err(ConnectError::AuthFailed(result.result));
194추가: }
195추가:
196추가: Ok(Session {
197추가: target,
198추가: fingerprint,
199추가: grant: result.grant,
200추가: daemon_version: result.daemon_version,
201추가: session_token: result.session_token,
202추가: sessions,
203추가: control,
204추가: })
205추가: }
206추가:
207추가: impl Session {
208추가: /// 제어 채널. 입력·클립보드·영상 설정 메시지를 주고받는다.
209추가: pub fn control(&mut self) -> &mut FramedStream<DeviceStream> {
210추가: &mut self.control
211추가: }
212추가:
213추가: /// 같은 포트로 두 번째 연결을 열어 영상 채널로 묶는다 (기획서 7.6 "4단계").
214추가: /// 세션 토큰은 한 번만 쓸 수 있으므로 세션당 한 번만 호출한다.
215추가: pub async fn open_video(&self, connect_timeout: Duration) -> Result<VideoStream, ConnectError> {
216추가: let verifier = PinnedVerifier::new(Some(self.fingerprint));
217추가: let stream = timeout(
218추가: connect_timeout,
219추가: open_tls(self.target, verifier, self.sessions.clone()),
220추가: )
221추가: .await
222추가: .map_err(|_| ConnectError::Timeout("영상 채널 연결"))??;
223추가:
224추가: let mut framed = FramedStream::new(stream);
225추가: framed
226추가: .send(&Message::ChannelAttach(ChannelAttach {
227추가: kind: ChannelKind::Video,
228추가: session_token: self.session_token,
229추가: }))
230추가: .await?;
231추가: Ok(VideoStream {
232추가: stream: framed.into_inner(),
233추가: })
234추가: }
235추가:
236추가: pub fn into_control(self) -> FramedStream<DeviceStream> {
237추가: self.control
238추가: }
239추가: }
240추가:
241추가: /// 영상 채널. 기기에서 호스트로 영상 패킷만 흐른다.
242추가: pub struct VideoStream {
243추가: stream: DeviceStream,
244추가: }
245추가:
246추가: impl VideoStream {
247추가: /// 영상 패킷 하나(16바이트 헤더 + 인코딩 데이터)를 읽는다.
248추가: pub async fn read_packet(&mut self) -> Result<(VideoPacketHeader, Bytes), FramedError> {
249추가: let mut header = [0u8; VIDEO_HEADER_LEN];
250추가: read_exact_or_closed(&mut self.stream, &mut header).await?;
251추가: let header = VideoPacketHeader::decode(&header)?;
252추가: let mut data = vec![0u8; header.data_len as usize];
253추가: read_exact_or_closed(&mut self.stream, &mut data).await?;
254추가: Ok((header, Bytes::from(data)))
255추가: }
256추가:
257추가: pub async fn shutdown(mut self) {
258추가: let _ = self.stream.shutdown().await;
259추가: }
260추가: }
261추가:
262추가: async fn read_exact_or_closed(
263추가: stream: &mut DeviceStream,
264추가: buf: &mut [u8],
265추가: ) -> Result<(), FramedError> {
266추가: match stream.read_exact(buf).await {
267추가: Ok(_) => Ok(()),
268추가: Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => Err(FramedError::Closed),
269추가: Err(e) => Err(FramedError::Io(e)),
270추가: }
271추가: }
272추가:
273추가: async fn open_tls(
274추가: target: SocketAddr,
275추가: verifier: Arc<PinnedVerifier>,
276추가: sessions: Arc<ClientSessionMemoryCache>,
277추가: ) -> Result<DeviceStream, ConnectError> {
278추가: let config = client_config(verifier, sessions)
279추가: .map_err(|e| ConnectError::Tls(std::io::Error::other(e)))?;
280추가: let tcp = TcpStream::connect(target).await.map_err(ConnectError::Io)?;
281추가: tcp.set_nodelay(true).map_err(ConnectError::Io)?;
282추가: let name = ServerName::IpAddress(target.ip().into());
283추가: TlsConnector::from(Arc::new(config))
284추가: .connect(name, tcp)
285추가: .await
286추가: .map_err(ConnectError::Tls)
287추가: }
288추가:
289추가: async fn read(
290추가: control: &mut FramedStream<DeviceStream>,
291추가: limit: Duration,
292추가: step: &'static str,
293추가: ) -> Result<Message, ConnectError> {
294추가: loop {
295추가: let (_, msg) = timeout(limit, control.read_message())
296추가: .await
297추가: .map_err(|_| ConnectError::Timeout(step))??;
298추가: match msg {
299추가: Message::Ping | Message::Pong => continue,
300추가: Message::Error(e) => {
301추가: log::warn!("기기 오류 응답: {:#06x} {}", e.code, e.reason);
302추가: return Err(ConnectError::Unexpected("인증 중 ERROR 응답"));
303추가: }
304추가: other => return Ok(other),
305추가: }
306추가: }
307추가: }
추가src/net/framed.rs+104-0
@@ -0,0 +1,104 @@
1추가: //! 비동기 스트림 위의 제어 프레임 송수신.
2추가:
3추가: use bytes::BytesMut;
4추가: use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
5추가:
6추가: use crate::protocol::{Frame, FrameDecoder, Message, ProtocolError, encode_frame};
7추가:
8추가: /// 제어 채널 송수신 중 오류.
9추가: #[derive(Debug)]
10추가: pub enum FramedError {
11추가: Io(std::io::Error),
12추가: Protocol(ProtocolError),
13추가: /// 상대가 연결을 닫았다.
14추가: Closed,
15추가: }
16추가:
17추가: impl std::fmt::Display for FramedError {
18추가: fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
19추가: match self {
20추가: Self::Io(e) => write!(f, "입출력 오류: {e}"),
21추가: Self::Protocol(e) => write!(f, "프로토콜 오류: {e}"),
22추가: Self::Closed => f.write_str("상대가 연결을 닫았습니다"),
23추가: }
24추가: }
25추가: }
26추가:
27추가: impl std::error::Error for FramedError {}
28추가:
29추가: impl From<std::io::Error> for FramedError {
30추가: fn from(e: std::io::Error) -> Self {
31추가: Self::Io(e)
32추가: }
33추가: }
34추가:
35추가: impl From<ProtocolError> for FramedError {
36추가: fn from(e: ProtocolError) -> Self {
37추가: Self::Protocol(e)
38추가: }
39추가: }
40추가:
41추가: /// 제어 프레임 단위로 읽고 쓰는 스트림 래퍼. `S`는 보통 TLS 스트림이다.
42추가: pub struct FramedStream<S> {
43추가: stream: S,
44추가: decoder: FrameDecoder,
45추가: read_buf: Vec<u8>,
46추가: next_seq: u16,
47추가: }
48추가:
49추가: impl<S: AsyncRead + AsyncWrite + Unpin> FramedStream<S> {
50추가: pub fn new(stream: S) -> Self {
51추가: Self {
52추가: stream,
53추가: decoder: FrameDecoder::new(),
54추가: read_buf: vec![0; 16 * 1024],
55추가: next_seq: 0,
56추가: }
57추가: }
58추가:
59추가: /// 완성된 프레임 하나를 읽는다.
60추가: pub async fn read_frame(&mut self) -> Result<Frame, FramedError> {
61추가: loop {
62추가: if let Some(frame) = self.decoder.decode()? {
63추가: return Ok(frame);
64추가: }
65추가: let n = self.stream.read(&mut self.read_buf).await?;
66추가: if n == 0 {
67추가: return Err(FramedError::Closed);
68추가: }
69추가: self.decoder.extend(&self.read_buf[..n]);
70추가: }
71추가: }
72추가:
73추가: /// 프레임을 읽어 메시지로 해석한다. seq_id도 함께 돌려준다.
74추가: pub async fn read_message(&mut self) -> Result<(u16, Message), FramedError> {
75추가: let frame = self.read_frame().await?;
76추가: let seq = frame.header.seq_id;
77추가: Ok((seq, Message::decode(&frame)?))
78추가: }
79추가:
80추가: /// 다음 순환 seq_id로 메시지를 보낸다. 사용한 seq_id를 돌려준다.
81추가: pub async fn send(&mut self, msg: &Message) -> Result<u16, FramedError> {
82추가: let seq = self.next_seq;
83추가: self.next_seq = self.next_seq.wrapping_add(1);
84추가: self.send_with_seq(msg, seq).await?;
85추가: Ok(seq)
86추가: }
87추가:
88추가: /// 지정한 seq_id로 보낸다. PONG, ACK처럼 요청의 seq_id를 되돌려줄 때 쓴다.
89추가: pub async fn send_with_seq(&mut self, msg: &Message, seq: u16) -> Result<(), FramedError> {
90추가: let mut buf = BytesMut::new();
91추가: encode_frame(&msg.to_frame(seq), &mut buf);
92추가: self.stream.write_all(&buf).await?;
93추가: self.stream.flush().await?;
94추가: Ok(())
95추가: }
96추가:
97추가: pub fn get_ref(&self) -> &S {
98추가: &self.stream
99추가: }
100추가:
101추가: pub fn into_inner(self) -> S {
102추가: self.stream
103추가: }
104추가: }
추가src/net/identity.rs+145-0
@@ -0,0 +1,145 @@
1추가: //! 호스트 PC의 Ed25519 신원 키 (기획서 5.3).
2추가:
3추가: use std::fs;
4추가: use std::io::{self, Write};
5추가: use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
6추가: use std::path::{Path, PathBuf};
7추가:
8추가: use ed25519_dalek::{Signer, SigningKey};
9추가:
10추가: use crate::protocol::MAX_HOSTNAME_LEN;
11추가:
12추가: /// 호스트 PC를 식별하는 Ed25519 키와 기기에 보여줄 호스트명.
13추가: pub struct HostIdentity {
14추가: key: SigningKey,
15추가: hostname: String,
16추가: }
17추가:
18추가: impl HostIdentity {
19추가: /// 기본 키 파일 경로: `~/.config/android-remote/device_key`.
20추가: pub fn default_path() -> Option<PathBuf> {
21추가: crate::config::config_dir().map(|d| d.join("device_key"))
22추가: }
23추가:
24추가: /// 키 파일(32바이트 시드)을 읽고, 없으면 새로 만들어 0600 권한으로 저장한다.
25추가: pub fn load_or_create(path: &Path) -> io::Result<Self> {
26추가: match fs::read(path) {
27추가: Ok(bytes) => {
28추가: let seed: [u8; 32] = bytes.as_slice().try_into().map_err(|_| {
29추가: io::Error::new(
30추가: io::ErrorKind::InvalidData,
31추가: "키 파일 크기가 32바이트가 아닙니다",
32추가: )
33추가: })?;
34추가: Ok(Self::from_seed(seed))
35추가: }
36추가: Err(e) if e.kind() == io::ErrorKind::NotFound => {
37추가: let identity = Self::generate()?;
38추가: if let Some(dir) = path.parent() {
39추가: fs::create_dir_all(dir)?;
40추가: }
41추가: let mut f = fs::OpenOptions::new()
42추가: .write(true)
43추가: .create_new(true)
44추가: .mode(0o600)
45추가: .open(path)?;
46추가: f.write_all(&identity.key.to_bytes())?;
47추가: f.set_permissions(fs::Permissions::from_mode(0o600))?;
48추가: Ok(identity)
49추가: }
50추가: Err(e) => Err(e),
51추가: }
52추가: }
53추가:
54추가: /// 저장하지 않는 새 키를 만든다.
55추가: pub fn generate() -> io::Result<Self> {
56추가: let mut seed = [0u8; 32];
57추가: getrandom::fill(&mut seed).map_err(io::Error::other)?;
58추가: Ok(Self::from_seed(seed))
59추가: }
60추가:
61추가: pub fn from_seed(seed: [u8; 32]) -> Self {
62추가: Self {
63추가: key: SigningKey::from_bytes(&seed),
64추가: hostname: local_hostname(),
65추가: }
66추가: }
67추가:
68추가: pub fn with_hostname(mut self, hostname: impl Into<String>) -> Self {
69추가: self.hostname = truncate_utf8(hostname.into(), MAX_HOSTNAME_LEN);
70추가: self
71추가: }
72추가:
73추가: pub fn public_key(&self) -> [u8; 32] {
74추가: self.key.verifying_key().to_bytes()
75추가: }
76추가:
77추가: pub fn hostname(&self) -> &str {
78추가: &self.hostname
79추가: }
80추가:
81추가: pub fn sign(&self, message: &[u8]) -> [u8; 64] {
82추가: self.key.sign(message).to_bytes()
83추가: }
84추가: }
85추가:
86추가: fn local_hostname() -> String {
87추가: let name = fs::read_to_string("/proc/sys/kernel/hostname")
88추가: .map(|s| s.trim().to_owned())
89추가: .unwrap_or_default();
90추가: let name = if name.is_empty() {
91추가: "linux-host".to_owned()
92추가: } else {
93추가: name
94추가: };
95추가: truncate_utf8(name, MAX_HOSTNAME_LEN)
96추가: }
97추가:
98추가: fn truncate_utf8(mut s: String, max: usize) -> String {
99추가: if s.len() > max {
100추가: let mut end = max;
101추가: while !s.is_char_boundary(end) {
102추가: end -= 1;
103추가: }
104추가: s.truncate(end);
105추가: }
106추가: s
107추가: }
108추가:
109추가: #[cfg(test)]
110추가: mod tests {
111추가: use super::*;
112추가: use ed25519_dalek::{Signature, VerifyingKey};
113추가:
114추가: #[test]
115추가: fn key_file_roundtrip_and_permissions() {
116추가: let dir = std::env::temp_dir().join(format!("ar-identity-{}", std::process::id()));
117추가: let path = dir.join("device_key");
118추가: let _ = fs::remove_dir_all(&dir);
119추가:
120추가: let a = HostIdentity::load_or_create(&path).unwrap();
121추가: let b = HostIdentity::load_or_create(&path).unwrap();
122추가: assert_eq!(a.public_key(), b.public_key());
123추가: let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
124추가: assert_eq!(mode, 0o600);
125추가: fs::remove_dir_all(&dir).unwrap();
126추가: }
127추가:
128추가: #[test]
129추가: fn signature_verifies() {
130추가: let id = HostIdentity::generate().unwrap();
131추가: let sig = id.sign(b"hello");
132추가: let vk = VerifyingKey::from_bytes(&id.public_key()).unwrap();
133추가: vk.verify_strict(b"hello", &Signature::from_bytes(&sig))
134추가: .unwrap();
135추가: }
136추가:
137추가: #[test]
138추가: fn hostname_is_truncated_on_char_boundary() {
139추가: let id = HostIdentity::generate()
140추가: .unwrap()
141추가: .with_hostname("가".repeat(100));
142추가: assert!(id.hostname().len() <= MAX_HOSTNAME_LEN);
143추가: assert!(id.hostname().chars().all(|c| c == '가'));
144추가: }
145추가: }
추가src/net/known.rs+113-0
@@ -0,0 +1,113 @@
1추가: //! 고정된 기기 인증서 지문 목록 (기획서 5.5 "인증서 고정").
2추가: //!
3추가: //! 파일 형식: 한 줄에 `IP 지문(16진수 64자)`.
4추가:
5추가: use std::collections::BTreeMap;
6추가: use std::fs;
7추가: use std::io;
8추가: use std::net::IpAddr;
9추가: use std::path::{Path, PathBuf};
10추가:
11추가: use crate::protocol::{fingerprint_hex, parse_fingerprint_hex};
12추가:
13추가: #[derive(Debug, Default)]
14추가: pub struct KnownDevices {
15추가: path: Option<PathBuf>,
16추가: devices: BTreeMap<IpAddr, [u8; 32]>,
17추가: }
18추가:
19추가: impl KnownDevices {
20추가: /// 기본 경로 `~/.config/android-remote/known_devices`에서 읽는다.
21추가: pub fn load_default() -> Self {
22추가: match crate::config::config_dir() {
23추가: Some(dir) => Self::load(&dir.join("known_devices")),
24추가: None => Self::default(),
25추가: }
26추가: }
27추가:
28추가: /// 파일을 읽는다. 없거나 형식이 틀린 줄은 건너뛴다.
29추가: pub fn load(path: &Path) -> Self {
30추가: let devices = fs::read_to_string(path)
31추가: .map(|s| parse(&s))
32추가: .unwrap_or_default();
33추가: Self {
34추가: path: Some(path.to_owned()),
35추가: devices,
36추가: }
37추가: }
38추가:
39추가: /// 파일 없이 메모리에서만 쓴다 (테스트용).
40추가: pub fn in_memory() -> Self {
41추가: Self::default()
42추가: }
43추가:
44추가: pub fn get(&self, ip: IpAddr) -> Option<[u8; 32]> {
45추가: self.devices.get(&ip).copied()
46추가: }
47추가:
48추가: pub fn insert(&mut self, ip: IpAddr, fingerprint: [u8; 32]) -> io::Result<()> {
49추가: self.devices.insert(ip, fingerprint);
50추가: self.save()
51추가: }
52추가:
53추가: /// 사이드 메뉴의 "기기 기록 지우기"에서 쓴다.
54추가: pub fn remove(&mut self, ip: IpAddr) -> io::Result<()> {
55추가: if self.devices.remove(&ip).is_some() {
56추가: self.save()?;
57추가: }
58추가: Ok(())
59추가: }
60추가:
61추가: fn save(&self) -> io::Result<()> {
62추가: let Some(path) = &self.path else {
63추가: return Ok(());
64추가: };
65추가: if let Some(dir) = path.parent() {
66추가: fs::create_dir_all(dir)?;
67추가: }
68추가: let body: String = self
69추가: .devices
70추가: .iter()
71추가: .map(|(ip, fp)| format!("{ip} {}\n", fingerprint_hex(fp)))
72추가: .collect();
73추가: fs::write(path, body)
74추가: }
75추가: }
76추가:
77추가: fn parse(s: &str) -> BTreeMap<IpAddr, [u8; 32]> {
78추가: s.lines()
79추가: .filter_map(|line| {
80추가: let mut parts = line.split_whitespace();
81추가: let ip = parts.next()?.parse().ok()?;
82추가: let fp = parse_fingerprint_hex(parts.next()?)?;
83추가: Some((ip, fp))
84추가: })
85추가: .collect()
86추가: }
87추가:
88추가: #[cfg(test)]
89추가: mod tests {
90추가: use super::*;
91추가:
92추가: #[test]
93추가: fn save_and_reload() {
94추가: let dir = std::env::temp_dir().join(format!("ar-known-{}", std::process::id()));
95추가: let path = dir.join("known_devices");
96추가: let _ = fs::remove_dir_all(&dir);
97추가:
98추가: let ip: IpAddr = "192.168.0.7".parse().unwrap();
99추가: let mut known = KnownDevices::load(&path);
100추가: known.insert(ip, [7; 32]).unwrap();
101추가: assert_eq!(KnownDevices::load(&path).get(ip), Some([7; 32]));
102추가:
103추가: known.remove(ip).unwrap();
104추가: assert_eq!(KnownDevices::load(&path).get(ip), None);
105추가: fs::remove_dir_all(&dir).unwrap();
106추가: }
107추가:
108추가: #[test]
109추가: fn skips_malformed_lines() {
110추가: let map = parse("10.0.0.1 abc\nnot-ip 00\n10.0.0.2 ".to_owned().as_str());
111추가: assert!(map.is_empty());
112추가: }
113추가: }
추가src/net/mod.rs+14-0
@@ -0,0 +1,14 @@
1추가: //! 기기 연결: TLS 1.3, 인증서 고정, Ed25519 인증, 영상 채널 (기획서 5.3, 5.5, 7.6).
2추가:
3추가: mod client;
4추가: pub mod framed;
5추가: mod identity;
6추가: mod known;
7추가: mod tls;
8추가:
9추가: pub use client::{
10추가: ConnectError, ConnectEvent, ConnectOptions, DeviceStream, Session, VideoStream, connect,
11추가: };
12추가: pub use framed::{FramedError, FramedStream};
13추가: pub use identity::HostIdentity;
14추가: pub use known::KnownDevices;
추가src/net/tls.rs+115-0
@@ -0,0 +1,115 @@
1추가: //! TLS 1.3 클라이언트 설정과 기기 인증서 고정 검증기 (기획서 5.5).
2추가: //!
3추가: //! 기기 인증서는 자체 서명이므로 CA 검증 대신 SHA-256 지문을 비교한다. 처음 보는 기기는
4추가: //! 지문을 기록만 하고 통과시키며(TOFU), 사용자는 6자리 확인 코드로 지문을 대조한다.
5추가:
6추가: use std::sync::{Arc, Mutex};
7추가:
8추가: use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
9추가: use rustls::client::{ClientSessionMemoryCache, Resumption};
10추가: use rustls::crypto::{CryptoProvider, verify_tls13_signature};
11추가: use rustls::pki_types::{CertificateDer, ServerName, UnixTime};
12추가: use rustls::{CertificateError, ClientConfig, DigitallySignedStruct, Error, SignatureScheme};
13추가:
14추가: use crate::protocol::cert_fingerprint;
15추가:
16추가: /// 한 번의 TLS 연결에 쓰는 검증기. 실제로 받은 지문을 기억해 둔다.
17추가: #[derive(Debug)]
18추가: pub(crate) struct PinnedVerifier {
19추가: expected: Option<[u8; 32]>,
20추가: seen: Mutex<Option<[u8; 32]>>,
21추가: provider: Arc<CryptoProvider>,
22추가: }
23추가:
24추가: impl PinnedVerifier {
25추가: pub(crate) fn new(expected: Option<[u8; 32]>) -> Arc<Self> {
26추가: Arc::new(Self {
27추가: expected,
28추가: seen: Mutex::new(None),
29추가: provider: provider(),
30추가: })
31추가: }
32추가:
33추가: /// 핸드셰이크 중 받은 인증서 지문. 세션 재개로 인증서를 받지 않았으면 `None`.
34추가: pub(crate) fn seen(&self) -> Option<[u8; 32]> {
35추가: *self.seen.lock().unwrap_or_else(|e| e.into_inner())
36추가: }
37추가: }
38추가:
39추가: impl ServerCertVerifier for PinnedVerifier {
40추가: fn verify_server_cert(
41추가: &self,
42추가: end_entity: &CertificateDer<'_>,
43추가: _intermediates: &[CertificateDer<'_>],
44추가: _server_name: &ServerName<'_>,
45추가: _ocsp_response: &[u8],
46추가: _now: UnixTime,
47추가: ) -> Result<ServerCertVerified, Error> {
48추가: let fp = cert_fingerprint(end_entity);
49추가: *self.seen.lock().unwrap_or_else(|e| e.into_inner()) = Some(fp);
50추가: match self.expected {
51추가: Some(expected) if expected != fp => Err(Error::InvalidCertificate(
52추가: CertificateError::ApplicationVerificationFailure,
53추가: )),
54추가: _ => Ok(ServerCertVerified::assertion()),
55추가: }
56추가: }
57추가:
58추가: fn verify_tls12_signature(
59추가: &self,
60추가: _message: &[u8],
61추가: _cert: &CertificateDer<'_>,
62추가: _dss: &DigitallySignedStruct,
63추가: ) -> Result<HandshakeSignatureValid, Error> {
64추가: // TLS 1.3만 허용하므로 호출되지 않아야 한다.
65추가: Err(Error::General("TLS 1.2는 지원하지 않습니다".into()))
66추가: }
67추가:
68추가: fn verify_tls13_signature(
69추가: &self,
70추가: message: &[u8],
71추가: cert: &CertificateDer<'_>,
72추가: dss: &DigitallySignedStruct,
73추가: ) -> Result<HandshakeSignatureValid, Error> {
74추가: verify_tls13_signature(
75추가: message,
76추가: cert,
77추가: dss,
78추가: &self.provider.signature_verification_algorithms,
79추가: )
80추가: }
81추가:
82추가: fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
83추가: self.provider
84추가: .signature_verification_algorithms
85추가: .supported_schemes()
86추가: }
87추가: }
88추가:
89추가: /// ring 기반 암호 공급자. 암호 스위트는 기획서대로 AES-128-GCM과 ChaCha20-Poly1305만 남긴다.
90추가: pub(crate) fn provider() -> Arc<CryptoProvider> {
91추가: use rustls::crypto::ring::{cipher_suite, default_provider};
92추가: Arc::new(CryptoProvider {
93추가: cipher_suites: vec![
94추가: cipher_suite::TLS13_AES_128_GCM_SHA256,
95추가: cipher_suite::TLS13_CHACHA20_POLY1305_SHA256,
96추가: ],
97추가: ..default_provider()
98추가: })
99추가: }
100추가:
101추가: /// 세션 재개 저장소를 공유하는 TLS 1.3 클라이언트 설정. 영상 연결이 제어 연결의 세션을
102추가: /// 재개해 핸드셰이크 시간을 줄인다 (기획서 5.5 "영상 연결"). 0-RTT는 쓰지 않는다.
103추가: pub(crate) fn client_config(
104추가: verifier: Arc<PinnedVerifier>,
105추가: sessions: Arc<ClientSessionMemoryCache>,
106추가: ) -> Result<ClientConfig, Error> {
107추가: let mut config = ClientConfig::builder_with_provider(provider())
108추가: .with_protocol_versions(&[&rustls::version::TLS13])?
109추가: .dangerous()
110추가: .with_custom_certificate_verifier(verifier)
111추가: .with_no_client_auth();
112추가: config.resumption = Resumption::store(sessions);
113추가: config.enable_early_data = false;
114추가: Ok(config)
115추가: }
추가src/protocol/auth.rs+55-0
@@ -0,0 +1,55 @@
1추가: //! 기기 인증서 지문과 확인 코드 (기획서 5.5).
2추가:
3추가: use sha2::{Digest, Sha256};
4추가:
5추가: /// 인증서 DER의 SHA-256 지문.
6추가: pub fn cert_fingerprint(cert_der: &[u8]) -> [u8; 32] {
7추가: Sha256::digest(cert_der).into()
8추가: }
9추가:
10추가: /// 지문 앞 8바이트를 Big-Endian u64로 읽어 1,000,000으로 나눈 나머지를 6자리로 표시한다.
11추가: /// 호스트 대기 화면과 동반 앱 승인 팝업이 같은 계산을 해야 한다.
12추가: pub fn confirm_code(fingerprint: &[u8; 32]) -> String {
13추가: let mut head = [0u8; 8];
14추가: head.copy_from_slice(&fingerprint[..8]);
15추가: format!("{:06}", u64::from_be_bytes(head) % 1_000_000)
16추가: }
17추가:
18추가: /// 지문을 소문자 16진수 64자로 표시한다.
19추가: pub fn fingerprint_hex(fingerprint: &[u8; 32]) -> String {
20추가: fingerprint.iter().map(|b| format!("{b:02x}")).collect()
21추가: }
22추가:
23추가: /// [`fingerprint_hex`]의 역변환.
24추가: pub fn parse_fingerprint_hex(s: &str) -> Option<[u8; 32]> {
25추가: let s = s.trim();
26추가: if s.len() != 64 || !s.is_ascii() {
27추가: return None;
28추가: }
29추가: let mut out = [0u8; 32];
30추가: for (i, byte) in out.iter_mut().enumerate() {
31추가: *byte = u8::from_str_radix(&s[i * 2..i * 2 + 2], 16).ok()?;
32추가: }
33추가: Some(out)
34추가: }
35추가:
36추가: #[cfg(test)]
37추가: mod tests {
38추가: use super::*;
39추가:
40추가: #[test]
41추가: fn confirm_code_is_six_digits_from_first_eight_bytes() {
42추가: let mut fp = [0xFFu8; 32];
43추가: fp[..8].copy_from_slice(&1_234_567u64.to_be_bytes());
44추가: assert_eq!(confirm_code(&fp), "234567");
45추가: fp[..8].copy_from_slice(&42u64.to_be_bytes());
46추가: assert_eq!(confirm_code(&fp), "000042");
47추가: }
48추가:
49추가: #[test]
50추가: fn hex_roundtrip() {
51추가: let fp = cert_fingerprint(b"test");
52추가: assert_eq!(parse_fingerprint_hex(&fingerprint_hex(&fp)), Some(fp));
53추가: assert_eq!(parse_fingerprint_hex("zz"), None);
54추가: }
55추가: }
수정src/protocol/mod.rs+2-0
@@ -4,10 +4,12 @@
44//! TCP(TLS) 스트림은 프레임 경계를 보장하지 않으므로 [`FrameDecoder`]가 부분 수신과
55//! 여러 프레임이 한 번에 도착하는 경우를 모두 처리한다.
66
7추가: mod auth;
78mod frame;
89mod messages;
910mod msg_type;
1011
12추가: pub use auth::{cert_fingerprint, confirm_code, fingerprint_hex, parse_fingerprint_hex};
1113pub use frame::{Frame, FrameDecoder, FrameHeader, encode_frame};
1214pub use messages::{
1315 AuthChallenge, AuthGrant, AuthHello, AuthResponse, AuthResult, AuthResultCode, AuthStatus,
추가src/ui/conn.rs+286-0
@@ -0,0 +1,286 @@
1추가: //! GUI와 네트워크 계층 사이의 연결 관리. 네트워크 작업은 tokio 런타임에서 돌고,
2추가: //! 결과는 채널로 UI 스레드에 전달한 뒤 이벤트 루프를 깨운다.
3추가:
4추가: use std::net::SocketAddr;
5추가: use std::sync::mpsc;
6추가: use std::sync::{Arc, Mutex};
7추가: use std::time::Duration;
8추가:
9추가: use tokio::runtime::Runtime;
10추가: use tokio::sync::mpsc as tmpsc;
11추가: use tokio::task::JoinHandle;
12추가:
13추가: use wayland_android_remote::net::{
14추가: ConnectError, ConnectEvent, ConnectOptions, FramedError, HostIdentity, KnownDevices, connect,
15추가: };
16추가: use wayland_android_remote::protocol::{
17추가: AuthGrant, CodecMask, Message, SystemAction, VideoConfig, VideoConfigRequest,
18추가: };
19추가:
20추가: /// UI에 알리는 연결 상태 변화.
21추가: #[derive(Debug, Clone)]
22추가: pub enum ConnEvent {
23추가: /// TLS 연결 완료. 확인 코드를 대기 화면에 표시한다.
24추가: Tls { confirm_code: String },
25추가: /// 휴대폰 승인 대기 중.
26추가: AwaitingApproval { confirm_code: String },
27추가: /// 인증 완료.
28추가: Connected { grant: AuthGrant },
29추가: /// 기기가 영상 설정을 알려왔다.
30추가: VideoConfig(VideoConfig),
31추가: /// 영상 패킷 수신 누계.
32추가: VideoFrames(u64),
33추가: /// 연결 실패 또는 종료. 사용자에게 보여줄 문구.
34추가: Ended(String),
35추가: }
36추가:
37추가: /// UI에서 연결 작업으로 보내는 명령.
38추가: #[derive(Debug)]
39추가: pub enum ConnCommand {
40추가: System(SystemAction),
41추가: RequestVideo(VideoConfigRequest),
42추가: }
43추가:
44추가: pub type Waker = Arc<dyn Fn() + Send + Sync>;
45추가:
46추가: pub struct Connector {
47추가: runtime: Runtime,
48추가: identity: Arc<HostIdentity>,
49추가: known: Arc<Mutex<KnownDevices>>,
50추가: waker: Waker,
51추가: }
52추가:
53추가: /// 진행 중인 연결 하나. 버리면 연결을 끊는다.
54추가: pub struct ConnHandle {
55추가: pub events: mpsc::Receiver<ConnEvent>,
56추가: commands: tmpsc::UnboundedSender<ConnCommand>,
57추가: task: JoinHandle<()>,
58추가: }
59추가:
60추가: impl ConnHandle {
61추가: pub fn send(&self, cmd: ConnCommand) {
62추가: let _ = self.commands.send(cmd);
63추가: }
64추가: }
65추가:
66추가: impl Drop for ConnHandle {
67추가: fn drop(&mut self) {
68추가: self.task.abort();
69추가: }
70추가: }
71추가:
72추가: impl Connector {
73추가: pub fn new(waker: Waker) -> std::io::Result<Self> {
74추가: let runtime = tokio::runtime::Builder::new_multi_thread()
75추가: .worker_threads(2)
76추가: .thread_name("android-remote-net")
77추가: .enable_all()
78추가: .build()?;
79추가: let identity = match HostIdentity::default_path() {
80추가: Some(path) => HostIdentity::load_or_create(&path).unwrap_or_else(|e| {
81추가: log::error!(
82추가: "PC 키를 읽지 못해 임시 키를 씁니다 ({}): {e}",
83추가: path.display()
84추가: );
85추가: HostIdentity::generate().expect("난수 생성 실패")
86추가: }),
87추가: None => HostIdentity::generate()?,
88추가: };
89추가: Ok(Self {
90추가: runtime,
91추가: identity: Arc::new(identity),
92추가: known: Arc::new(Mutex::new(KnownDevices::load_default())),
93추가: waker,
94추가: })
95추가: }
96추가:
97추가: pub fn start(&self, target: SocketAddr, video: VideoConfigRequest) -> ConnHandle {
98추가: let (tx, rx) = mpsc::channel();
99추가: let (cmd_tx, cmd_rx) = tmpsc::unbounded_channel();
100추가: let emit = Emitter {
101추가: tx,
102추가: waker: self.waker.clone(),
103추가: };
104추가: let task = self.runtime.spawn(run(
105추가: target,
106추가: self.identity.clone(),
107추가: self.known.clone(),
108추가: video,
109추가: emit,
110추가: cmd_rx,
111추가: ));
112추가: ConnHandle {
113추가: events: rx,
114추가: commands: cmd_tx,
115추가: task,
116추가: }
117추가: }
118추가:
119추가: /// 저장된 기기 지문을 지운다 (기획서 5.5 "지문 불일치" 후 재승인).
120추가: pub fn forget_device(&self, target: SocketAddr) {
121추가: let mut known = self.known.lock().unwrap_or_else(|e| e.into_inner());
122추가: if let Err(e) = known.remove(target.ip()) {
123추가: log::warn!("기기 기록 삭제 실패: {e}");
124추가: }
125추가: }
126추가: }
127추가:
128추가: #[derive(Clone)]
129추가: struct Emitter {
130추가: tx: mpsc::Sender<ConnEvent>,
131추가: waker: Waker,
132추가: }
133추가:
134추가: impl Emitter {
135추가: fn emit(&self, event: ConnEvent) {
136추가: if self.tx.send(event).is_ok() {
137추가: (self.waker)();
138추가: }
139추가: }
140추가: }
141추가:
142추가: async fn run(
143추가: target: SocketAddr,
144추가: identity: Arc<HostIdentity>,
145추가: known: Arc<Mutex<KnownDevices>>,
146추가: video: VideoConfigRequest,
147추가: emit: Emitter,
148추가: mut commands: tmpsc::UnboundedReceiver<ConnCommand>,
149추가: ) {
150추가: let pinned = known
151추가: .lock()
152추가: .unwrap_or_else(|e| e.into_inner())
153추가: .get(target.ip());
154추가:
155추가: let on_event = |e: ConnectEvent| match e {
156추가: ConnectEvent::TlsEstablished { confirm_code, .. } => {
157추가: emit.emit(ConnEvent::Tls { confirm_code });
158추가: }
159추가: ConnectEvent::AwaitingApproval { confirm_code } => {
160추가: emit.emit(ConnEvent::AwaitingApproval { confirm_code });
161추가: }
162추가: };
163추가: let mut session = match connect(
164추가: target,
165추가: &identity,
166추가: pinned,
167추가: ConnectOptions::default(),
168추가: on_event,
169추가: )
170추가: .await
171추가: {
172추가: Ok(s) => s,
173추가: Err(e) => {
174추가: emit.emit(ConnEvent::Ended(describe_connect_error(&e)));
175추가: return;
176추가: }
177추가: };
178추가:
179추가: if session.grant == AuthGrant::Always {
180추가: let mut known = known.lock().unwrap_or_else(|e| e.into_inner());
181추가: if let Err(e) = known.insert(target.ip(), session.fingerprint) {
182추가: log::warn!("기기 지문 저장 실패: {e}");
183추가: }
184추가: }
185추가: emit.emit(ConnEvent::Connected {
186추가: grant: session.grant,
187추가: });
188추가:
189추가: if let Err(e) = session
190추가: .control()
191추가: .send(&Message::VideoConfigRequest(video))
192추가: .await
193추가: {
194추가: emit.emit(ConnEvent::Ended(format!("연결이 끊겼습니다: {e}")));
195추가: return;
196추가: }
197추가:
198추가: // 영상 채널: 디코더가 붙기 전까지는 수신 프레임 수만 센다.
199추가: let video_task = match session.open_video(Duration::from_secs(5)).await {
200추가: Ok(mut stream) => {
201추가: let emit = emit.clone();
202추가: Some(tokio::spawn(async move {
203추가: let mut frames = 0u64;
204추가: while let Ok((header, _data)) = stream.read_packet().await {
205추가: if !header.is_config {
206추가: frames += 1;
207추가: emit.emit(ConnEvent::VideoFrames(frames));
208추가: }
209추가: }
210추가: }))
211추가: }
212추가: Err(e) => {
213추가: log::warn!("영상 채널 연결 실패: {e}");
214추가: None
215추가: }
216추가: };
217추가:
218추가: let reason = control_loop(session.control(), &mut commands, &emit).await;
219추가: if let Some(t) = video_task {
220추가: t.abort();
221추가: }
222추가: emit.emit(ConnEvent::Ended(reason));
223추가: }
224추가:
225추가: async fn control_loop(
226추가: control: &mut wayland_android_remote::net::FramedStream<
227추가: wayland_android_remote::net::DeviceStream,
228추가: >,
229추가: commands: &mut tmpsc::UnboundedReceiver<ConnCommand>,
230추가: emit: &Emitter,
231추가: ) -> String {
232추가: let mut ping = tokio::time::interval(Duration::from_secs(2));
233추가: loop {
234추가: tokio::select! {
235추가: msg = control.read_message() => match msg {
236추가: Ok((seq, Message::Ping)) => {
237추가: if let Err(e) = control.send_with_seq(&Message::Pong, seq).await {
238추가: return format!("연결이 끊겼습니다: {e}");
239추가: }
240추가: }
241추가: Ok((_, Message::VideoConfig(cfg))) => emit.emit(ConnEvent::VideoConfig(cfg)),
242추가: Ok((_, Message::Error(e))) => log::warn!("기기 오류: {:#06x} {}", e.code, e.reason),
243추가: Ok((_, other)) => log::debug!("처리하지 않은 메시지: {:?}", other.msg_type()),
244추가: Err(FramedError::Closed) => return "기기가 연결을 닫았습니다".to_owned(),
245추가: Err(e) => return format!("연결이 끊겼습니다: {e}"),
246추가: },
247추가: cmd = commands.recv() => {
248추가: let msg = match cmd {
249추가: Some(ConnCommand::System(a)) => Message::SystemAction(a),
250추가: Some(ConnCommand::RequestVideo(r)) => Message::VideoConfigRequest(r),
251추가: None => return "연결을 끊었습니다".to_owned(),
252추가: };
253추가: if let Err(e) = control.send(&msg).await {
254추가: return format!("연결이 끊겼습니다: {e}");
255추가: }
256추가: }
257추가: _ = ping.tick() => {
258추가: if let Err(e) = control.send(&Message::Ping).await {
259추가: return format!("연결이 끊겼습니다: {e}");
260추가: }
261추가: }
262추가: }
263추가: }
264추가: }
265추가:
266추가: fn describe_connect_error(e: &ConnectError) -> String {
267추가: match e {
268추가: ConnectError::Io(io) if io.kind() == std::io::ErrorKind::ConnectionRefused => {
269추가: "휴대폰에서 Android Remote 앱을 열어 서비스를 켜 주세요".to_owned()
270추가: }
271추가: ConnectError::Timeout("연결") => "기기에 연결할 수 없습니다 (시간 초과)".to_owned(),
272추가: other => other.to_string(),
273추가: }
274추가: }
275추가:
276추가: /// 사이드 메뉴 설정을 영상 설정 요청으로 바꾼다.
277추가: pub fn video_request(max_size: u16, max_fps: u8, bitrate_mbps: u32) -> VideoConfigRequest {
278추가: VideoConfigRequest {
279추가: max_size,
280추가: max_fps,
281추가: // 호스트는 NVDEC/VA-API로 세 코덱 모두 하드웨어 디코딩할 수 있다고 가정한다.
282추가: // 디코더를 붙일 때 실제 지원 여부로 바꾼다.
283추가: codecs: CodecMask::H264 | CodecMask::H265 | CodecMask::AV1,
284추가: bitrate: bitrate_mbps * 1_000_000,
285추가: }
286추가: }
수정src/ui/fonts.rs+6-0
@@ -44,3 +44,9 @@ fn fc_match_korean() -> Option<(String, u32)> {
4444 let index = lines.next()?.trim().parse().ok()?;
4545 (!path.is_empty()).then_some((path, index))
4646}
47추가:
48추가: /// `HarnessBuilder::with_context_setup`처럼 `&Context`를 받는 콜백용.
49추가: #[cfg(test)]
50추가: pub fn install_korean_font_owned(ctx: &egui::Context) {
51추가: install_korean_font(ctx);
52추가: }
추가src/ui/icons.rs+88-0
@@ -0,0 +1,88 @@
1추가: //! 아이콘 열에 쓰는 선 아이콘. 폰트에 의존하지 않도록 벡터로 직접 그린다.
2추가:
3추가: use std::f32::consts::TAU;
4추가:
5추가: use egui::{Color32, Painter, Pos2, Rect, Shape, Stroke, pos2, vec2};
6추가:
7추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
8추가: pub enum Icon {
9추가: Settings,
10추가: Screenshot,
11추가: Back,
12추가: Home,
13추가: Recents,
14추가: Disconnect,
15추가: }
16추가:
17추가: /// `rect` 가운데에 18px 크기로 아이콘을 그린다.
18추가: pub fn paint(painter: &Painter, rect: Rect, icon: Icon, color: Color32) {
19추가: let c = rect.center();
20추가: let s = 9.0; // 반지름 기준 크기
21추가: let stroke = Stroke::new(1.6, color);
22추가: match icon {
23추가: Icon::Settings => gear(painter, c, s, stroke),
24추가: Icon::Screenshot => camera(painter, c, s, stroke),
25추가: Icon::Back => {
26추가: let pts = vec![
27추가: c + vec2(-s * 0.75, 0.0),
28추가: c + vec2(s * 0.6, -s * 0.8),
29추가: c + vec2(s * 0.6, s * 0.8),
30추가: ];
31추가: painter.add(Shape::closed_line(pts, stroke));
32추가: }
33추가: Icon::Home => {
34추가: painter.circle_stroke(c, s * 0.75, stroke);
35추가: }
36추가: Icon::Recents => {
37추가: let r = Rect::from_center_size(c, vec2(s * 1.4, s * 1.4));
38추가: painter.rect_stroke(r, 2.0, stroke, egui::StrokeKind::Middle);
39추가: }
40추가: Icon::Disconnect => power(painter, c, s, stroke),
41추가: }
42추가: }
43추가:
44추가: fn gear(painter: &Painter, c: Pos2, s: f32, stroke: Stroke) {
45추가: let teeth = 8;
46추가: let (outer, inner) = (s, s * 0.72);
47추가: let mut pts = Vec::with_capacity(teeth * 4);
48추가: for i in 0..teeth {
49추가: let a = i as f32 / teeth as f32 * TAU;
50추가: let step = TAU / teeth as f32;
51추가: for (frac, r) in [(0.0, inner), (0.15, outer), (0.45, outer), (0.6, inner)] {
52추가: let t = a + step * frac;
53추가: pts.push(c + vec2(t.cos(), t.sin()) * r);
54추가: }
55추가: }
56추가: painter.add(Shape::closed_line(pts, stroke));
57추가: painter.circle_stroke(c, s * 0.3, stroke);
58추가: }
59추가:
60추가: fn camera(painter: &Painter, c: Pos2, s: f32, stroke: Stroke) {
61추가: let body = Rect::from_center_size(c + vec2(0.0, s * 0.15), vec2(s * 2.0, s * 1.4));
62추가: painter.rect_stroke(body, 2.5, stroke, egui::StrokeKind::Middle);
63추가: let bump = vec![
64추가: pos2(c.x - s * 0.45, body.min.y),
65추가: pos2(c.x - s * 0.3, body.min.y - s * 0.35),
66추가: pos2(c.x + s * 0.3, body.min.y - s * 0.35),
67추가: pos2(c.x + s * 0.45, body.min.y),
68추가: ];
69추가: painter.add(Shape::line(bump, stroke));
70추가: painter.circle_stroke(body.center(), s * 0.42, stroke);
71추가: }
72추가:
73추가: fn power(painter: &Painter, c: Pos2, s: f32, stroke: Stroke) {
74추가: // 위쪽이 열린 원호와 세로선.
75추가: let r = s * 0.78;
76추가: let gap = 0.9; // 라디안, 위쪽 열린 각도의 절반
77추가: let start = -TAU / 4.0 + gap;
78추가: let end = -TAU / 4.0 + TAU - gap;
79추가: let n = 24;
80추가: let pts: Vec<Pos2> = (0..=n)
81추가: .map(|i| {
82추가: let t = start + (end - start) * i as f32 / n as f32;
83추가: c + vec2(t.cos(), t.sin()) * r
84추가: })
85추가: .collect();
86추가: painter.add(Shape::line(pts, stroke));
87추가: painter.line_segment([c + vec2(0.0, -s), c + vec2(0.0, -s * 0.1)], stroke);
88추가: }
추가src/ui/interaction_tests.rs+172-0
@@ -0,0 +1,172 @@
1추가: //! 마우스 조작 시뮬레이션: 아이콘 클릭과 빈 공간 드래그(창 이동)가 서로 가로채지 않는지 확인한다.
2추가:
3추가: use egui::{Pos2, Rect, pos2, vec2};
4추가: use egui_kittest::Harness;
5추가: use wayland_android_remote::protocol::{AuthGrant, SystemAction};
6추가:
7추가: use super::conn::ConnEvent;
8추가: use super::layout;
9추가: use super::view::{Actions, View};
10추가:
11추가: #[derive(Default)]
12추가: struct Recorded {
13추가: screen: Option<Rect>,
14추가: drag: bool,
15추가: open_settings: bool,
16추가: system: Option<SystemAction>,
17추가: }
18추가:
19추가: struct State {
20추가: view: View,
21추가: rec: Recorded,
22추가: }
23추가:
24추가: fn harness(connected: bool) -> Harness<'static, State> {
25추가: let mut view = View::for_test();
26추가: if connected {
27추가: view.start_connecting_for_test("10.0.0.2:27200".parse().unwrap());
28추가: view.on_conn_event(ConnEvent::Connected {
29추가: grant: AuthGrant::Always,
30추가: });
31추가: }
32추가: let size = view.window_size();
33추가: let state = State {
34추가: view,
35추가: rec: Recorded::default(),
36추가: };
37추가: let mut h = Harness::builder()
38추가: .with_size(size)
39추가: .with_accessibility_check(false)
40추가: .with_context_setup(super::fonts::install_korean_font_owned)
41추가: .build_ui_state(
42추가: |ui, s: &mut State| {
43추가: s.rec.screen = Some(ui.max_rect());
44추가: let mut a = Actions::default();
45추가: s.view.ui(ui, &mut a);
46추가: s.rec.drag |= a.start_drag;
47추가: s.rec.open_settings |= a.open_settings;
48추가: s.rec.system = s.rec.system.or(a.system_action);
49추가: },
50추가: state,
51추가: );
52추가: h.run();
53추가: h
54추가: }
55추가:
56추가: fn layout_of(h: &Harness<'_, State>) -> layout::Layout {
57추가: layout::compute(h.state().rec.screen.unwrap())
58추가: }
59추가:
60추가: fn click(h: &mut Harness<'_, State>, p: Pos2) {
61추가: // 누르고 바로 떼는 짧은 클릭. run()은 여러 프레임을 돌려 길게 누른 것처럼 될 수 있어 step()을 쓴다.
62추가: h.hover_at(p);
63추가: h.step();
64추가: h.drag_at(p);
65추가: h.step();
66추가: h.drop_at(p);
67추가: h.step();
68추가: }
69추가:
70추가: fn drag(h: &mut Harness<'_, State>, from: Pos2) {
71추가: h.hover_at(from);
72추가: h.drag_at(from);
73추가: h.run();
74추가: h.hover_at(from + vec2(25.0, 25.0));
75추가: h.run();
76추가: h.drop_at(from + vec2(25.0, 25.0));
77추가: h.run();
78추가: }
79추가:
80추가: #[test]
81추가: fn clicking_settings_icon_opens_settings_without_moving_window() {
82추가: let mut h = harness(false);
83추가: let l = layout_of(&h);
84추가: click(&mut h, layout::rail_slot(l.rail, 0, false).center());
85추가: assert!(h.state().rec.open_settings);
86추가: assert!(!h.state().rec.drag);
87추가: }
88추가:
89추가: #[test]
90추가: fn dragging_empty_rail_moves_window() {
91추가: let mut h = harness(false);
92추가: let l = layout_of(&h);
93추가: drag(&mut h, pos2(l.rail.center().x, l.rail.center().y));
94추가: assert!(h.state().rec.drag);
95추가: assert!(!h.state().rec.open_settings);
96추가: }
97추가:
98추가: #[test]
99추가: fn dragging_empty_nav_bar_moves_window() {
100추가: let mut h = harness(true);
101추가: let l = layout_of(&h);
102추가: drag(&mut h, pos2(l.nav_bar.min.x + 8.0, l.nav_bar.center().y));
103추가: assert!(h.state().rec.drag);
104추가: assert_eq!(h.state().rec.system, None);
105추가: }
106추가:
107추가: #[test]
108추가: fn clicking_nav_button_sends_system_action() {
109추가: let mut h = harness(true);
110추가: let l = layout_of(&h);
111추가: let [back, home, _recents] = layout::nav_slots(l.nav_bar);
112추가: click(&mut h, back.center());
113추가: assert_eq!(h.state().rec.system, Some(SystemAction::Back));
114추가: assert!(!h.state().rec.drag);
115추가:
116추가: let mut h = harness(true);
117추가: click(&mut h, home.center());
118추가: assert_eq!(h.state().rec.system, Some(SystemAction::Home));
119추가: }
120추가:
121추가: #[test]
122추가: fn dragging_title_bar_still_moves_window() {
123추가: let mut h = harness(false);
124추가: let l = layout_of(&h);
125추가: drag(&mut h, l.title_bar.left_center() + vec2(40.0, 0.0));
126추가: assert!(h.state().rec.drag);
127추가: }
128추가:
129추가: fn side_button(h: &mut Harness<'_, State>, p: Pos2, button: egui::PointerButton) {
130추가: h.hover_at(p);
131추가: h.step();
132추가: for pressed in [true, false] {
133추가: h.event(egui::Event::PointerButton {
134추가: pos: p,
135추가: button,
136추가: pressed,
137추가: modifiers: egui::Modifiers::NONE,
138추가: });
139추가: h.step();
140추가: }
141추가: }
142추가:
143추가: #[test]
144추가: fn mouse_back_side_button_sends_back_when_connected() {
145추가: let mut h = harness(true);
146추가: let l = layout_of(&h);
147추가: side_button(&mut h, l.viewport.center(), egui::PointerButton::Extra1);
148추가: assert_eq!(h.state().rec.system, Some(SystemAction::Back));
149추가: assert!(!h.state().rec.drag);
150추가: }
151추가:
152추가: #[test]
153추가: fn other_mouse_buttons_send_nothing() {
154추가: let mut h = harness(true);
155추가: let l = layout_of(&h);
156추가: for button in [
157추가: egui::PointerButton::Secondary,
158추가: egui::PointerButton::Middle,
159추가: egui::PointerButton::Extra2,
160추가: ] {
161추가: side_button(&mut h, l.viewport.center(), button);
162추가: }
163추가: assert_eq!(h.state().rec.system, None);
164추가: }
165추가:
166추가: #[test]
167추가: fn mouse_back_side_button_ignored_when_disconnected() {
168추가: let mut h = harness(false);
169추가: let l = layout_of(&h);
170추가: side_button(&mut h, l.viewport.center(), egui::PointerButton::Extra1);
171추가: assert_eq!(h.state().rec.system, None);
172추가: }
수정src/ui/layout.rs+71-42
@@ -1,79 +1,108 @@
1삭제: //! 창 각 영역의 크기와 위치 (기획서 4.1 ~ 4.3). 단위는 논리 픽셀.
1추가: //! 창 각 영역의 크기와 위치. 단위는 논리 픽셀.
2추가: //!
3추가: //! 창 = [제목 표시줄] 아래에 [왼쪽 아이콘 열][휴대폰 화면 + 그 아래 내비게이션 줄].
4추가: //! 창 크기는 고정이고 설정 등은 별도 창으로 띄우므로 휴대폰 화면은 움직이지 않는다.
25
36use egui::{Rect, Vec2, pos2, vec2};
47
5삭제: /// 왼쪽 풀-하이트 토글 버튼 너비.
6삭제: pub const TOGGLE_W: f32 = 14.0;
7삭제: /// 펼쳤을 때 사이드 메뉴 너비.
8삭제: pub const PANEL_W: f32 = 232.0;
8추가: /// 왼쪽 세로 아이콘 열 너비.
9추가: pub const RAIL_W: f32 = 40.0;
10추가: /// 아이콘 버튼 한 칸 높이.
11추가: pub const RAIL_ITEM_H: f32 = 40.0;
912/// 얇은 상단 제목 표시줄 높이.
1013pub const TITLE_H: f32 = 22.0;
11삭제: /// 뷰포트를 감싸는 검은 테두리 두께.
14추가: /// 휴대폰 화면 아래 내비게이션 줄(뒤로·홈·최근 앱) 높이.
15추가: pub const NAV_H: f32 = 40.0;
16추가: /// 내비게이션 버튼 사이 간격(가운데 기준).
17추가: pub const NAV_SPACING: f32 = 72.0;
18추가: /// 휴대폰 화면을 감싸는 검은 테두리 두께.
1219pub const BORDER: f32 = 4.0;
13삭제: /// 연결 전 기본 뷰포트 크기. Galaxy S21+ 화면 비율(1080x2400, 9:20)에 맞춘다.
20추가: /// 연결 전 기본 화면 크기. Galaxy S21+ 화면 비율(1080x2400, 9:20)에 맞춘다.
1421pub const DEFAULT_VIEWPORT: Vec2 = vec2(360.0, 800.0);
1522
1623/// 한 프레임의 영역 배치.
1724#[derive(Debug, Clone, Copy)]
1825pub struct Layout {
19삭제: pub toggle: Rect,
20삭제: pub panel: Option<Rect>,
2126 pub title_bar: Rect,
27추가: pub rail: Rect,
2228 pub viewport: Rect,
29추가: pub nav_bar: Rect,
2330}
2431
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추가: pub fn window_size(viewport: Vec2) -> Vec2 {
34추가: vec2(RAIL_W + viewport.x + BORDER, TITLE_H + viewport.y + NAV_H)
3235}
3336
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));
37추가: pub fn compute(screen: Rect) -> Layout {
38추가: let title_bar = Rect::from_min_max(screen.min, pos2(screen.max.x, screen.min.y + TITLE_H));
39추가: let rail = Rect::from_min_max(
40추가: pos2(screen.min.x, title_bar.max.y),
41추가: pos2(screen.min.x + RAIL_W, screen.max.y),
42추가: );
4643 let viewport = Rect::from_min_max(
47삭제: pos2(x + BORDER, title_bar.max.y),
48삭제: pos2(screen.max.x - BORDER, screen.max.y - BORDER),
44추가: pos2(rail.max.x, title_bar.max.y),
45추가: pos2(screen.max.x - BORDER, screen.max.y - NAV_H),
46추가: );
47추가: let nav_bar = Rect::from_min_max(
48추가: pos2(viewport.min.x, viewport.max.y),
49추가: pos2(viewport.max.x, screen.max.y),
4950 );
50삭제:
5151 Layout {
52삭제: toggle,
53삭제: panel,
5452 title_bar,
53추가: rail,
5554 viewport,
55추가: nav_bar,
5656 }
5757}
5858
59추가: /// 내비게이션 줄의 버튼 3칸(뒤로·홈·최근 앱). 휴대폰 화면 가운데를 기준으로 배치한다.
60추가: pub fn nav_slots(nav_bar: Rect) -> [Rect; 3] {
61추가: let size = vec2(NAV_SPACING * 0.8, nav_bar.height());
62추가: let c = nav_bar.center();
63추가: [-NAV_SPACING, 0.0, NAV_SPACING].map(|dx| Rect::from_center_size(c + vec2(dx, 0.0), size))
64추가: }
65추가:
66추가: /// 아이콘 열의 `index`번째 칸. `from_bottom`이면 아래에서부터 센다.
67추가: pub fn rail_slot(rail: Rect, index: usize, from_bottom: bool) -> Rect {
68추가: let size = vec2(rail.width(), RAIL_ITEM_H);
69추가: let offset = index as f32 * RAIL_ITEM_H;
70추가: let min = if from_bottom {
71추가: pos2(rail.min.x, rail.max.y - offset - RAIL_ITEM_H)
72추가: } else {
73추가: pos2(rail.min.x, rail.min.y + 6.0 + offset)
74추가: };
75추가: Rect::from_min_size(min, size)
76추가: }
77추가:
5978#[cfg(test)]
6079mod tests {
6180 use super::*;
6281
6382 #[test]
6483 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);
84추가: let size = window_size(DEFAULT_VIEWPORT);
85추가: let layout = compute(Rect::from_min_size(pos2(0.0, 0.0), size));
86추가: assert_eq!(layout.viewport.size(), DEFAULT_VIEWPORT);
87추가: assert_eq!(layout.rail.width(), RAIL_W);
88추가: assert!(layout.rail.max.x <= layout.viewport.min.x);
89추가: assert_eq!(layout.nav_bar.height(), NAV_H);
90추가: assert_eq!(layout.nav_bar.min.y, layout.viewport.max.y);
91추가: assert_eq!(layout.nav_bar.center().x, layout.viewport.center().x);
92추가: for slot in nav_slots(layout.nav_bar) {
93추가: assert!(layout.nav_bar.contains_rect(slot));
7094 }
7195 }
7296
7397 #[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));
98추가: fn rail_slots_stay_inside_rail() {
99추가: let layout = compute(Rect::from_min_size(
100추가: pos2(0.0, 0.0),
101추가: window_size(DEFAULT_VIEWPORT),
102추가: ));
103추가: for i in 0..5 {
104추가: assert!(layout.rail.contains_rect(rail_slot(layout.rail, i, false)));
105추가: assert!(layout.rail.contains_rect(rail_slot(layout.rail, i, true)));
106추가: }
78107 }
79108}
수정src/ui/mod.rs+247-103
@@ -1,9 +1,18 @@
1삭제: //! 호스트 GUI. winit 창 위에 wgpu로 직접 그리고, 설정·입력 UI는 egui로 같은 렌더 패스에 얹는다.
1추가: //! 호스트 GUI. winit 창 위에 wgpu로 직접 그리고, 입력·설정 UI는 egui로 같은 렌더 패스에 얹는다.
22//! 영상은 이후 같은 wgpu 디바이스에 텍스처로 올려 그린다.
3추가: //!
4추가: //! 창은 두 종류다. 크기가 고정된 메인 창(휴대폰 화면)과, 아이콘 열의 버튼으로 여는 독립 설정 창.
5추가: //! 두 창은 wgpu 디바이스를 공유하고 egui 컨텍스트는 따로 쓴다.
36
7추가: mod conn;
48mod fonts;
9추가: mod icons;
10추가: #[cfg(test)]
11추가: mod interaction_tests;
512mod layout;
613mod recent;
14추가: #[cfg(test)]
15추가: mod snapshots;
716mod view;
817
918use std::num::NonZeroU32;
@@ -12,116 +21,121 @@ use std::time::{Duration, Instant};
1221
1322use egui::ViewportId;
1423use egui_wgpu::winit::Painter;
15삭제: use egui_wgpu::{RendererOptions, SurfaceConfig, WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew};
24추가: use egui_wgpu::{
25추가: RendererOptions, SurfaceConfig, WgpuConfiguration, WgpuSetup, WgpuSetupCreateNew,
26추가: WgpuSetupExisting,
27추가: };
1628use egui_winit::winit;
1729use winit::application::ApplicationHandler;
18삭제: use winit::dpi::{LogicalSize, PhysicalPosition};
30추가: use winit::dpi::LogicalSize;
1931use winit::event::WindowEvent;
2032use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
21삭제: use winit::window::{Window, WindowId};
33추가: use winit::window::{Window, WindowAttributes, WindowId};
2234
35추가: use conn::{ConnCommand, ConnHandle, Connector, video_request};
2336use view::{Actions, View};
2437
38추가: /// 네트워크 스레드가 UI를 깨울 때 보내는 이벤트.
39추가: #[derive(Debug, Clone, Copy)]
40추가: struct Wake;
41추가:
2542/// 이벤트 루프를 만들고 창이 닫힐 때까지 실행한다.
2643pub fn run() -> Result<(), Box<dyn std::error::Error>> {
27삭제: let event_loop = EventLoop::new()?;
28삭제: let mut app = App::new();
44추가: let event_loop = EventLoop::<Wake>::with_user_event().build()?;
45추가: let proxy = event_loop.create_proxy();
46추가: let connector = Connector::new(Arc::new(move || {
47추가: let _ = proxy.send_event(Wake);
48추가: }))?;
49추가: let mut app = App::new(connector);
2950 event_loop.run_app(&mut app)?;
3051 Ok(())
3152}
3253
54추가: #[derive(Debug, Clone, Copy, PartialEq, Eq)]
55추가: enum Kind {
56추가: Main,
57추가: Settings,
58추가: }
59추가:
60추가: /// 창 하나에 딸린 그리기 상태.
3361struct Gfx {
3462 window: Arc<Window>,
63추가: ctx: egui::Context,
3564 painter: Painter,
3665 egui_winit: egui_winit::State,
37삭제: }
38삭제:
39삭제: struct App {
40삭제: ctx: egui::Context,
41삭제: view: View,
42삭제: gfx: Option<Gfx>,
4366 next_repaint: Option<Instant>,
4467}
4568
46삭제: impl App {
47삭제: fn new() -> Self {
69추가: impl Gfx {
70추가: fn new(
71추가: event_loop: &ActiveEventLoop,
72추가: attrs: WindowAttributes,
73추가: setup: WgpuSetup,
74추가: ) -> Result<Self, Box<dyn std::error::Error>> {
75추가: let window = Arc::new(event_loop.create_window(attrs)?);
4876 let ctx = egui::Context::default();
4977 ctx.set_visuals(egui::Visuals::dark());
5078 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)?);
6779
68삭제: let mut setup = WgpuSetupCreateNew::from_display_handle(event_loop.owned_display_handle());
69삭제: setup.power_preference = egui_wgpu::wgpu::PowerPreference::HighPerformance;
7080 let config = WgpuConfiguration {
7181 // 프레임 큐를 1장으로 제한해 입력에서 화면까지의 지연을 줄인다.
7282 surface: SurfaceConfig::LOW_LATENCY,
73삭제: wgpu_setup: WgpuSetup::CreateNew(setup),
83추가: wgpu_setup: setup,
7484 ..Default::default()
7585 };
7686 let mut painter = pollster::block_on(Painter::new(
77삭제: self.ctx.clone(),
87추가: ctx.clone(),
7888 config,
7989 false,
8090 RendererOptions::default(),
8191 ));
8292 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삭제: }
8793
8894 let egui_winit = egui_winit::State::new(
89삭제: self.ctx.clone(),
95추가: ctx.clone(),
9096 ViewportId::ROOT,
9197 event_loop,
9298 Some(window.scale_factor() as f32),
9399 window.theme(),
94100 painter.max_texture_side(),
95101 );
96삭제:
97삭제: Ok(Gfx {
102추가: window.request_redraw();
103추가: Ok(Self {
98104 window,
105추가: ctx,
99106 painter,
100107 egui_winit,
108추가: next_repaint: None,
101109 })
102110 }
103111
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추가: /// 같은 wgpu 디바이스로 새 창을 그리도록 설정을 복제한다.
113추가: fn shared_setup(&self) -> Option<WgpuSetup> {
114추가: let rs = self.painter.render_state()?;
115추가: Some(WgpuSetup::Existing(WgpuSetupExisting {
116추가: instance: rs.instance.clone(),
117추가: adapter: rs.adapter.clone(),
118추가: device: rs.device.clone(),
119추가: queue: rs.queue.clone(),
120추가: }))
121추가: }
112122
113삭제: gfx.egui_winit
114삭제: .handle_platform_output(&gfx.window, output.platform_output);
123추가: /// egui 한 프레임을 실행하고 그린다.
124추가: fn frame(&mut self, mut ui_fn: impl FnMut(&mut egui::Ui)) {
125추가: let raw_input = self.egui_winit.take_egui_input(&self.window);
126추가: let output = self.ctx.run_ui(raw_input, |ui| ui_fn(ui));
127추가: self.egui_winit
128추가: .handle_platform_output(&self.window, output.platform_output);
115129 let primitives = self.ctx.tessellate(output.shapes, output.pixels_per_point);
116130 let mut textures = output.textures_delta;
117삭제: gfx.painter.paint_and_update_textures(
131추가: self.painter.paint_and_update_textures(
118132 ViewportId::ROOT,
119133 output.pixels_per_point,
120134 [0.0, 0.0, 0.0, 1.0],
121135 &primitives,
122136 &mut textures,
123137 Vec::new(),
124삭제: &gfx.window,
138추가: &self.window,
125139 );
126140
127141 let delay = output
@@ -129,54 +143,175 @@ impl App {
129143 .get(&ViewportId::ROOT)
130144 .map_or(Duration::MAX, |v| v.repaint_delay);
131145 if delay.is_zero() {
132삭제: gfx.window.request_redraw();
146추가: self.window.request_redraw();
133147 } else {
134148 self.next_repaint = Instant::now().checked_add(delay);
135149 }
150추가: }
151추가: }
152추가:
153추가: struct App {
154추가: view: View,
155추가: main: Option<Gfx>,
156추가: settings: Option<Gfx>,
157추가: connector: Connector,
158추가: conn: Option<ConnHandle>,
159추가: }
160추가:
161추가: impl App {
162추가: fn new(connector: Connector) -> Self {
163추가: Self {
164추가: view: View::new(),
165추가: main: None,
166추가: settings: None,
167추가: connector,
168추가: conn: None,
169추가: }
170추가: }
171추가:
172추가: fn init_main(&self, event_loop: &ActiveEventLoop) -> Result<Gfx, Box<dyn std::error::Error>> {
173추가: let size = self.view.window_size();
174추가: let attrs = Window::default_attributes()
175추가: .with_title("Android Remote")
176추가: .with_decorations(false)
177추가: .with_resizable(false)
178추가: .with_inner_size(LogicalSize::new(size.x, size.y));
179추가: let mut setup = WgpuSetupCreateNew::from_display_handle(event_loop.owned_display_handle());
180추가: setup.power_preference = egui_wgpu::wgpu::PowerPreference::HighPerformance;
181추가: let gfx = Gfx::new(event_loop, attrs, WgpuSetup::CreateNew(setup))?;
182추가: if let Some(rs) = gfx.painter.render_state() {
183추가: let info = rs.adapter.get_info();
184추가: log::info!("GPU: {} ({:?})", info.name, info.backend);
185추가: }
186추가: Ok(gfx)
187추가: }
188추가:
189추가: fn open_settings(&mut self, event_loop: &ActiveEventLoop) {
190추가: if let Some(s) = &self.settings {
191추가: s.window.focus_window();
192추가: return;
193추가: }
194추가: let Some(setup) = self.main.as_ref().and_then(Gfx::shared_setup) else {
195추가: return;
196추가: };
197추가: let attrs = Window::default_attributes()
198추가: .with_title("Android Remote 설정")
199추가: .with_inner_size(LogicalSize::new(320.0, 380.0))
200추가: .with_min_inner_size(LogicalSize::new(280.0, 300.0));
201추가: match Gfx::new(event_loop, attrs, setup) {
202추가: Ok(gfx) => self.settings = Some(gfx),
203추가: Err(e) => log::error!("설정 창을 열지 못했습니다: {e}"),
204추가: }
205추가: }
136206
207추가: fn kind_of(&self, id: WindowId) -> Option<Kind> {
208추가: if self.main.as_ref().is_some_and(|g| g.window.id() == id) {
209추가: Some(Kind::Main)
210추가: } else if self.settings.as_ref().is_some_and(|g| g.window.id() == id) {
211추가: Some(Kind::Settings)
212추가: } else {
213추가: None
214추가: }
215추가: }
216추가:
217추가: fn drain_conn_events(&mut self) {
218추가: let Some(conn) = &self.conn else { return };
219추가: while let Ok(event) = conn.events.try_recv() {
220추가: let ended = matches!(event, conn::ConnEvent::Ended(_));
221추가: self.view.on_conn_event(event);
222추가: if ended {
223추가: self.conn = None;
224추가: break;
225추가: }
226추가: }
227추가: }
228추가:
229추가: fn redraw(&mut self, kind: Kind, event_loop: &ActiveEventLoop) {
230추가: self.drain_conn_events();
231추가: let mut actions = Actions::default();
232추가: let view = &mut self.view;
233추가: match kind {
234추가: Kind::Main => {
235추가: if let Some(gfx) = self.main.as_mut() {
236추가: gfx.frame(|ui| view.ui(ui, &mut actions));
237추가: }
238추가: }
239추가: Kind::Settings => {
240추가: if let Some(gfx) = self.settings.as_mut() {
241추가: gfx.frame(|ui| view.settings_ui(ui, &mut actions));
242추가: }
243추가: }
244추가: }
137245 self.apply(actions, event_loop);
138246 }
139247
140248 fn apply(&mut self, actions: Actions, event_loop: &ActiveEventLoop) {
141삭제: let Some(gfx) = &self.gfx else { return };
142삭제: let window = &gfx.window;
143249 if actions.close {
144250 event_loop.exit();
145251 return;
146252 }
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));
253추가: if let Some(main) = &self.main {
254추가: let window = &main.window;
255추가: if actions.start_drag
256추가: && let Err(e) = window.drag_window()
257추가: {
258추가: log::debug!("창 이동 실패: {e}");
259추가: }
260추가: if actions.minimize {
261추가: window.set_minimized(true);
262추가: }
263추가: }
264추가: if actions.open_settings {
265추가: self.open_settings(event_loop);
266추가: }
267추가: if let Some(target) = actions.forget_device {
268추가: self.connector.forget_device(target);
269추가: }
270추가: if actions.disconnect {
271추가: self.conn = None;
272추가: self.view.reset_to_disconnected();
273추가: self.request_redraw_all();
274추가: }
275추가: if let Some(target) = actions.connect {
276추가: let s = self.view.settings();
277추가: let req = video_request(s.max_size, s.max_fps, s.bitrate_mbps);
278추가: self.conn = Some(self.connector.start(target, req));
279추가: self.request_redraw_all();
280추가: }
281추가: if let Some(conn) = &self.conn {
282추가: if let Some(action) = actions.system_action {
283추가: conn.send(ConnCommand::System(action));
163284 }
164삭제: let _ = window.request_inner_size(LogicalSize::new(size.x, size.y));
165삭제: window.request_redraw();
285추가: if actions.video_settings_changed {
286추가: let s = self.view.settings();
287추가: conn.send(ConnCommand::RequestVideo(video_request(
288추가: s.max_size,
289추가: s.max_fps,
290추가: s.bitrate_mbps,
291추가: )));
292추가: }
293추가: }
294추가: }
295추가:
296추가: fn request_redraw_all(&self) {
297추가: for gfx in [&self.main, &self.settings].into_iter().flatten() {
298추가: gfx.window.request_redraw();
166299 }
167300 }
168301}
169302
170삭제: impl ApplicationHandler for App {
303추가: impl ApplicationHandler<Wake> for App {
304추가: fn user_event(&mut self, _event_loop: &ActiveEventLoop, _event: Wake) {
305추가: // 연결 상태는 두 창 모두에 영향을 준다 (아이콘 활성화, 설정 안내 문구).
306추가: self.request_redraw_all();
307추가: }
308추가:
171309 fn resumed(&mut self, event_loop: &ActiveEventLoop) {
172삭제: if self.gfx.is_some() {
310추가: if self.main.is_some() {
173311 return;
174312 }
175삭제: match self.init_gfx(event_loop) {
176삭제: Ok(gfx) => {
177삭제: gfx.window.request_redraw();
178삭제: self.gfx = Some(gfx);
179삭제: }
313추가: match self.init_main(event_loop) {
314추가: Ok(gfx) => self.main = Some(gfx),
180315 Err(e) => {
181316 log::error!("창 또는 GPU 초기화 실패: {e}");
182317 event_loop.exit();
@@ -184,47 +319,56 @@ impl ApplicationHandler for App {
184319 }
185320 }
186321
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);
322추가: fn window_event(&mut self, event_loop: &ActiveEventLoop, id: WindowId, event: WindowEvent) {
323추가: let Some(kind) = self.kind_of(id) else { return };
192324
193삭제: match event {
325추가: match &event {
194326 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);
327추가: match kind {
328추가: Kind::Main => event_loop.exit(),
329추가: Kind::Settings => self.settings = None,
203330 }
331추가: return;
204332 }
205333 WindowEvent::RedrawRequested => {
206삭제: self.redraw(event_loop);
334추가: self.redraw(kind, event_loop);
207335 return;
208336 }
209337 _ => {}
210338 }
211339
340추가: let gfx = match kind {
341추가: Kind::Main => self.main.as_mut(),
342추가: Kind::Settings => self.settings.as_mut(),
343추가: };
344추가: let Some(gfx) = gfx else { return };
345추가: let response = gfx.egui_winit.on_window_event(&gfx.window, &event);
346추가: if let WindowEvent::Resized(size) = event
347추가: && let (Some(w), Some(h)) = (NonZeroU32::new(size.width), NonZeroU32::new(size.height))
348추가: {
349추가: gfx.painter.on_window_resized(ViewportId::ROOT, w, h);
350추가: }
212351 if response.repaint {
213352 gfx.window.request_redraw();
214353 }
215354 }
216355
217356 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 {
357추가: let now = Instant::now();
358추가: let mut next: Option<Instant> = None;
359추가: for gfx in [&mut self.main, &mut self.settings].into_iter().flatten() {
360추가: match gfx.next_repaint {
361추가: Some(at) if at <= now => {
362추가: gfx.next_repaint = None;
222363 gfx.window.request_redraw();
223364 }
224삭제: event_loop.set_control_flow(ControlFlow::Wait);
365추가: Some(at) => next = Some(next.map_or(at, |n| n.min(at))),
366추가: None => {}
225367 }
226삭제: Some(at) => event_loop.set_control_flow(ControlFlow::WaitUntil(at)),
227삭제: None => event_loop.set_control_flow(ControlFlow::Wait),
228368 }
369추가: event_loop.set_control_flow(match next {
370추가: Some(at) => ControlFlow::WaitUntil(at),
371추가: None => ControlFlow::Wait,
372추가: });
229373 }
230374}
수정src/ui/recent.rs+8-10
@@ -5,6 +5,8 @@ use std::io;
55use std::net::{IpAddr, SocketAddr};
66use std::path::PathBuf;
77
8추가: use wayland_android_remote::config::config_dir;
9추가:
810/// 데몬 기본 포트 (기획서 5.4).
911pub const DEFAULT_PORT: u16 = 27200;
1012/// 최근 접속 기록 최대 개수.
@@ -56,12 +58,17 @@ impl RecentTargets {
5658 Self { items, path }
5759 }
5860
61추가: /// 파일에 저장하지 않는 빈 목록 (테스트용).
62추가: #[cfg(test)]
63추가: pub fn in_memory() -> Self {
64추가: Self::default()
65추가: }
66추가:
5967 pub fn items(&self) -> &[String] {
6068 &self.items
6169 }
6270
6371 /// 접속 성공한 주소를 맨 앞에 넣고 파일에 저장한다.
64삭제: #[expect(dead_code, reason = "AUTH_RESULT(OK) 수신 처리를 구현할 때 호출한다")]
6572 pub fn record(&mut self, target: &str) -> io::Result<()> {
6673 push_front_dedup(&mut self.items, target);
6774 let Some(path) = &self.path else {
@@ -91,15 +98,6 @@ fn push_front_dedup(items: &mut Vec<String>, target: &str) {
9198 items.truncate(MAX_RECENT);
9299}
93100
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삭제:
103101#[cfg(test)]
104102mod tests {
105103 use super::*;
추가src/ui/snapshots.rs+75-0
@@ -0,0 +1,75 @@
1추가: //! 화면을 GPU로 오프스크린 렌더링해 PNG로 저장한다. 눈으로 확인하는 용도라 기본 실행에서 제외한다.
2추가: //!
3추가: //! `cargo test --bin android-remote snapshots -- --ignored` 후 `target/ui-snapshots/*.png` 확인.
4추가:
5추가: use std::path::PathBuf;
6추가:
7추가: use egui_kittest::Harness;
8추가: use wayland_android_remote::protocol::{AuthGrant, VideoCodec, VideoConfig};
9추가:
10추가: use super::conn::ConnEvent;
11추가: use super::fonts;
12추가: use super::view::{Actions, View};
13추가:
14추가: fn out_dir() -> PathBuf {
15추가: let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/ui-snapshots");
16추가: std::fs::create_dir_all(&dir).unwrap();
17추가: dir
18추가: }
19추가:
20추가: fn render(name: &str, size: egui::Vec2, mut draw: impl FnMut(&mut egui::Ui)) {
21추가: let mut harness = Harness::builder()
22추가: .with_size(size)
23추가: .with_accessibility_check(false)
24추가: .with_context_setup(|ctx| {
25추가: ctx.set_visuals(egui::Visuals::dark());
26추가: fonts::install_korean_font(ctx);
27추가: })
28추가: .wgpu()
29추가: .build_ui(|ui| draw(ui));
30추가: harness.run();
31추가: let image = harness.render().expect("렌더링 실패");
32추가: image.save(out_dir().join(format!("{name}.png"))).unwrap();
33추가: }
34추가:
35추가: #[test]
36추가: #[ignore = "GPU가 필요한 시각 확인용"]
37추가: fn snapshots() {
38추가: let mut view = View::for_test();
39추가: let size = view.window_size();
40추가:
41추가: render("main_disconnected", size, |ui| {
42추가: view.ui(ui, &mut Actions::default())
43추가: });
44추가:
45추가: let target = "192.168.0.12:27200".parse().unwrap();
46추가: view.start_connecting_for_test(target);
47추가: view.on_conn_event(ConnEvent::AwaitingApproval {
48추가: confirm_code: "300698".to_owned(),
49추가: });
50추가: render("main_awaiting_approval", size, |ui| {
51추가: view.ui(ui, &mut Actions::default())
52추가: });
53추가:
54추가: view.on_conn_event(ConnEvent::Connected {
55추가: grant: AuthGrant::Always,
56추가: });
57추가: view.on_conn_event(ConnEvent::VideoConfig(VideoConfig {
58추가: codec: VideoCodec::H265,
59추가: config_gen: 1,
60추가: width: 864,
61추가: height: 1920,
62추가: fps: 60,
63추가: bitrate: 8_000_000,
64추가: display_width: 1080,
65추가: display_height: 2400,
66추가: }));
67추가: view.on_conn_event(ConnEvent::VideoFrames(120));
68추가: render("main_connected", size, |ui| {
69추가: view.ui(ui, &mut Actions::default())
70추가: });
71추가:
72추가: render("settings_window", egui::vec2(320.0, 380.0), |ui| {
73추가: view.settings_ui(ui, &mut Actions::default())
74추가: });
75추가: }
수정src/ui/view.rs

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

Raw로 열기
추가tests/common/fake_device.rs

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

Raw로 열기
추가tests/common/mod.rs

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

Raw로 열기
추가tests/connect.rs

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

Raw로 열기
추가tests/fake_device_smoke.rs

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

Raw로 열기