diff --git a/src/platform/win/drop_target.rs b/src/platform/win/drop_target.rs index b2c7c56c..b9caad96 100644 --- a/src/platform/win/drop_target.rs +++ b/src/platform/win/drop_target.rs @@ -90,7 +90,8 @@ impl DropTarget { }; unsafe { - let Ok(medium) = data_object.GetData(&format) else { + // GetData hands us ownership of the medium, so it must be released once we're done. + let Ok(mut medium) = data_object.GetData(&format) else { self.drop_data.replace(DropData::None); return; }; @@ -99,6 +100,7 @@ impl DropTarget { let item_count = DragQueryFileW(hdrop, 0xFFFFFFFF, null_mut(), 0); if item_count == 0 { + ReleaseStgMedium(&mut medium); self.drop_data.replace(DropData::None); return; } @@ -115,6 +117,8 @@ impl DropTarget { paths.push(OsString::from_wide(&buffer[..characters as usize]).into()) } + ReleaseStgMedium(&mut medium); + self.drop_data.replace(DropData::Files(paths)); } } @@ -197,3 +201,248 @@ impl IDropTarget_Impl for DropTarget_Impl { Ok(()) } } + +#[cfg(test)] +mod tests { + use std::cell::Cell; + use std::ffi::c_void; + use std::mem::{size_of, ManuallyDrop}; + use std::path::PathBuf; + use std::ptr::NonNull; + use std::rc::Rc; + use std::sync::atomic::{AtomicIsize, Ordering}; + use std::sync::Arc; + + use raw_window_handle::{HasWindowHandle, RawWindowHandle}; + use windows::core::implement; + use windows::Win32::Foundation::{E_NOTIMPL, HGLOBAL, POINTL, S_OK}; + use windows::Win32::System::Com::StructuredStorage::{ + CreateStreamOnHGlobal, GetHGlobalFromStream, + }; + use windows::Win32::System::Com::{ + IAdviseSink, IDataObject, IDataObject_Impl, IEnumFORMATETC, IEnumSTATDATA, IStream, + FORMATETC, STGMEDIUM, STGMEDIUM_0, TYMED_HGLOBAL, + }; + use windows::Win32::System::Ole::{IDropTarget, DROPEFFECT_NONE}; + use windows::Win32::System::SystemServices::MODIFIERKEYS_FLAGS; + use windows_core::{ComObject, IUnknown, Ref, BOOL}; + use windows_sys::Win32::UI::Shell::DROPFILES; + + use super::DropTarget; + use crate::platform::BaseviewWindow; + use crate::wrappers::win32::window::{HWnd, WindowData}; + use crate::{ + DropData, Event, EventStatus, HandlerError, Window, WindowHandler, WindowSettings, + WindowSize, + }; + + struct EmptyHandler; + + impl WindowHandler for EmptyHandler { + fn draw(&self) -> Result<(), HandlerError> { + Ok(()) + } + + fn resized(&self, _new_size: WindowSize) -> Result<(), HandlerError> { + Ok(()) + } + + fn on_event(&self, _event: Event) -> EventStatus { + EventStatus::Ignored + } + } + + /// Creates a window that is never shown, and a drop target for it made the same way the + /// window makes its own. + fn hidden_window_drop_target() -> (Window, ComObject) { + let hwnd = Arc::new(AtomicIsize::new(0)); + let builder_hwnd = Arc::clone(&hwnd); + + let window = Window::create(WindowSettings::new(), move |context| { + if let Ok(RawWindowHandle::Win32(handle)) = + context.window_handle().map(|handle| handle.as_raw()) + { + builder_hwnd.store(handle.hwnd.get(), Ordering::Relaxed); + } + Ok(EmptyHandler) + }); + let window = match window { + Ok(window) => window, + Err(error) => panic!("could not create the window: {error}"), + }; + + let Some(hwnd) = NonNull::new(hwnd.load(Ordering::Relaxed) as *mut c_void) else { + panic!("the handler builder didn't get a Win32 window handle"); + }; + // SAFETY: `hwnd` is a live window created on this thread. + let hwnd = unsafe { HWnd::from_raw(hwnd) }; + + let Some(data) = hwnd.get_userdata_ptr::>() else { + panic!("the window has no window data"); + }; + // SAFETY: the window is alive, so its window data is too. + let window_state = unsafe { + WindowData::handle(data, |data| data.inner().map(|w| Rc::clone(&w.window_state))) + }; + let Some(window_state) = window_state else { + panic!("the window data is not initialized"); + }; + + (window, ComObject::new(DropTarget::new(Rc::downgrade(&window_state), hwnd))) + } + + /// Owns the file list handed out by one `GetData` call, and counts itself out when the + /// receiver releases the medium. + #[implement] + struct MediumOwner { + // Created with delete-on-release, so the file list is freed along with this. + _stream: IStream, + outstanding: Rc>, + } + + impl Drop for MediumOwner { + fn drop(&mut self) { + self.outstanding.set(self.outstanding.get().saturating_sub(1)); + } + } + + /// A drag source offering `files` as CF_HDROP, with a fresh medium for each `GetData` call. + #[implement(IDataObject)] + struct FileDrop { + files: &'static [&'static str], + outstanding: Rc>, + } + + impl FileDrop { + fn hdrop_stream(&self) -> windows_core::Result { + let header = + DROPFILES { pFiles: size_of::() as u32, fWide: 1, ..Default::default() }; + // SAFETY: DROPFILES is a plain packed C struct, so all of its bytes are initialized. + let header = unsafe { + std::slice::from_raw_parts( + (&header as *const DROPFILES).cast::(), + size_of::(), + ) + }; + + let mut bytes = header.to_vec(); + let names = self.files.iter().flat_map(|file| file.encode_utf16().chain(Some(0))); + for unit in names.chain(Some(0)) { + bytes.extend_from_slice(&unit.to_le_bytes()); + } + + // SAFETY: a null handle makes the stream allocate its own block. + let stream = unsafe { CreateStreamOnHGlobal(HGLOBAL::default(), true) }?; + // SAFETY: `bytes` outlives the call and holds `bytes.len()` bytes. + unsafe { stream.Write(bytes.as_ptr().cast(), bytes.len() as u32, None) }.ok()?; + Ok(stream) + } + } + + #[allow(non_snake_case, reason = "To match trait")] + impl IDataObject_Impl for FileDrop_Impl { + fn GetData(&self, _format: *const FORMATETC) -> windows_core::Result { + let stream = self.hdrop_stream()?; + // SAFETY: `stream` is a live stream created on an HGLOBAL. + let hglobal = unsafe { GetHGlobalFromStream(&stream) }?; + + self.outstanding.set(self.outstanding.get().saturating_add(1)); + let owner = MediumOwner { _stream: stream, outstanding: Rc::clone(&self.outstanding) }; + let owner: IUnknown = ComObject::new(owner).into_interface(); + + Ok(STGMEDIUM { + tymed: TYMED_HGLOBAL.0 as u32, + u: STGMEDIUM_0 { hGlobal: hglobal }, + pUnkForRelease: ManuallyDrop::new(Some(owner)), + }) + } + + fn GetDataHere( + &self, _format: *const FORMATETC, _medium: *mut STGMEDIUM, + ) -> windows_core::Result<()> { + Err(E_NOTIMPL.into()) + } + + fn QueryGetData(&self, _format: *const FORMATETC) -> windows_core::HRESULT { + S_OK + } + + fn GetCanonicalFormatEtc( + &self, _format_in: *const FORMATETC, _format_out: *mut FORMATETC, + ) -> windows_core::HRESULT { + E_NOTIMPL + } + + fn SetData( + &self, _format: *const FORMATETC, _medium: *const STGMEDIUM, _release: BOOL, + ) -> windows_core::Result<()> { + Err(E_NOTIMPL.into()) + } + + fn EnumFormatEtc(&self, _direction: u32) -> windows_core::Result { + Err(E_NOTIMPL.into()) + } + + fn DAdvise( + &self, _format: *const FORMATETC, _advf: u32, _sink: Ref, + ) -> windows_core::Result { + Err(E_NOTIMPL.into()) + } + + fn DUnadvise(&self, _connection: u32) -> windows_core::Result<()> { + Err(E_NOTIMPL.into()) + } + + fn EnumDAdvise(&self) -> windows_core::Result { + Err(E_NOTIMPL.into()) + } + } + + /// Drags `files` into a window and drops them, and returns how many media were still + /// unreleased after `DragEnter` and after `Drop`. + fn unreleased_media(files: &'static [&'static str]) -> (usize, usize) { + let (_window, target) = hidden_window_drop_target(); + let interface: IDropTarget = target.to_interface(); + + let outstanding = Rc::new(Cell::new(0)); + let data = FileDrop { files, outstanding: Rc::clone(&outstanding) }; + let data: IDataObject = ComObject::new(data).into_interface(); + let point = POINTL { x: 0, y: 0 }; + let mut effect = DROPEFFECT_NONE; + + // SAFETY: `data` and `effect` outlive the call. + let result = + unsafe { interface.DragEnter(&data, MODIFIERKEYS_FLAGS(0), point, &mut effect) }; + if let Err(error) = result { + panic!("DragEnter failed: {error}"); + } + let after_drag_enter = outstanding.get(); + + // SAFETY: `data` and `effect` outlive the call. + let result = unsafe { interface.Drop(&data, MODIFIERKEYS_FLAGS(0), point, &mut effect) }; + if let Err(error) = result { + panic!("Drop failed: {error}"); + } + let after_drop = outstanding.get(); + + let expected = match files { + [] => DropData::None, + files => DropData::Files(files.iter().map(PathBuf::from).collect()), + }; + assert_eq!(*target.drop_data.borrow(), expected, "the drop target read the wrong files"); + + (after_drag_enter, after_drop) + } + + #[test] + fn drop_medium_is_released_with_one_file() { + let unreleased = unreleased_media(&["C:\\dropped.txt"]); + assert_eq!(unreleased, (0, 0), "media left unreleased after (DragEnter, Drop)"); + } + + #[test] + fn drop_medium_is_released_with_no_files() { + let unreleased = unreleased_media(&[]); + assert_eq!(unreleased, (0, 0), "media left unreleased after (DragEnter, Drop)"); + } +}