leejunyoung5819wayland-android-remote

공개

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

317줄10 KB
1//! 화면 그리기와 사용자 조작 처리 (기획서 4절). 창 조작은 [`Actions`]로 돌려주고
2//! 실제 winit 호출은 상위 [`super::App`]에서 한다.
3
4use std::net::SocketAddr;
5
6use egui::{
7 Align2, Button, Color32, FontId, Key, Rect, RichText, Sense, TextEdit, Ui, UiBuilder, Vec2,
8 pos2, vec2,
9};
10
11use super::layout::{self, DEFAULT_VIEWPORT, Layout};
12use super::recent::{RecentTargets, display_target, parse_target};
13
14const FRAME_COLOR: Color32 = Color32::BLACK;
15const PANEL_BG: Color32 = Color32::from_rgb(0x14, 0x14, 0x14);
16const DIM_TEXT: Color32 = Color32::from_rgb(0x8a, 0x8a, 0x8a);
17const INPUT_BG: Color32 = Color32::from_rgb(0x1c, 0x1c, 0x1c);
18const ERROR_TEXT: Color32 = Color32::from_rgb(0xe0, 0x6c, 0x6c);
19
20/// 한 프레임 동안 UI가 요청한 창 동작.
21#[derive(Debug, Default)]
22pub 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)]
31enum Connection {
32 /// 검은 화면과 IP 입력창 (기획서 4.4).
33 Disconnected,
34 /// 휴대폰 승인 대기. 네트워크 연결은 아직 구현 전이다.
35 Connecting { target: SocketAddr },
36}
37
38/// 사이드 메뉴 설정값 (기획서 4.3). 아직 기기로 전송하지는 않는다.
39#[derive(Debug, Clone)]
40struct 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
48impl 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
60pub 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
71impl 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
273fn 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
292fn 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
311fn size_label(v: u16) -> String {
312 if v == 0 {
313 "원본".to_owned()
314 } else {
315 format!("{v}p")
316 }
317}