team-ljyzipelo

공개
822줄27 KB
1//! Windows에서 압축파일 안 항목을 창 밖으로 끌어 놓기.
2//!
3//! 7-Zip 파일 관리자와 같은 흐름을 씀. 끌기를 시작하면 앱은 바로 풀기를 시작하고, OLE 끌기
4//! (DoDragDrop)는 버튼을 누른 창의 스레드(화면 스레드)에서 진행함(다른 스레드에서는 마우스
5//! 입력을 받지 못함). 끌기는 놓거나 취소할 때까지 돌아오지 않으므로 그동안 앱이 넘긴 pump로
6//! 작업자의 풀기 진행을 받음.
7//!
8//! - 끌고 다니는 동안: 받는 쪽(Zipelo 창 자신 포함)이 목록을 물으면 기다리지 않고 풀릴 예정인
9//! 경로를 돌려줌. 그래서 끌기와 화면이 멈추지 않음. Esc를 누르면 그 자리에서 풀기를 취소함.
10//! - 버튼을 놓았을 때: 이미 다 풀렸으면 바로 놓음. 아직이면 Windows 기본 진행률 창(취소 가능)을
11//! 띄우고 다 풀린 뒤에 놓기를 완료해, 받는 쪽은 놓은 위치로 완성된 파일을 복사함.
12
13use std::{
14 cell::Cell,
15 collections::VecDeque,
16 ffi::c_void,
17 path::PathBuf,
18 sync::{
19 Arc, Mutex,
20 atomic::{AtomicU32, Ordering},
21 },
22 time::{Duration, Instant},
23};
24use windows_sys::{
25 Win32::{
26 Foundation::{DRAGDROP_S_CANCEL, DRAGDROP_S_DROP, DRAGDROP_S_USEDEFAULTCURSORS, HWND},
27 System::{
28 Com::{CLSCTX_INPROC_SERVER, CoCreateInstance},
29 Memory::{GHND, GlobalAlloc, GlobalLock, GlobalUnlock},
30 Ole::{CF_HDROP, DROPEFFECT, DROPEFFECT_COPY, DoDragDrop, OleInitialize},
31 },
32 UI::{
33 Input::KeyboardAndMouse::{GetAsyncKeyState, VK_ESCAPE, VK_LBUTTON, VK_RBUTTON},
34 Shell::SHCreateStdEnumFmtEtc,
35 WindowsAndMessaging::{
36 DispatchMessageW, GetSystemMetrics, MSG, MsgWaitForMultipleObjects, PM_REMOVE,
37 PeekMessageW, PostQuitMessage, QS_ALLINPUT, SM_SWAPBUTTON, TranslateMessage,
38 WM_KEYDOWN, WM_QUIT,
39 },
40 },
41 },
42 core::{GUID, HRESULT},
43};
44use zipelo_ui_memory_app::drag_out::{DragEvent, DragOut, Pump, PumpState};
45
46thread_local! {
47 /// 끌기가 진행되는 동안(start 안에서만) 앱이 넘긴 작업 진행 함수.
48 static PUMP: Cell<Option<*mut Pump<'static>>> = const { Cell::new(None) };
49}
50
51const S_OK: HRESULT = 0;
52const E_NOINTERFACE: HRESULT = 0x8000_4002_u32 as i32;
53const E_NOTIMPL: HRESULT = 0x8000_4001_u32 as i32;
54const E_FAIL: HRESULT = 0x8000_4005_u32 as i32;
55const DV_E_FORMATETC: HRESULT = 0x8004_0064_u32 as i32;
56const OLE_E_ADVISENOTSUPPORTED: HRESULT = 0x8004_0003_u32 as i32;
57const DATA_S_SAMEFORMATETC: HRESULT = 0x0004_0130;
58const TYMED_HGLOBAL: u32 = 1;
59const DVASPECT_CONTENT: u32 = 1;
60const DATADIR_GET: u32 = 1;
61const MK_LBUTTON: u32 = 0x1;
62const MK_RBUTTON: u32 = 0x2;
63/// 놓은 뒤 이 시간 안에 다 풀리면 진행률 창을 띄우지 않음.
64const PROGRESS_DELAY: Duration = Duration::from_millis(300);
65
66const fn guid(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> GUID {
67 GUID {
68 data1,
69 data2,
70 data3,
71 data4,
72 }
73}
74const OLE_TAIL: [u8; 8] = [0xC0, 0, 0, 0, 0, 0, 0, 0x46];
75const IID_IUNKNOWN: GUID = guid(0, 0, 0, OLE_TAIL);
76const IID_IDATAOBJECT: GUID = guid(0x0000_010e, 0, 0, OLE_TAIL);
77const IID_IDROPSOURCE: GUID = guid(0x0000_0121, 0, 0, OLE_TAIL);
78const CLSID_PROGRESS_DIALOG: GUID = guid(
79 0xF838_3852,
80 0xFCD3,
81 0x11d1,
82 [0xA6, 0xB9, 0x00, 0x60, 0x97, 0xDF, 0x5B, 0xD4],
83);
84const IID_IPROGRESS_DIALOG: GUID = guid(
85 0xEBBC_7C04,
86 0x315E,
87 0x11d2,
88 [0xB6, 0x2F, 0x00, 0x60, 0x97, 0xDF, 0x5B, 0xD4],
89);
90
91/// FORMATETC와 같은 배치.
92#[repr(C)]
93#[derive(Clone, Copy)]
94struct FormatEtc {
95 format: u16,
96 device: *mut c_void,
97 aspect: u32,
98 index: i32,
99 tymed: u32,
100}
101
102/// STGMEDIUM과 같은 배치(공용체는 HGLOBAL 하나만 씀).
103#[repr(C)]
104struct StgMedium {
105 tymed: u32,
106 data: *mut c_void,
107 release: *mut c_void,
108}
109
110/// DROPFILES와 같은 배치. 뒤에 UTF-16 경로 목록이 이어짐.
111#[repr(C)]
112struct DropFiles {
113 files: u32,
114 x: i32,
115 y: i32,
116 non_client: i32,
117 wide: i32,
118}
119
120#[derive(Default)]
121struct Shared {
122 /// 다 풀린 뒤 넘길 경로. 놓기 전에 목록을 물으면 이 경로를 돌려줌.
123 planned: Vec<PathBuf>,
124 /// 다 풀렸으면 Some(true), 실패했으면 Some(false).
125 ready: Option<bool>,
126 events: VecDeque<DragEvent>,
127}
128
129type State = Arc<Mutex<Shared>>;
130
131pub struct WindowsDrag {
132 hwnd: isize,
133 state: State,
134 repaint: eframe::egui::Context,
135}
136
137/// 창이 Win32 창이면 끌어 놓기 구현을 만듦.
138pub fn create(
139 handles: &impl raw_window_handle::HasWindowHandle,
140 repaint: eframe::egui::Context,
141) -> Option<WindowsDrag> {
142 let raw_window_handle::RawWindowHandle::Win32(window) = handles.window_handle().ok()?.as_raw()
143 else {
144 return None;
145 };
146 // 안전성: 화면 스레드에서 OLE를 초기화함. winit이 이미 했으면 S_FALSE이며 앱이 끝날
147 // 때까지 유지함.
148 let result = unsafe { OleInitialize(std::ptr::null()) };
149 zipelo_ui_memory_app::log_debug!("Windows 끌어 놓기 준비 (OLE {result:#x})");
150 Some(WindowsDrag {
151 hwnd: window.hwnd.get(),
152 state: Arc::new(Mutex::new(Shared::default())),
153 repaint,
154 })
155}
156
157fn button_held() -> bool {
158 // 안전성: 인자만 받는 Win32 상태 조회임.
159 unsafe {
160 let swapped = GetSystemMetrics(SM_SWAPBUTTON) != 0;
161 let key = if swapped { VK_RBUTTON } else { VK_LBUTTON };
162 GetAsyncKeyState(key as i32) < 0
163 }
164}
165
166/// Esc가 지금 눌려 있거나 지난 확인 이후 눌린 적이 있는지. 짧게 누른 것도 놓치지 않음.
167fn escape_pressed() -> bool {
168 // 안전성: 인자만 받는 Win32 상태 조회임.
169 let state = unsafe { GetAsyncKeyState(VK_ESCAPE as i32) };
170 state < 0 || state & 1 != 0
171}
172
173/// 화면 스레드에 쌓인 메시지를 처리함. 기다리는 동안에도 진행률 창이 표시되고 Zipelo 창이
174/// 응답 없음으로 바뀌지 않게 함. 창에 온 Esc 키를 보았거나 종료 요청이 오면 true.
175fn pump_messages() -> bool {
176 let mut cancel = false;
177 // 안전성: 표준 메시지 루프임. 받은 메시지는 같은 스레드에서 바로 처리함.
178 unsafe {
179 let mut message: MSG = std::mem::zeroed();
180 while PeekMessageW(&mut message, std::ptr::null_mut(), 0, 0, PM_REMOVE) != 0 {
181 if message.message == WM_QUIT {
182 // 종료 요청은 끌기가 끝난 뒤 앱 메시지 루프가 받도록 다시 넣고 끌기를 취소함.
183 PostQuitMessage(message.wParam as i32);
184 return true;
185 }
186 if message.message == WM_KEYDOWN && message.wParam == VK_ESCAPE as usize {
187 cancel = true;
188 continue;
189 }
190 TranslateMessage(&message);
191 DispatchMessageW(&message);
192 }
193 }
194 cancel
195}
196
197/// 메시지가 오거나 시간이 지날 때까지 기다림.
198fn wait_messages(timeout: Duration) {
199 // 안전성: 기다릴 핸들 없이 메시지 도착만 기다림.
200 unsafe {
201 MsgWaitForMultipleObjects(
202 0,
203 std::ptr::null(),
204 0,
205 timeout.as_millis() as u32,
206 QS_ALLINPUT,
207 );
208 }
209}
210
211/// 끌기 중에 앱의 작업 진행을 받음. start 밖에서는 실패로 봄.
212fn pump(cancel: bool) -> PumpState {
213 match PUMP.with(Cell::get) {
214 // 안전성: PUMP는 start가 진행 중인 같은 스레드에서만 설정돼 있음.
215 Some(pump) => unsafe { (*pump)(cancel) },
216 None => PumpState::Failed,
217 }
218}
219
220impl DragOut for WindowsDrag {
221 fn start(&mut self, planned: &[PathBuf], pump: &mut Pump<'_>) -> bool {
222 if !button_held() {
223 return false;
224 }
225 {
226 let mut shared = self.state.lock().unwrap();
227 shared.planned = planned.to_vec();
228 shared.ready = None;
229 shared.events.clear();
230 }
231 // 안전성: pump는 이 함수가 돌아오기 전까지만 쓰고, 끝나면 바로 지움. 데이터 객체와
232 // 끌기 원본의 메서드는 DoDragDrop 안에서 같은 스레드로 불림.
233 let pump: *mut Pump<'_> = pump;
234 PUMP.with(|cell| {
235 cell.set(Some(unsafe {
236 std::mem::transmute::<*mut Pump<'_>, *mut Pump<'static>>(pump)
237 }))
238 });
239 // 안전성: 두 객체는 끌기가 끝난 뒤 이 함수가 가진 참조 하나씩을 놓음.
240 let result = unsafe {
241 let data = DataObject::create(self.state.clone());
242 let source = DropSource::create(self.state.clone(), self.hwnd);
243 let mut effect: DROPEFFECT = 0;
244 let result = DoDragDrop(data, source, DROPEFFECT_COPY, &mut effect);
245 release_unknown(source);
246 release_unknown(data);
247 result
248 };
249 PUMP.with(|cell| cell.set(None));
250 zipelo_ui_memory_app::log_debug!("셸 끌기 끝: {result:#x}");
251 self.state
252 .lock()
253 .unwrap()
254 .events
255 .push_back(if result == DRAGDROP_S_DROP {
256 DragEvent::Finished
257 } else {
258 DragEvent::Cancelled
259 });
260 self.repaint.request_repaint();
261 true
262 }
263
264 fn poll(&mut self) -> Option<DragEvent> {
265 self.state.lock().unwrap().events.pop_front()
266 }
267
268 fn provide(&mut self, paths: &[PathBuf]) {
269 let mut shared = self.state.lock().unwrap();
270 shared.planned = paths.to_vec();
271 shared.ready = Some(true);
272 }
273
274 fn fail(&mut self) {
275 self.state.lock().unwrap().ready = Some(false);
276 }
277}
278
279fn wide_text(text: &str) -> Vec<u16> {
280 text.encode_utf16().chain(Some(0)).collect()
281}
282
283fn wide(path: &std::path::Path) -> Vec<u16> {
284 use std::os::windows::ffi::OsStrExt;
285 let text = path.as_os_str().encode_wide().collect::<Vec<_>>();
286 // 셸은 \\?\ 접두사가 붙은 경로를 받지 않으므로 뗌.
287 let prefix: Vec<u16> = r"\\?\".encode_utf16().collect();
288 if text.starts_with(&prefix) {
289 text[prefix.len()..].to_vec()
290 } else {
291 text
292 }
293}
294
295fn same_guid(a: &GUID, b: &GUID) -> bool {
296 a.data1 == b.data1 && a.data2 == b.data2 && a.data3 == b.data3 && a.data4 == b.data4
297}
298
299/// IUnknown 부분을 공유하는 COM 객체 머리. 두 객체 모두 첫 필드가 vtable 포인터임.
300#[repr(C)]
301struct UnknownVtbl {
302 query_interface:
303 unsafe extern "system" fn(*mut c_void, *const GUID, *mut *mut c_void) -> HRESULT,
304 add_ref: unsafe extern "system" fn(*mut c_void) -> u32,
305 release: unsafe extern "system" fn(*mut c_void) -> u32,
306}
307
308/// COM 객체의 IUnknown::Release를 부름.
309unsafe fn release_unknown(object: *mut c_void) {
310 // 안전성: object는 IUnknown으로 시작하는 vtable을 가진 COM 객체임.
311 unsafe {
312 let vtable = *(object as *const *const UnknownVtbl);
313 ((*vtable).release)(object);
314 }
315}
316
317// ---- 데이터 객체 -------------------------------------------------------------------------
318
319/// CF_HDROP만 제공하는 최소 IDataObject. 어떤 요청에도 기다리지 않음.
320#[repr(C)]
321struct DataObject {
322 vtable: *const DataObjectVtbl,
323 refs: AtomicU32,
324 state: State,
325}
326
327#[repr(C)]
328struct DataObjectVtbl {
329 unknown: UnknownVtbl,
330 get_data:
331 unsafe extern "system" fn(*mut DataObject, *const FormatEtc, *mut StgMedium) -> HRESULT,
332 get_data_here:
333 unsafe extern "system" fn(*mut DataObject, *const FormatEtc, *mut StgMedium) -> HRESULT,
334 query_get_data: unsafe extern "system" fn(*mut DataObject, *const FormatEtc) -> HRESULT,
335 get_canonical_format_etc:
336 unsafe extern "system" fn(*mut DataObject, *const FormatEtc, *mut FormatEtc) -> HRESULT,
337 set_data: unsafe extern "system" fn(
338 *mut DataObject,
339 *const FormatEtc,
340 *const StgMedium,
341 i32,
342 ) -> HRESULT,
343 enum_format_etc: unsafe extern "system" fn(*mut DataObject, u32, *mut *mut c_void) -> HRESULT,
344 d_advise: unsafe extern "system" fn(
345 *mut DataObject,
346 *const FormatEtc,
347 u32,
348 *mut c_void,
349 *mut u32,
350 ) -> HRESULT,
351 d_unadvise: unsafe extern "system" fn(*mut DataObject, u32) -> HRESULT,
352 enum_d_advise: unsafe extern "system" fn(*mut DataObject, *mut *mut c_void) -> HRESULT,
353}
354
355static DATA_VTABLE: DataObjectVtbl = DataObjectVtbl {
356 unknown: UnknownVtbl {
357 query_interface: data_query_interface,
358 add_ref: data_add_ref,
359 release: data_release,
360 },
361 get_data,
362 get_data_here,
363 query_get_data,
364 get_canonical_format_etc,
365 set_data,
366 enum_format_etc,
367 d_advise,
368 d_unadvise,
369 enum_d_advise,
370};
371
372impl DataObject {
373 fn create(state: State) -> *mut c_void {
374 Box::into_raw(Box::new(Self {
375 vtable: &DATA_VTABLE,
376 refs: AtomicU32::new(1),
377 state,
378 }))
379 .cast()
380 }
381}
382
383unsafe extern "system" fn data_query_interface(
384 this: *mut c_void,
385 iid: *const GUID,
386 out: *mut *mut c_void,
387) -> HRESULT {
388 // 안전성: OLE 규약대로 iid와 out은 호출 동안 유효함.
389 unsafe { query(this, iid, out, &IID_IDATAOBJECT, data_add_ref) }
390}
391
392unsafe extern "system" fn data_add_ref(this: *mut c_void) -> u32 {
393 // 안전성: 참조가 남아 있는 동안 객체는 살아 있음.
394 unsafe {
395 (*this.cast::<DataObject>())
396 .refs
397 .fetch_add(1, Ordering::AcqRel)
398 + 1
399 }
400}
401
402unsafe extern "system" fn data_release(this: *mut c_void) -> u32 {
403 // 안전성: 마지막 참조를 놓을 때 한 번만 Box로 되돌려 해제함.
404 unsafe {
405 let object = this.cast::<DataObject>();
406 let left = (*object).refs.fetch_sub(1, Ordering::AcqRel) - 1;
407 if left == 0 {
408 drop(Box::from_raw(object));
409 }
410 left
411 }
412}
413
414/// IUnknown과 지정한 인터페이스만 돌려주는 QueryInterface 공통 처리.
415unsafe fn query(
416 this: *mut c_void,
417 iid: *const GUID,
418 out: *mut *mut c_void,
419 own: &GUID,
420 add_ref: unsafe extern "system" fn(*mut c_void) -> u32,
421) -> HRESULT {
422 if out.is_null() {
423 return E_NOINTERFACE;
424 }
425 // 안전성: 호출한 쪽이 넘긴 포인터는 호출 동안 유효함.
426 unsafe {
427 if !iid.is_null() && (same_guid(&*iid, &IID_IUNKNOWN) || same_guid(&*iid, own)) {
428 add_ref(this);
429 *out = this;
430 S_OK
431 } else {
432 *out = std::ptr::null_mut();
433 E_NOINTERFACE
434 }
435 }
436}
437
438fn supported(format: *const FormatEtc) -> bool {
439 // 안전성: OLE가 넘기는 FORMATETC 포인터는 호출 동안 유효함.
440 !format.is_null()
441 && unsafe { (*format).format == CF_HDROP && (*format).tymed & TYMED_HGLOBAL != 0 }
442}
443
444unsafe extern "system" fn get_data(
445 this: *mut DataObject,
446 format: *const FormatEtc,
447 medium: *mut StgMedium,
448) -> HRESULT {
449 if !supported(format) || medium.is_null() {
450 return DV_E_FORMATETC;
451 }
452 // 안전성: this는 참조가 남은 객체임.
453 let (paths, ready) = unsafe {
454 let shared = (*this).state.lock().unwrap();
455 (shared.planned.clone(), shared.ready)
456 };
457 if ready == Some(false) || paths.is_empty() {
458 return E_FAIL;
459 }
460 // 놓기 전이면 아직 풀리지 않은 예정 경로를 돌려줌. 놓을 때는 끌기 원본이 다 풀리기를
461 // 기다린 뒤에 놓기를 완료하므로 받는 쪽은 완성된 파일을 받음.
462 let mut list: Vec<u16> = Vec::new();
463 for path in &paths {
464 list.extend(wide(path));
465 list.push(0);
466 }
467 list.push(0);
468 let header = std::mem::size_of::<DropFiles>();
469 let size = header + list.len() * 2;
470 // 안전성: 할당한 메모리를 잠근 동안에만 쓰고, 받는 쪽이 STGMEDIUM으로 해제함.
471 unsafe {
472 let memory = GlobalAlloc(GHND, size);
473 if memory.is_null() {
474 return E_FAIL;
475 }
476 let base = GlobalLock(memory).cast::<u8>();
477 if base.is_null() {
478 return E_FAIL;
479 }
480 base.cast::<DropFiles>().write_unaligned(DropFiles {
481 files: header as u32,
482 x: 0,
483 y: 0,
484 non_client: 0,
485 wide: 1,
486 });
487 std::ptr::copy_nonoverlapping(list.as_ptr().cast::<u8>(), base.add(header), list.len() * 2);
488 GlobalUnlock(memory);
489 *medium = StgMedium {
490 tymed: TYMED_HGLOBAL,
491 data: memory,
492 release: std::ptr::null_mut(),
493 };
494 }
495 S_OK
496}
497
498unsafe extern "system" fn get_data_here(
499 _: *mut DataObject,
500 _: *const FormatEtc,
501 _: *mut StgMedium,
502) -> HRESULT {
503 E_NOTIMPL
504}
505
506unsafe extern "system" fn query_get_data(_: *mut DataObject, format: *const FormatEtc) -> HRESULT {
507 if supported(format) {
508 S_OK
509 } else {
510 DV_E_FORMATETC
511 }
512}
513
514unsafe extern "system" fn get_canonical_format_etc(
515 _: *mut DataObject,
516 _: *const FormatEtc,
517 out: *mut FormatEtc,
518) -> HRESULT {
519 if !out.is_null() {
520 // 안전성: out은 호출 동안 유효한 FORMATETC임.
521 unsafe { (*out).device = std::ptr::null_mut() };
522 }
523 DATA_S_SAMEFORMATETC
524}
525
526unsafe extern "system" fn set_data(
527 _: *mut DataObject,
528 _: *const FormatEtc,
529 _: *const StgMedium,
530 _: i32,
531) -> HRESULT {
532 E_NOTIMPL
533}
534
535unsafe extern "system" fn enum_format_etc(
536 _: *mut DataObject,
537 direction: u32,
538 out: *mut *mut c_void,
539) -> HRESULT {
540 if direction != DATADIR_GET || out.is_null() {
541 return E_NOTIMPL;
542 }
543 let format = FormatEtc {
544 format: CF_HDROP,
545 device: std::ptr::null_mut(),
546 aspect: DVASPECT_CONTENT,
547 index: -1,
548 tymed: TYMED_HGLOBAL,
549 };
550 // 안전성: 셸이 FORMATETC 배열을 복사해 새 열거자를 만듦.
551 unsafe { SHCreateStdEnumFmtEtc(1, (&format as *const FormatEtc).cast(), out) }
552}
553
554unsafe extern "system" fn d_advise(
555 _: *mut DataObject,
556 _: *const FormatEtc,
557 _: u32,
558 _: *mut c_void,
559 _: *mut u32,
560) -> HRESULT {
561 OLE_E_ADVISENOTSUPPORTED
562}
563
564unsafe extern "system" fn d_unadvise(_: *mut DataObject, _: u32) -> HRESULT {
565 OLE_E_ADVISENOTSUPPORTED
566}
567
568unsafe extern "system" fn enum_d_advise(_: *mut DataObject, _: *mut *mut c_void) -> HRESULT {
569 OLE_E_ADVISENOTSUPPORTED
570}
571
572// ---- 끌기 원본 ---------------------------------------------------------------------------
573
574/// 끌기 중 버튼과 Esc를 보고 끌기를 계속할지 정하는 IDropSource.
575#[repr(C)]
576struct DropSource {
577 vtable: *const DropSourceVtbl,
578 refs: AtomicU32,
579 state: State,
580 hwnd: isize,
581}
582
583#[repr(C)]
584struct DropSourceVtbl {
585 unknown: UnknownVtbl,
586 query_continue_drag: unsafe extern "system" fn(*mut DropSource, i32, u32) -> HRESULT,
587 give_feedback: unsafe extern "system" fn(*mut DropSource, u32) -> HRESULT,
588}
589
590static SOURCE_VTABLE: DropSourceVtbl = DropSourceVtbl {
591 unknown: UnknownVtbl {
592 query_interface: source_query_interface,
593 add_ref: source_add_ref,
594 release: source_release,
595 },
596 query_continue_drag,
597 give_feedback,
598};
599
600impl DropSource {
601 fn create(state: State, hwnd: isize) -> *mut c_void {
602 Box::into_raw(Box::new(Self {
603 vtable: &SOURCE_VTABLE,
604 refs: AtomicU32::new(1),
605 state,
606 hwnd,
607 }))
608 .cast()
609 }
610
611 fn set_ready(&self, ready: PumpState) {
612 let mut shared = self.state.lock().unwrap();
613 match ready {
614 PumpState::Ready(paths) => {
615 shared.planned = paths;
616 shared.ready = Some(true);
617 }
618 PumpState::Failed => shared.ready = Some(false),
619 PumpState::Waiting { .. } => {}
620 }
621 }
622
623 fn ready(&self) -> Option<bool> {
624 self.state.lock().unwrap().ready
625 }
626
627 /// 버튼을 놓았는데 아직 다 풀리지 않았으면 진행률 창을 띄우고 기다림.
628 /// 다 풀리면 true, 취소했거나 실패하면 false.
629 fn wait_for_files(&self) -> bool {
630 let started = Instant::now();
631 let mut dialog: Option<ProgressDialog> = None;
632 // 기다리기 전에 눌렸던 Esc 기록은 지움.
633 escape_pressed();
634 loop {
635 // 메시지를 처리해야 진행률 창(Zipelo 창이 부모)이 표시되고 Zipelo 창도 응답함.
636 let cancelled =
637 pump_messages() | escape_pressed() | dialog.as_ref().is_some_and(|d| d.cancelled());
638 let state = pump(cancelled);
639 match state {
640 PumpState::Waiting { done, total } => {
641 if cancelled {
642 self.set_ready(PumpState::Failed);
643 return false;
644 }
645 if dialog.is_none() && started.elapsed() >= PROGRESS_DELAY {
646 dialog = ProgressDialog::open(self.hwnd);
647 }
648 if let Some(dialog) = &dialog {
649 dialog.progress(done, total);
650 }
651 wait_messages(Duration::from_millis(30));
652 }
653 ready => {
654 let ok = matches!(ready, PumpState::Ready(_));
655 self.set_ready(ready);
656 return ok;
657 }
658 }
659 }
660 }
661}
662
663unsafe extern "system" fn source_query_interface(
664 this: *mut c_void,
665 iid: *const GUID,
666 out: *mut *mut c_void,
667) -> HRESULT {
668 // 안전성: OLE 규약대로 iid와 out은 호출 동안 유효함.
669 unsafe { query(this, iid, out, &IID_IDROPSOURCE, source_add_ref) }
670}
671
672unsafe extern "system" fn source_add_ref(this: *mut c_void) -> u32 {
673 // 안전성: 참조가 남아 있는 동안 객체는 살아 있음.
674 unsafe {
675 (*this.cast::<DropSource>())
676 .refs
677 .fetch_add(1, Ordering::AcqRel)
678 + 1
679 }
680}
681
682unsafe extern "system" fn source_release(this: *mut c_void) -> u32 {
683 // 안전성: 마지막 참조를 놓을 때 한 번만 Box로 되돌려 해제함.
684 unsafe {
685 let object = this.cast::<DropSource>();
686 let left = (*object).refs.fetch_sub(1, Ordering::AcqRel) - 1;
687 if left == 0 {
688 drop(Box::from_raw(object));
689 }
690 left
691 }
692}
693
694unsafe extern "system" fn query_continue_drag(
695 this: *mut DropSource,
696 escape: i32,
697 keys: u32,
698) -> HRESULT {
699 // 안전성: this는 DoDragDrop이 쓰는 동안 살아 있는 객체임.
700 let source = unsafe { &*this };
701 if escape != 0 {
702 // 끌기를 취소하면 받을 곳이 없으므로 풀기도 바로 취소함.
703 pump(true);
704 source.set_ready(PumpState::Failed);
705 return DRAGDROP_S_CANCEL;
706 }
707 // 끌고 다니는 동안에도 작업자 진행을 받음(막히지 않음).
708 if source.ready().is_none() {
709 let state = pump(false);
710 if state == PumpState::Failed {
711 // 암호 등 사용자 응답이 필요하거나 실패함. 끌기를 끝내고 앱 화면에서 안내함.
712 source.set_ready(PumpState::Failed);
713 return DRAGDROP_S_CANCEL;
714 }
715 source.set_ready(state);
716 }
717 if keys & (MK_LBUTTON | MK_RBUTTON) != 0 {
718 return S_OK;
719 }
720 // 버튼을 놓음: 다 풀린 뒤에 놓기를 완료함.
721 match source.ready() {
722 Some(true) => DRAGDROP_S_DROP,
723 Some(false) => DRAGDROP_S_CANCEL,
724 None if source.wait_for_files() => DRAGDROP_S_DROP,
725 None => DRAGDROP_S_CANCEL,
726 }
727}
728
729unsafe extern "system" fn give_feedback(_: *mut DropSource, _: u32) -> HRESULT {
730 DRAGDROP_S_USEDEFAULTCURSORS
731}
732
733// ---- 진행률 창 ---------------------------------------------------------------------------
734
735/// Windows 기본 진행률 창(IProgressDialog). 자기 스레드에서 돌아 화면이 멈춰도 응답함.
736struct ProgressDialog(*mut c_void);
737
738#[repr(C)]
739struct ProgressDialogVtbl {
740 unknown: UnknownVtbl,
741 start: unsafe extern "system" fn(*mut c_void, HWND, *mut c_void, u32, *const c_void) -> HRESULT,
742 stop: unsafe extern "system" fn(*mut c_void) -> HRESULT,
743 set_title: unsafe extern "system" fn(*mut c_void, *const u16) -> HRESULT,
744 set_animation: unsafe extern "system" fn(*mut c_void, *mut c_void, u32) -> HRESULT,
745 has_user_cancelled: unsafe extern "system" fn(*mut c_void) -> i32,
746 set_progress: unsafe extern "system" fn(*mut c_void, u32, u32) -> HRESULT,
747 set_progress64: unsafe extern "system" fn(*mut c_void, u64, u64) -> HRESULT,
748 set_line:
749 unsafe extern "system" fn(*mut c_void, u32, *const u16, i32, *const c_void) -> HRESULT,
750 set_cancel_msg: unsafe extern "system" fn(*mut c_void, *const u16, *const c_void) -> HRESULT,
751}
752
753/// PROGDLG_AUTOTIME | PROGDLG_NOMINIMIZE
754const PROGRESS_FLAGS: u32 = 0x2 | 0x8;
755
756impl ProgressDialog {
757 fn vtable(&self) -> &ProgressDialogVtbl {
758 // 안전성: self.0은 CoCreateInstance가 돌려준 IProgressDialog임.
759 unsafe { &**(self.0 as *const *const ProgressDialogVtbl) }
760 }
761
762 fn open(hwnd: isize) -> Option<Self> {
763 let mut object: *mut c_void = std::ptr::null_mut();
764 // 안전성: 표준 셸 COM 객체를 만들고 실패하면 쓰지 않음.
765 let result = unsafe {
766 CoCreateInstance(
767 &CLSID_PROGRESS_DIALOG,
768 std::ptr::null_mut(),
769 CLSCTX_INPROC_SERVER,
770 &IID_IPROGRESS_DIALOG,
771 &mut object,
772 )
773 };
774 if result < 0 || object.is_null() {
775 zipelo_ui_memory_app::log_warn!("진행률 창을 만들지 못함: {result:#x}");
776 return None;
777 }
778 let dialog = Self(object);
779 let title = wide_text("Zipelo");
780 let line1 = wide_text("끌어 놓은 파일을 푸는 중입니다");
781 let line2 = wide_text("다 풀리면 놓은 곳으로 옮깁니다");
782 let cancel = wide_text("취소하는 중입니다");
783 let vtable = dialog.vtable();
784 // 안전성: 문자열은 각 호출 동안 살아 있고, 창은 Drop에서 닫음.
785 unsafe {
786 (vtable.set_title)(object, title.as_ptr());
787 (vtable.set_line)(object, 1, line1.as_ptr(), 0, std::ptr::null());
788 (vtable.set_line)(object, 2, line2.as_ptr(), 0, std::ptr::null());
789 (vtable.set_cancel_msg)(object, cancel.as_ptr(), std::ptr::null());
790 (vtable.start)(
791 object,
792 hwnd as HWND,
793 std::ptr::null_mut(),
794 PROGRESS_FLAGS,
795 std::ptr::null(),
796 );
797 }
798 Some(dialog)
799 }
800
801 fn progress(&self, done: u64, total: Option<u64>) {
802 // 안전성: 열린 진행률 창에 값만 넘김.
803 unsafe {
804 (self.vtable().set_progress64)(self.0, done, total.unwrap_or(0).max(done));
805 }
806 }
807
808 fn cancelled(&self) -> bool {
809 // 안전성: 열린 진행률 창의 상태 조회임.
810 unsafe { (self.vtable().has_user_cancelled)(self.0) != 0 }
811 }
812}
813
814impl Drop for ProgressDialog {
815 fn drop(&mut self) {
816 // 안전성: 창을 닫고 참조를 한 번 놓음.
817 unsafe {
818 (self.vtable().stop)(self.0);
819 release_unknown(self.0);
820 }
821 }
822}