leejunyoung5819 wayland-android-remote
공개Ubuntu(Wayland/X11)에서 Android 기기 화면 미러링 및 원격 제어 (Rust)
| 1 | //! Wayland 파일 끌어다 놓기 수신 (기획서 3.3). winit 0.30은 Wayland에서 드래그 앤 드롭을 지원하지 |
| 2 | //! 않으므로, smithay-clipboard처럼 winit의 Wayland 연결을 함께 쓰는 별도 이벤트 큐와 스레드에서 |
| 3 | //! wl_data_device를 만들어 메인 창 표면에 떨어진 파일 목록(text/uri-list)을 받는다. |
| 4 | //! X11에서는 winit의 `DroppedFile` 이벤트를 쓴다. |
| 5 | |
| 6 | use std::ffi::c_void; |
| 7 | use std::io::Read; |
| 8 | use std::path::PathBuf; |
| 9 | use std::sync::mpsc; |
| 10 | |
| 11 | use sctk::data_device_manager::data_device::{DataDevice, DataDeviceHandler}; |
| 12 | use sctk::data_device_manager::data_offer::{DataOfferHandler, DragOffer}; |
| 13 | use sctk::data_device_manager::data_source::DataSourceHandler; |
| 14 | use sctk::data_device_manager::{DataDeviceManagerState, WritePipe}; |
| 15 | use sctk::reexports::client::backend::Backend; |
| 16 | use sctk::reexports::client::globals::registry_queue_init; |
| 17 | use sctk::reexports::client::protocol::wl_data_device::WlDataDevice; |
| 18 | use sctk::reexports::client::protocol::wl_data_device_manager::DndAction; |
| 19 | use sctk::reexports::client::protocol::wl_data_source::WlDataSource; |
| 20 | use sctk::reexports::client::protocol::wl_seat::WlSeat; |
| 21 | use sctk::reexports::client::protocol::wl_surface::WlSurface; |
| 22 | use sctk::reexports::client::{Connection, Proxy, QueueHandle}; |
| 23 | use sctk::registry::{ProvidesRegistryState, RegistryState}; |
| 24 | use sctk::seat::{Capability, SeatHandler, SeatState}; |
| 25 | use sctk::{delegate_data_device, delegate_registry, delegate_seat, registry_handlers}; |
| 26 | |
| 27 | use super::conn::Waker; |
| 28 | use super::transfer::parse_uri_list; |
| 29 | |
| 30 | const URI_LIST: &str = "text/uri-list"; |
| 31 | |
| 32 | /// 메인 창에 대한 끌어다 놓기 상황. |
| 33 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 34 | pub enum DndEvent { |
| 35 | /// 파일을 창 위로 끌고 들어왔다. |
| 36 | Enter, |
| 37 | /// 놓지 않고 나갔다. |
| 38 | Leave, |
| 39 | /// 놓았다. 로컬 파일 경로들. |
| 40 | Drop(Vec<PathBuf>), |
| 41 | } |
| 42 | |
| 43 | /// 수신 스레드를 띄운다. `display`와 `surface`는 winit 창의 wl_display, wl_surface 포인터다. |
| 44 | /// |
| 45 | /// # Safety |
| 46 | /// 두 포인터는 창이 살아 있는 동안 유효해야 한다 (프로세스가 끝날 때까지 메인 창을 유지한다). |
| 47 | pub unsafe fn spawn( |
| 48 | display: *mut c_void, |
| 49 | surface: *mut c_void, |
| 50 | events: mpsc::Sender<DndEvent>, |
| 51 | waker: Waker, |
| 52 | ) -> std::io::Result<()> { |
| 53 | let backend = unsafe { Backend::from_foreign_display(display.cast()) }; |
| 54 | let conn = Connection::from_backend(backend); |
| 55 | let surface = surface as usize; |
| 56 | std::thread::Builder::new() |
| 57 | .name("android-remote-dnd".into()) |
| 58 | .spawn(move || run(conn, surface, events, waker))?; |
| 59 | Ok(()) |
| 60 | } |
| 61 | |
| 62 | fn run(conn: Connection, surface: usize, events: mpsc::Sender<DndEvent>, waker: Waker) { |
| 63 | let (globals, mut queue) = match registry_queue_init::<State>(&conn) { |
| 64 | Ok(v) => v, |
| 65 | Err(e) => { |
| 66 | log::warn!("끌어다 놓기 초기화 실패: {e}"); |
| 67 | return; |
| 68 | } |
| 69 | }; |
| 70 | let qh = queue.handle(); |
| 71 | let manager = match DataDeviceManagerState::bind(&globals, &qh) { |
| 72 | Ok(m) => m, |
| 73 | Err(e) => { |
| 74 | log::warn!("wl_data_device_manager 없음, 끌어다 놓기를 쓰지 않습니다: {e}"); |
| 75 | return; |
| 76 | } |
| 77 | }; |
| 78 | let mut state = State { |
| 79 | registry: RegistryState::new(&globals), |
| 80 | seats: SeatState::new(&globals, &qh), |
| 81 | manager, |
| 82 | devices: Vec::new(), |
| 83 | surface, |
| 84 | hovering: false, |
| 85 | events, |
| 86 | waker, |
| 87 | conn: conn.clone(), |
| 88 | }; |
| 89 | for seat in state.seats.seats().collect::<Vec<_>>() { |
| 90 | state.add_device(&qh, &seat); |
| 91 | } |
| 92 | log::debug!("끌어다 놓기 수신 준비"); |
| 93 | loop { |
| 94 | if let Err(e) = queue.blocking_dispatch(&mut state) { |
| 95 | log::warn!("끌어다 놓기 이벤트 처리 중단: {e}"); |
| 96 | return; |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | struct State { |
| 102 | registry: RegistryState, |
| 103 | seats: SeatState, |
| 104 | manager: DataDeviceManagerState, |
| 105 | devices: Vec<DataDevice>, |
| 106 | /// 메인 창 wl_surface 포인터. |
| 107 | surface: usize, |
| 108 | hovering: bool, |
| 109 | events: mpsc::Sender<DndEvent>, |
| 110 | waker: Waker, |
| 111 | conn: Connection, |
| 112 | } |
| 113 | |
| 114 | impl State { |
| 115 | fn add_device(&mut self, qh: &QueueHandle<Self>, seat: &WlSeat) { |
| 116 | if self.devices.iter().any(|d| d.data().seat() == seat) { |
| 117 | return; |
| 118 | } |
| 119 | self.devices.push(self.manager.get_data_device(qh, seat)); |
| 120 | } |
| 121 | |
| 122 | fn emit(&self, event: DndEvent) { |
| 123 | if self.events.send(event).is_ok() { |
| 124 | (self.waker)(); |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | fn is_ours(&self, surface: &WlSurface) -> bool { |
| 129 | surface.id().as_ptr() as usize == self.surface |
| 130 | } |
| 131 | |
| 132 | fn offer_of(data_device: &WlDataDevice) -> Option<DragOffer> { |
| 133 | data_device |
| 134 | .data::<sctk::data_device_manager::data_device::DataDeviceData>()? |
| 135 | .drag_offer() |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | impl DataDeviceHandler for State { |
| 140 | fn enter( |
| 141 | &mut self, |
| 142 | _: &Connection, |
| 143 | _: &QueueHandle<Self>, |
| 144 | data_device: &WlDataDevice, |
| 145 | _: f64, |
| 146 | _: f64, |
| 147 | surface: &WlSurface, |
| 148 | ) { |
| 149 | let Some(offer) = Self::offer_of(data_device) else { |
| 150 | return; |
| 151 | }; |
| 152 | let files = |
| 153 | self.is_ours(surface) && offer.with_mime_types(|m| m.iter().any(|t| t == URI_LIST)); |
| 154 | if files { |
| 155 | offer.accept_mime_type(offer.serial, Some(URI_LIST.to_owned())); |
| 156 | offer.set_actions(DndAction::Copy, DndAction::Copy); |
| 157 | self.hovering = true; |
| 158 | self.emit(DndEvent::Enter); |
| 159 | } else { |
| 160 | offer.accept_mime_type(offer.serial, None); |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | fn leave(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataDevice) { |
| 165 | if std::mem::take(&mut self.hovering) { |
| 166 | self.emit(DndEvent::Leave); |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | fn motion(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataDevice, _: f64, _: f64) {} |
| 171 | |
| 172 | fn selection(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataDevice) {} |
| 173 | |
| 174 | fn drop_performed( |
| 175 | &mut self, |
| 176 | _: &Connection, |
| 177 | _: &QueueHandle<Self>, |
| 178 | data_device: &WlDataDevice, |
| 179 | ) { |
| 180 | if !std::mem::take(&mut self.hovering) { |
| 181 | return; |
| 182 | } |
| 183 | let Some(offer) = Self::offer_of(data_device) else { |
| 184 | return; |
| 185 | }; |
| 186 | let mut pipe = match offer.receive(URI_LIST.to_owned()) { |
| 187 | Ok(p) => p, |
| 188 | Err(e) => { |
| 189 | log::warn!("끌어다 놓은 파일 목록을 받지 못했습니다: {e}"); |
| 190 | self.emit(DndEvent::Leave); |
| 191 | return; |
| 192 | } |
| 193 | }; |
| 194 | let _ = self.conn.flush(); |
| 195 | let events = self.events.clone(); |
| 196 | let waker = self.waker.clone(); |
| 197 | let conn = self.conn.clone(); |
| 198 | // 보내는 쪽이 파이프에 다 쓸 때까지 이벤트 큐를 막지 않도록 따로 읽는다. |
| 199 | std::thread::spawn(move || { |
| 200 | let mut text = String::new(); |
| 201 | let read = pipe.read_to_string(&mut text); |
| 202 | offer.finish(); |
| 203 | offer.destroy(); |
| 204 | let _ = conn.flush(); |
| 205 | match read { |
| 206 | Ok(_) => { |
| 207 | let paths = parse_uri_list(&text); |
| 208 | log::info!("끌어다 놓은 파일 {}개", paths.len()); |
| 209 | if events.send(DndEvent::Drop(paths)).is_ok() { |
| 210 | waker(); |
| 211 | } |
| 212 | } |
| 213 | Err(e) => log::warn!("끌어다 놓은 파일 목록 읽기 실패: {e}"), |
| 214 | } |
| 215 | }); |
| 216 | } |
| 217 | } |
| 218 | |
| 219 | impl DataOfferHandler for State { |
| 220 | fn source_actions( |
| 221 | &mut self, |
| 222 | _: &Connection, |
| 223 | _: &QueueHandle<Self>, |
| 224 | _: &mut DragOffer, |
| 225 | _: DndAction, |
| 226 | ) { |
| 227 | } |
| 228 | |
| 229 | fn selected_action( |
| 230 | &mut self, |
| 231 | _: &Connection, |
| 232 | _: &QueueHandle<Self>, |
| 233 | _: &mut DragOffer, |
| 234 | _: DndAction, |
| 235 | ) { |
| 236 | } |
| 237 | } |
| 238 | |
| 239 | impl DataSourceHandler for State { |
| 240 | fn accept_mime( |
| 241 | &mut self, |
| 242 | _: &Connection, |
| 243 | _: &QueueHandle<Self>, |
| 244 | _: &WlDataSource, |
| 245 | _: Option<String>, |
| 246 | ) { |
| 247 | } |
| 248 | |
| 249 | fn send_request( |
| 250 | &mut self, |
| 251 | _: &Connection, |
| 252 | _: &QueueHandle<Self>, |
| 253 | _: &WlDataSource, |
| 254 | _: String, |
| 255 | _: WritePipe, |
| 256 | ) { |
| 257 | } |
| 258 | |
| 259 | fn cancelled(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataSource) {} |
| 260 | |
| 261 | fn dnd_dropped(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataSource) {} |
| 262 | |
| 263 | fn dnd_finished(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataSource) {} |
| 264 | |
| 265 | fn action(&mut self, _: &Connection, _: &QueueHandle<Self>, _: &WlDataSource, _: DndAction) {} |
| 266 | } |
| 267 | |
| 268 | impl SeatHandler for State { |
| 269 | fn seat_state(&mut self) -> &mut SeatState { |
| 270 | &mut self.seats |
| 271 | } |
| 272 | |
| 273 | fn new_seat(&mut self, _: &Connection, qh: &QueueHandle<Self>, seat: WlSeat) { |
| 274 | self.add_device(qh, &seat); |
| 275 | } |
| 276 | |
| 277 | fn new_capability(&mut self, _: &Connection, _: &QueueHandle<Self>, _: WlSeat, _: Capability) {} |
| 278 | |
| 279 | fn remove_capability( |
| 280 | &mut self, |
| 281 | _: &Connection, |
| 282 | _: &QueueHandle<Self>, |
| 283 | _: WlSeat, |
| 284 | _: Capability, |
| 285 | ) { |
| 286 | } |
| 287 | |
| 288 | fn remove_seat(&mut self, _: &Connection, _: &QueueHandle<Self>, seat: WlSeat) { |
| 289 | self.devices.retain(|d| d.data().seat() != &seat); |
| 290 | } |
| 291 | } |
| 292 | |
| 293 | impl ProvidesRegistryState for State { |
| 294 | registry_handlers![SeatState]; |
| 295 | |
| 296 | fn registry(&mut self) -> &mut RegistryState { |
| 297 | &mut self.registry |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | delegate_registry!(State); |
| 302 | delegate_seat!(State); |
| 303 | delegate_data_device!(State); |