| 1 | //! Wayland에서 압축파일 안 항목을 창 밖으로 끌어 놓기. |
| 2 | //! |
| 3 | //! winit은 끌어 놓기를 받기만 하고 시작하지는 못하므로, winit이 쓰는 같은 Wayland 연결에 |
| 4 | //! 별도 이벤트 큐를 만들어 wl_data_device로 직접 끌기를 시작함. 끌기 시작에는 버튼을 누른 |
| 5 | //! 순간의 serial이 필요하므로 같은 seat에서 포인터를 하나 더 받아 왼쪽 버튼 누름을 기억함. |
| 6 | //! |
| 7 | //! 받는 쪽에는 text/uri-list(풀린 파일 경로)와, 샌드박스 앱(스냅·Flatpak 브라우저 등)을 |
| 8 | //! 위한 application/vnd.portal.filetransfer(문서 포털 전송 키)를 함께 제공함. |
| 9 | |
| 10 | use std::{ |
| 11 | collections::VecDeque, |
| 12 | io::Write, |
| 13 | os::fd::OwnedFd, |
| 14 | path::PathBuf, |
| 15 | sync::{Arc, Mutex}, |
| 16 | }; |
| 17 | use wayland_client::{ |
| 18 | Connection, Dispatch, Proxy, QueueHandle, WEnum, event_created_child, |
| 19 | protocol::{ |
| 20 | wl_data_device, wl_data_device_manager, wl_data_offer, wl_data_source, wl_pointer, |
| 21 | wl_registry, wl_seat, wl_surface, |
| 22 | }, |
| 23 | }; |
| 24 | use zipelo_ui_memory_app::drag_out::{DragEvent, DragOut, uri_list}; |
| 25 | |
| 26 | const URI_LIST: &str = "text/uri-list"; |
| 27 | const PORTAL: &str = "application/vnd.portal.filetransfer"; |
| 28 | /// linux/input-event-codes.h의 BTN_LEFT. |
| 29 | const BTN_LEFT: u32 = 0x110; |
| 30 | |
| 31 | enum Ready { |
| 32 | Paths(Vec<PathBuf>), |
| 33 | Failed, |
| 34 | } |
| 35 | |
| 36 | #[derive(Default)] |
| 37 | struct Shared { |
| 38 | /// 이 창 위에서 누르고 있는 왼쪽 버튼의 serial. |
| 39 | press: Option<u32>, |
| 40 | /// 파일이 준비되기 전에 들어온 데이터 요청. |
| 41 | pending: Vec<(String, OwnedFd)>, |
| 42 | ready: Option<Ready>, |
| 43 | events: VecDeque<DragEvent>, |
| 44 | source: Option<wl_data_source::WlDataSource>, |
| 45 | } |
| 46 | |
| 47 | struct State { |
| 48 | shared: Arc<Mutex<Shared>>, |
| 49 | surface: wl_surface::WlSurface, |
| 50 | focused: bool, |
| 51 | seat: Option<wl_seat::WlSeat>, |
| 52 | manager: Option<wl_data_device_manager::WlDataDeviceManager>, |
| 53 | pointer: Option<wl_pointer::WlPointer>, |
| 54 | repaint: eframe::egui::Context, |
| 55 | } |
| 56 | |
| 57 | pub struct WaylandDrag { |
| 58 | conn: Connection, |
| 59 | qh: QueueHandle<State>, |
| 60 | manager: wl_data_device_manager::WlDataDeviceManager, |
| 61 | device: wl_data_device::WlDataDevice, |
| 62 | surface: wl_surface::WlSurface, |
| 63 | shared: Arc<Mutex<Shared>>, |
| 64 | /// 문서 포털 전송을 쓸 수 있는지. 시작을 늦추지 않도록 따로 확인함. |
| 65 | portal: Arc<std::sync::atomic::AtomicBool>, |
| 66 | } |
| 67 | |
| 68 | /// 창이 Wayland 창이면 끌어 놓기 구현을 만듦. 아니면(X11, Windows) None. |
| 69 | pub fn create( |
| 70 | handles: &(impl raw_window_handle::HasDisplayHandle + raw_window_handle::HasWindowHandle), |
| 71 | repaint: eframe::egui::Context, |
| 72 | ) -> Option<WaylandDrag> { |
| 73 | use raw_window_handle::{RawDisplayHandle, RawWindowHandle}; |
| 74 | let RawDisplayHandle::Wayland(display) = handles.display_handle().ok()?.as_raw() else { |
| 75 | return None; |
| 76 | }; |
| 77 | let RawWindowHandle::Wayland(window) = handles.window_handle().ok()?.as_raw() else { |
| 78 | return None; |
| 79 | }; |
| 80 | // 안전성: winit이 만든 wl_display와 wl_surface는 창이 살아 있는 동안 유효함. |
| 81 | // 앱은 창과 같은 수명으로 이 구현을 들고 있으며, 외부 디스플레이는 닫지 않음. |
| 82 | let backend = unsafe { |
| 83 | wayland_backend::sys::client::Backend::from_foreign_display(display.display.as_ptr().cast()) |
| 84 | }; |
| 85 | let conn = Connection::from_backend(backend); |
| 86 | let surface_id = unsafe { |
| 87 | wayland_backend::sys::client::ObjectId::from_ptr( |
| 88 | wl_surface::WlSurface::interface(), |
| 89 | window.surface.as_ptr().cast(), |
| 90 | ) |
| 91 | } |
| 92 | .ok()?; |
| 93 | let surface = wl_surface::WlSurface::from_id(&conn, surface_id).ok()?; |
| 94 | let mut queue = conn.new_event_queue::<State>(); |
| 95 | let qh = queue.handle(); |
| 96 | let shared = Arc::new(Mutex::new(Shared::default())); |
| 97 | let mut state = State { |
| 98 | shared: shared.clone(), |
| 99 | surface: surface.clone(), |
| 100 | focused: false, |
| 101 | seat: None, |
| 102 | manager: None, |
| 103 | pointer: None, |
| 104 | repaint, |
| 105 | }; |
| 106 | conn.display().get_registry(&qh, ()); |
| 107 | queue.roundtrip(&mut state).ok()?; |
| 108 | // seat의 포인터 지원 여부를 받음. |
| 109 | queue.roundtrip(&mut state).ok()?; |
| 110 | let manager = state.manager.clone()?; |
| 111 | let device = manager.get_data_device(state.seat.as_ref()?, &qh, ()); |
| 112 | queue.roundtrip(&mut state).ok()?; |
| 113 | let portal = Arc::new(std::sync::atomic::AtomicBool::new(false)); |
| 114 | let found = portal.clone(); |
| 115 | let _ = std::thread::Builder::new() |
| 116 | .name("zipelo-portal-check".into()) |
| 117 | .spawn(move || { |
| 118 | let available = pollster::block_on(ashpd::documents::FileTransfer::new()).is_ok(); |
| 119 | zipelo_ui_memory_app::log_debug!("문서 포털 전송 사용 가능: {available}"); |
| 120 | found.store(available, std::sync::atomic::Ordering::Release); |
| 121 | }); |
| 122 | zipelo_ui_memory_app::log_debug!( |
| 123 | "Wayland 끌어 놓기 준비 (데이터 장치 v{})", |
| 124 | manager.version() |
| 125 | ); |
| 126 | std::thread::Builder::new() |
| 127 | .name("zipelo-wayland-drag".into()) |
| 128 | .spawn(move || { |
| 129 | loop { |
| 130 | if let Err(error) = queue.blocking_dispatch(&mut state) { |
| 131 | zipelo_ui_memory_app::log_warn!("Wayland 끌어 놓기 큐 종료: {error}"); |
| 132 | break; |
| 133 | } |
| 134 | } |
| 135 | }) |
| 136 | .ok()?; |
| 137 | Some(WaylandDrag { |
| 138 | conn, |
| 139 | qh, |
| 140 | manager, |
| 141 | device, |
| 142 | surface, |
| 143 | shared, |
| 144 | portal, |
| 145 | }) |
| 146 | } |
| 147 | |
| 148 | impl DragOut for WaylandDrag { |
| 149 | fn start( |
| 150 | &mut self, |
| 151 | _: &[PathBuf], |
| 152 | _: &mut zipelo_ui_memory_app::drag_out::Pump<'_>, |
| 153 | ) -> bool { |
| 154 | let mut shared = self.shared.lock().unwrap(); |
| 155 | let Some(serial) = shared.press else { |
| 156 | zipelo_ui_memory_app::log_debug!("끌기 시작 실패: 누르고 있는 버튼 없음"); |
| 157 | return false; |
| 158 | }; |
| 159 | if let Some(old) = shared.source.take() { |
| 160 | old.destroy(); |
| 161 | } |
| 162 | shared.pending.clear(); |
| 163 | shared.ready = None; |
| 164 | shared.events.clear(); |
| 165 | let source = self.manager.create_data_source(&self.qh, ()); |
| 166 | source.offer(URI_LIST.into()); |
| 167 | if self.portal.load(std::sync::atomic::Ordering::Acquire) { |
| 168 | source.offer(PORTAL.into()); |
| 169 | } |
| 170 | if source.version() >= 3 { |
| 171 | source.set_actions(wl_data_device_manager::DndAction::Copy); |
| 172 | } |
| 173 | self.device |
| 174 | .start_drag(Some(&source), &self.surface, None, serial); |
| 175 | shared.source = Some(source); |
| 176 | drop(shared); |
| 177 | self.conn.flush().is_ok() |
| 178 | } |
| 179 | |
| 180 | fn poll(&mut self) -> Option<DragEvent> { |
| 181 | self.shared.lock().unwrap().events.pop_front() |
| 182 | } |
| 183 | |
| 184 | fn provide(&mut self, paths: &[PathBuf]) { |
| 185 | let pending = { |
| 186 | let mut shared = self.shared.lock().unwrap(); |
| 187 | shared.ready = Some(Ready::Paths(paths.to_vec())); |
| 188 | std::mem::take(&mut shared.pending) |
| 189 | }; |
| 190 | for (mime, fd) in pending { |
| 191 | send(mime, fd, paths.to_vec()); |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | fn fail(&mut self) { |
| 196 | let mut shared = self.shared.lock().unwrap(); |
| 197 | shared.ready = Some(Ready::Failed); |
| 198 | // 기다리던 요청은 fd를 닫아 빈 데이터로 끝냄. |
| 199 | shared.pending.clear(); |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | /// 받는 쪽이 요청한 형식으로 데이터를 써 줌. 받는 쪽이 늦게 읽어도 화면이 멈추지 않게 |
| 204 | /// 별도 스레드에서 씀. |
| 205 | fn send(mime: String, fd: OwnedFd, paths: Vec<PathBuf>) { |
| 206 | let _ = std::thread::Builder::new() |
| 207 | .name("zipelo-wayland-send".into()) |
| 208 | .spawn(move || { |
| 209 | let data = if mime == PORTAL { |
| 210 | match portal_key(&paths) { |
| 211 | Ok(key) => key, |
| 212 | Err(error) => { |
| 213 | zipelo_ui_memory_app::log_warn!("문서 포털 전송 실패: {error}"); |
| 214 | return; |
| 215 | } |
| 216 | } |
| 217 | } else { |
| 218 | uri_list(&paths) |
| 219 | }; |
| 220 | let mut file = std::fs::File::from(fd); |
| 221 | if let Err(error) = file.write_all(data.as_bytes()) { |
| 222 | zipelo_ui_memory_app::log_warn!("끌어 놓기 데이터 쓰기 실패: {error}"); |
| 223 | } |
| 224 | }); |
| 225 | } |
| 226 | |
| 227 | /// 문서 포털에 파일을 올리고 받는 쪽에 넘길 전송 키를 만듦. |
| 228 | fn portal_key(paths: &[PathBuf]) -> Result<String, String> { |
| 229 | use std::os::unix::fs::OpenOptionsExt; |
| 230 | let files = paths |
| 231 | .iter() |
| 232 | .map(|path| { |
| 233 | // 폴더도 넘길 수 있도록 O_PATH로 엶. |
| 234 | std::fs::OpenOptions::new() |
| 235 | .read(true) |
| 236 | .custom_flags(0o10000000 | 0o2000000) |
| 237 | .open(path) |
| 238 | }) |
| 239 | .collect::<Result<Vec<_>, _>>() |
| 240 | .map_err(|error| error.to_string())?; |
| 241 | pollster::block_on(async { |
| 242 | let transfer = ashpd::documents::FileTransfer::new().await?; |
| 243 | let key = transfer.start_transfer(false, true).await?; |
| 244 | transfer.add_files(&key, &files).await?; |
| 245 | Ok::<_, ashpd::Error>(key) |
| 246 | }) |
| 247 | .map_err(|error| error.to_string()) |
| 248 | } |
| 249 | |
| 250 | impl Dispatch<wl_registry::WlRegistry, ()> for State { |
| 251 | fn event( |
| 252 | state: &mut Self, |
| 253 | registry: &wl_registry::WlRegistry, |
| 254 | event: wl_registry::Event, |
| 255 | _: &(), |
| 256 | _: &Connection, |
| 257 | qh: &QueueHandle<Self>, |
| 258 | ) { |
| 259 | if let wl_registry::Event::Global { |
| 260 | name, |
| 261 | interface, |
| 262 | version, |
| 263 | } = event |
| 264 | { |
| 265 | match interface.as_str() { |
| 266 | "wl_seat" if state.seat.is_none() => { |
| 267 | state.seat = Some(registry.bind(name, version.min(5), qh, ())); |
| 268 | } |
| 269 | "wl_data_device_manager" if state.manager.is_none() => { |
| 270 | state.manager = Some(registry.bind(name, version.min(3), qh, ())); |
| 271 | } |
| 272 | _ => {} |
| 273 | } |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | |
| 278 | impl Dispatch<wl_seat::WlSeat, ()> for State { |
| 279 | fn event( |
| 280 | state: &mut Self, |
| 281 | seat: &wl_seat::WlSeat, |
| 282 | event: wl_seat::Event, |
| 283 | _: &(), |
| 284 | _: &Connection, |
| 285 | qh: &QueueHandle<Self>, |
| 286 | ) { |
| 287 | if let wl_seat::Event::Capabilities { |
| 288 | capabilities: WEnum::Value(capabilities), |
| 289 | } = event |
| 290 | && capabilities.contains(wl_seat::Capability::Pointer) |
| 291 | && state.pointer.is_none() |
| 292 | { |
| 293 | state.pointer = Some(seat.get_pointer(qh, ())); |
| 294 | } |
| 295 | } |
| 296 | } |
| 297 | |
| 298 | impl Dispatch<wl_pointer::WlPointer, ()> for State { |
| 299 | fn event( |
| 300 | state: &mut Self, |
| 301 | _: &wl_pointer::WlPointer, |
| 302 | event: wl_pointer::Event, |
| 303 | _: &(), |
| 304 | _: &Connection, |
| 305 | _: &QueueHandle<Self>, |
| 306 | ) { |
| 307 | match event { |
| 308 | wl_pointer::Event::Enter { surface, .. } => { |
| 309 | state.focused = surface == state.surface; |
| 310 | } |
| 311 | wl_pointer::Event::Leave { .. } => state.focused = false, |
| 312 | wl_pointer::Event::Button { |
| 313 | serial, |
| 314 | button: BTN_LEFT, |
| 315 | state: WEnum::Value(pressed), |
| 316 | .. |
| 317 | } => { |
| 318 | state.shared.lock().unwrap().press = (state.focused |
| 319 | && pressed == wl_pointer::ButtonState::Pressed) |
| 320 | .then_some(serial); |
| 321 | } |
| 322 | _ => {} |
| 323 | } |
| 324 | } |
| 325 | } |
| 326 | |
| 327 | impl Dispatch<wl_data_device_manager::WlDataDeviceManager, ()> for State { |
| 328 | fn event( |
| 329 | _: &mut Self, |
| 330 | _: &wl_data_device_manager::WlDataDeviceManager, |
| 331 | _: wl_data_device_manager::Event, |
| 332 | _: &(), |
| 333 | _: &Connection, |
| 334 | _: &QueueHandle<Self>, |
| 335 | ) { |
| 336 | } |
| 337 | } |
| 338 | |
| 339 | impl Dispatch<wl_data_device::WlDataDevice, ()> for State { |
| 340 | fn event( |
| 341 | _: &mut Self, |
| 342 | _: &wl_data_device::WlDataDevice, |
| 343 | _: wl_data_device::Event, |
| 344 | _: &(), |
| 345 | _: &Connection, |
| 346 | _: &QueueHandle<Self>, |
| 347 | ) { |
| 348 | // 이 창으로 들어오는 끌어 놓기는 winit이 따로 처리하므로 무시함. |
| 349 | } |
| 350 | |
| 351 | event_created_child!(State, wl_data_device::WlDataDevice, [ |
| 352 | wl_data_device::EVT_DATA_OFFER_OPCODE => (wl_data_offer::WlDataOffer, ()), |
| 353 | ]); |
| 354 | } |
| 355 | |
| 356 | impl Dispatch<wl_data_offer::WlDataOffer, ()> for State { |
| 357 | fn event( |
| 358 | _: &mut Self, |
| 359 | _: &wl_data_offer::WlDataOffer, |
| 360 | _: wl_data_offer::Event, |
| 361 | _: &(), |
| 362 | _: &Connection, |
| 363 | _: &QueueHandle<Self>, |
| 364 | ) { |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | impl Dispatch<wl_data_source::WlDataSource, ()> for State { |
| 369 | fn event( |
| 370 | state: &mut Self, |
| 371 | source: &wl_data_source::WlDataSource, |
| 372 | event: wl_data_source::Event, |
| 373 | _: &(), |
| 374 | _: &Connection, |
| 375 | _: &QueueHandle<Self>, |
| 376 | ) { |
| 377 | let mut shared = state.shared.lock().unwrap(); |
| 378 | let current = shared.source.as_ref() == Some(source); |
| 379 | match event { |
| 380 | wl_data_source::Event::Send { mime_type, fd } => { |
| 381 | zipelo_ui_memory_app::log_debug!("끌어 놓기 데이터 요청: {mime_type}"); |
| 382 | match &shared.ready { |
| 383 | Some(Ready::Paths(paths)) => send(mime_type, fd, paths.clone()), |
| 384 | // 실패했으면 fd를 닫아 빈 데이터로 끝냄. |
| 385 | Some(Ready::Failed) => {} |
| 386 | None => shared.pending.push((mime_type, fd)), |
| 387 | } |
| 388 | } |
| 389 | wl_data_source::Event::Cancelled => { |
| 390 | source.destroy(); |
| 391 | if current { |
| 392 | shared.source = None; |
| 393 | shared.events.push_back(DragEvent::Cancelled); |
| 394 | } |
| 395 | } |
| 396 | wl_data_source::Event::DndDropPerformed if current => { |
| 397 | shared.events.push_back(DragEvent::Dropped); |
| 398 | } |
| 399 | wl_data_source::Event::DndFinished => { |
| 400 | source.destroy(); |
| 401 | if current { |
| 402 | shared.source = None; |
| 403 | shared.events.push_back(DragEvent::Finished); |
| 404 | } |
| 405 | } |
| 406 | _ => {} |
| 407 | } |
| 408 | drop(shared); |
| 409 | state.repaint.request_repaint(); |
| 410 | } |
| 411 | } |