From a27e982c23b4ec036bc34ff58c12d218da71eaac Mon Sep 17 00:00:00 2001 From: LiJianying Date: Sun, 29 Nov 2026 09:36:13 +0800 Subject: [PATCH] Marshal Windows DropTarget registration to window thread and throttle DragOver --- src/platform/windows/drop_target_windows.cpp | 199 +++++++++++--- tests/CMakeLists.txt | 4 + tests/drop_target_ui_thread_windows_test.cpp | 271 +++++++++++++++++++ 3 files changed, 439 insertions(+), 35 deletions(-) create mode 100644 tests/drop_target_ui_thread_windows_test.cpp diff --git a/src/platform/windows/drop_target_windows.cpp b/src/platform/windows/drop_target_windows.cpp index c24dad95..7922ab6b 100644 --- a/src/platform/windows/drop_target_windows.cpp +++ b/src/platform/windows/drop_target_windows.cpp @@ -5,7 +5,11 @@ #include // clang-format on +#include +#include +#include #include +#include #include #include #include @@ -14,6 +18,7 @@ #include "dpi_utils_windows.h" #include "drag_drop_utils_windows.h" #include "string_utils_windows.h" +#include "ui_thread_windows.h" namespace nativeapi { namespace { @@ -87,7 +92,10 @@ class DropTargetCom : public IDropTarget { IID_PPV_ARGS(&helper_)); } - void Detach() { handler_ = nullptr; } + void Detach() { + detached_.store(true, std::memory_order_release); + handler_ = nullptr; + } // IUnknown HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** object) override { @@ -112,28 +120,44 @@ class DropTargetCom : public IDropTarget { DWORD /*key_state*/, POINTL point, DWORD* effect) override { + if (!effect) return E_INVALIDARG; const DWORD allowed = *effect; - *effect = handler_ ? handler_->Entered(data, point, allowed) : DROPEFFECT_NONE; + DropTargetComHandler* handler = ActiveHandler(); + *effect = handler ? handler->Entered(data, point, allowed) : DROPEFFECT_NONE; + helper_active_ = false; if (helper_) { POINT pt = {point.x, point.y}; - helper_->DragEnter(hwnd_, data, &pt, *effect); + helper_active_ = SUCCEEDED(helper_->DragEnter(hwnd_, data, &pt, *effect)); + last_helper_pt_ = pt; + last_helper_effect_ = *effect; } return S_OK; } HRESULT STDMETHODCALLTYPE DragOver(DWORD /*key_state*/, POINTL point, DWORD* effect) override { + if (!effect) return E_INVALIDARG; const DWORD allowed = *effect; - *effect = handler_ ? handler_->Moved(point, allowed) : DROPEFFECT_NONE; - if (helper_) { + DropTargetComHandler* handler = ActiveHandler(); + *effect = handler ? handler->Moved(point, allowed) : DROPEFFECT_NONE; + if (helper_ && helper_active_ && + (point.x != last_helper_pt_.x || point.y != last_helper_pt_.y || + *effect != last_helper_effect_)) { POINT pt = {point.x, point.y}; helper_->DragOver(&pt, *effect); + last_helper_pt_ = pt; + last_helper_effect_ = *effect; } return S_OK; } HRESULT STDMETHODCALLTYPE DragLeave() override { - if (helper_) helper_->DragLeave(); - if (handler_) handler_->Exited(); + if (helper_ && helper_active_) { + helper_->DragLeave(); + } + helper_active_ = false; + if (DropTargetComHandler* handler = ActiveHandler()) { + handler->Exited(); + } return S_OK; } @@ -141,26 +165,74 @@ class DropTargetCom : public IDropTarget { DWORD /*key_state*/, POINTL point, DWORD* effect) override { + if (!effect) return E_INVALIDARG; const DWORD allowed = *effect; - if (helper_) { + const bool was_active = helper_active_; + helper_active_ = false; + DropTargetComHandler* handler = ActiveHandler(); + *effect = handler ? handler->Dropped(data, point, allowed) : DROPEFFECT_NONE; + if (helper_ && was_active) { POINT pt = {point.x, point.y}; helper_->Drop(data, &pt, *effect); } - *effect = handler_ ? handler_->Dropped(data, point, allowed) : DROPEFFECT_NONE; return S_OK; } private: + DropTargetComHandler* ActiveHandler() const { + return detached_.load(std::memory_order_acquire) ? nullptr : handler_; + } + ~DropTargetCom() { if (helper_) helper_->Release(); } LONG references_ = 1; HWND hwnd_; + std::atomic detached_{false}; DropTargetComHandler* handler_; IDropTargetHelper* helper_ = nullptr; + bool helper_active_ = false; + POINT last_helper_pt_ = {0, 0}; + DWORD last_helper_effect_ = DROPEFFECT_NONE; }; +// Runs a small synchronous task on `thread_id` (inline if already on it). +// OLE drag-drop registration and revocation must run on the window's owning +// Win32 thread: if RegisterDragDrop runs on a Dart UI isolate thread that has +// no Win32 message loop, COM marshals Explorer's DragEnter RPC into that +// unpumped STA apartment and freezes the drag source (explorer.exe) forever. +template +bool RunOnOwningThread(DWORD thread_id, Work work) { + if (thread_id == 0) { + return false; + } + if (thread_id == GetCurrentThreadId()) { + return work(); + } + struct SyncState { + std::mutex mutex; + std::condition_variable ready; + bool done = false; + bool result = false; + }; + auto sync = std::make_shared(); + if (!detail::PostToThread(thread_id, [sync, work = std::move(work)]() mutable { + const bool ok = work(); + { + std::lock_guard lock(sync->mutex); + sync->result = ok; + sync->done = true; + } + sync->ready.notify_one(); + })) { + return false; + } + std::unique_lock lock(sync->mutex); + sync->ready.wait_for(lock, std::chrono::seconds(5), [&] { return sync->done; }); + return sync->done && sync->result; +} + } // namespace struct DropTarget::Impl::Platform : DropTargetComHandler { @@ -182,28 +254,44 @@ struct DropTarget::Impl::Platform : DropTargetComHandler { Point ToContent(POINTL point) const { POINT client = {point.x, point.y}; ScreenToClient(hwnd, &client); - double scale = GetScaleFactorForWindow(hwnd); - if (scale <= 0.0) scale = 1.0; + const double scale = cached_scale > 0.0 ? cached_scale : 1.0; return {client.x / scale, client.y / scale}; } DWORD Entered(IDataObject* data, POINTL point, DWORD allowed) override { + cached_scale = GetScaleFactorForWindow(hwnd); + if (cached_scale <= 0.0) cached_scale = 1.0; + last_move_emit_tick = 0; const bool has_data = HasFormat(data, CF_HDROP) || HasFormat(data, CF_UNICODETEXT); last_position = ToContent(point); return ToDropEffect(impl->Entered(last_position, SourceOperations(allowed), has_data)); } DWORD Moved(POINTL point, DWORD allowed) override { + const unsigned ops = SourceOperations(allowed); + if (!impl->accepted || (ops & OperationBit(impl->operation)) == 0) { + return DROPEFFECT_NONE; + } last_position = ToContent(point); - return ToDropEffect(impl->Moved(last_position, SourceOperations(allowed))); + // Throttle DropTargetMovedEvent to ~60 Hz so high-rate mouse polling + // (250-1000 Hz) does not flood the Dart/UI event queue during hover. + constexpr ULONGLONG kMoveThrottleMs = 16; + const ULONGLONG now = GetTickCount64(); + if (last_move_emit_tick == 0 || now - last_move_emit_tick >= kMoveThrottleMs) { + last_move_emit_tick = now; + return ToDropEffect(impl->Moved(last_position, ops)); + } + return ToDropEffect(impl->operation); } void Exited() override { + last_move_emit_tick = 0; // DragLeave carries no position; report where the drag was last seen. impl->Exited(last_position); } DWORD Dropped(IDataObject* data, POINTL point, DWORD allowed) override { + last_move_emit_tick = 0; last_position = ToContent(point); // A source that changed its offer since the last DragOver refuses here too. if (impl->Moved(last_position, SourceOperations(allowed)) == DragOperation::None) { @@ -215,10 +303,16 @@ struct DropTarget::Impl::Platform : DropTargetComHandler { return effect; } + ~Platform() override { alive->store(false, std::memory_order_release); } + Impl* impl; + std::shared_ptr> alive = std::make_shared>(true); HWND hwnd = nullptr; + DWORD owner_thread_id = 0; DropTargetCom* com = nullptr; std::optional ole; + double cached_scale = 1.0; + ULONGLONG last_move_emit_tick = 0; Point last_position{0, 0}; }; @@ -239,36 +333,71 @@ bool DropTarget::Impl::Register() { if (!hwnd || !IsWindow(hwnd)) { return false; } - platform->ole.emplace(); - if (!platform->ole->Succeeded()) { - platform->ole.reset(); + const DWORD owner_thread = GetWindowThreadProcessId(hwnd, nullptr); + if (owner_thread == 0) { return false; } - auto* com = new DropTargetCom(hwnd, platform.get()); - // OLE finds the target by walking up from the window under the cursor, so - // registering the top-level window also covers child windows (a Flutter view). - if (FAILED(RegisterDragDrop(hwnd, com))) { - com->Detach(); - com->Release(); - platform->ole.reset(); - return false; - } - platform->hwnd = hwnd; - platform->com = com; - return true; + Platform* plat = platform.get(); + auto alive = plat->alive; + return RunOnOwningThread(owner_thread, [plat, alive, hwnd, owner_thread]() -> bool { + if (!alive->load(std::memory_order_acquire) || !IsWindow(hwnd)) { + return false; + } + plat->ole.emplace(); + if (!plat->ole->Succeeded()) { + plat->ole.reset(); + return false; + } + auto* com = new DropTargetCom(hwnd, plat); + // OLE finds the target by walking up from the window under the cursor, so + // registering the top-level window also covers child windows (a Flutter view). + HRESULT hr = RegisterDragDrop(hwnd, com); + if (hr == DRAGDROP_E_ALREADYREGISTERED) { + RevokeDragDrop(hwnd); + hr = RegisterDragDrop(hwnd, com); + } + if (FAILED(hr)) { + com->Detach(); + com->Release(); + plat->ole.reset(); + return false; + } + plat->hwnd = hwnd; + plat->owner_thread_id = owner_thread; + plat->com = com; + return true; + }); } void DropTarget::Impl::Unregister() { - if (platform->hwnd && IsWindow(platform->hwnd)) { - RevokeDragDrop(platform->hwnd); + Platform* plat = platform.get(); + if (plat->com) { + plat->com->Detach(); } - if (platform->com) { - platform->com->Detach(); - platform->com->Release(); + const DWORD owner_thread = plat->owner_thread_id; + auto alive = plat->alive; + auto cleanup = [plat, alive]() -> bool { + if (!alive->load(std::memory_order_acquire)) { + return false; + } + if (plat->hwnd && IsWindow(plat->hwnd)) { + RevokeDragDrop(plat->hwnd); + } + if (plat->com) { + plat->com->Detach(); + plat->com->Release(); + plat->com = nullptr; + } + plat->hwnd = nullptr; + plat->owner_thread_id = 0; + plat->ole.reset(); + return true; + }; + if (owner_thread != 0) { + RunOnOwningThread(owner_thread, cleanup); + } else { + cleanup(); } - platform->com = nullptr; - platform->hwnd = nullptr; - platform->ole.reset(); } } // namespace nativeapi diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index f478ef46..4e84d700 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -90,6 +90,10 @@ if(WIN32) target_link_libraries(window_hidden_titlebar_nccalcsize_windows_test PRIVATE nativeapi comctl32) add_test(NAME window_hidden_titlebar_nccalcsize_windows_test COMMAND window_hidden_titlebar_nccalcsize_windows_test) set_tests_properties(window_hidden_titlebar_nccalcsize_windows_test PROPERTIES TIMEOUT 20) + add_executable(drop_target_ui_thread_windows_test drop_target_ui_thread_windows_test.cpp) + target_link_libraries(drop_target_ui_thread_windows_test PRIVATE nativeapi ole32 uuid) + add_test(NAME drop_target_ui_thread_windows_test COMMAND drop_target_ui_thread_windows_test) + set_tests_properties(drop_target_ui_thread_windows_test PROPERTIES TIMEOUT 20) endif() # window_manager#569 (#77): WS_POPUP windows and their caption. diff --git a/tests/drop_target_ui_thread_windows_test.cpp b/tests/drop_target_ui_thread_windows_test.cpp new file mode 100644 index 00000000..2c97fee9 --- /dev/null +++ b/tests/drop_target_ui_thread_windows_test.cpp @@ -0,0 +1,271 @@ +// Regression test for libnativeapi/nativeapi#57: +// When DropTarget::AddListener() is called from a non-UI thread that does NOT +// pump Win32 messages (e.g. Flutter's Dart UI isolate thread under +// UIThreadPolicy::RunOnSeparateThread), RegisterDragDrop must still run on the +// window's owning Win32 thread so OLE marshals DragEnter/DragOver/DragLeave to +// the pumping platform thread instead of deadlocking the drag source forever. + +// clang-format off +#include +#include +// clang-format on + +#include +#include +#include +#include +#include +#include +#include + +#include "../src/drop_target.h" +#include "../src/platform/windows/ui_thread_windows.h" +#include "../src/window.h" + +namespace { + +int g_failures = 0; + +void Check(bool ok, const char* what) { + if (!ok) { + std::fprintf(stderr, "FAIL: %s\n", what); + ++g_failures; + } +} + +// Minimal IDataObject offering CF_UNICODETEXT so DropTarget accepts the drag. +class DummyTextDataObject : public IDataObject { + public: + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** obj) override { + if (!obj) return E_POINTER; + if (riid == IID_IUnknown || riid == IID_IDataObject) { + *obj = static_cast(this); + AddRef(); + return S_OK; + } + *obj = nullptr; + return E_NOINTERFACE; + } + ULONG STDMETHODCALLTYPE AddRef() override { return InterlockedIncrement(&refs_); } + ULONG STDMETHODCALLTYPE Release() override { + const LONG r = InterlockedDecrement(&refs_); + if (r == 0) delete this; + return r; + } + HRESULT STDMETHODCALLTYPE GetData(FORMATETC* fmt, STGMEDIUM* med) override { + if (!fmt || !med || fmt->cfFormat != CF_UNICODETEXT) return DV_E_FORMATETC; + const wchar_t text[] = L"hello"; + HGLOBAL mem = GlobalAlloc(GMEM_MOVEABLE, sizeof(text)); + if (!mem) return E_OUTOFMEMORY; + void* dst = GlobalLock(mem); + memcpy(dst, text, sizeof(text)); + GlobalUnlock(mem); + med->tymed = TYMED_HGLOBAL; + med->hGlobal = mem; + med->pUnkForRelease = nullptr; + return S_OK; + } + HRESULT STDMETHODCALLTYPE GetDataHere(FORMATETC*, STGMEDIUM*) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE QueryGetData(FORMATETC* fmt) override { + return (fmt && fmt->cfFormat == CF_UNICODETEXT && (fmt->tymed & TYMED_HGLOBAL)) ? S_OK + : DV_E_FORMATETC; + } + HRESULT STDMETHODCALLTYPE GetCanonicalFormatEtc(FORMATETC*, FORMATETC*) override { + return E_NOTIMPL; + } + HRESULT STDMETHODCALLTYPE SetData(FORMATETC*, STGMEDIUM*, BOOL) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE EnumFormatEtc(DWORD, IEnumFORMATETC**) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE DAdvise(FORMATETC*, DWORD, IAdviseSink*, DWORD*) override { + return OLE_E_ADVISENOTSUPPORTED; + } + HRESULT STDMETHODCALLTYPE DUnadvise(DWORD) override { return OLE_E_ADVISENOTSUPPORTED; } + HRESULT STDMETHODCALLTYPE EnumDAdvise(IEnumSTATDATA**) override { + return OLE_E_ADVISENOTSUPPORTED; + } + + private: + LONG refs_ = 1; +}; + +LRESULT CALLBACK TestWndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp) { + return DefWindowProcW(hwnd, msg, wp, lp); +} + +} // namespace + +int main() { + std::mutex ready_mutex; + std::condition_variable ready_cv; + HWND hwnd = nullptr; + DWORD platform_tid = 0; + std::atomic stop_platform{false}; + + // Thread 1: Platform/UI thread owning the HWND and pumping Win32 messages. + std::thread platform_thread([&] { + OleInitialize(nullptr); + + WNDCLASSW wc = {}; + wc.lpfnWndProc = TestWndProc; + wc.hInstance = GetModuleHandleW(nullptr); + wc.lpszClassName = L"NativeAPIIssue57DropTargetTest"; + RegisterClassW(&wc); + + HWND created = CreateWindowExW(0, wc.lpszClassName, L"DropTarget Test", WS_OVERLAPPEDWINDOW, + 100, 100, 400, 300, nullptr, nullptr, wc.hInstance, nullptr); + ShowWindow(created, SW_SHOWNOACTIVATE); + UpdateWindow(created); + + { + std::lock_guard lock(ready_mutex); + hwnd = created; + platform_tid = GetCurrentThreadId(); + } + ready_cv.notify_all(); + + MSG msg = {}; + while (!stop_platform.load(std::memory_order_acquire)) { + while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + Sleep(5); + } + + DestroyWindow(created); + UnregisterClassW(wc.lpszClassName, wc.hInstance); + OleUninitialize(); + }); + + { + std::unique_lock lock(ready_mutex); + ready_cv.wait(lock, [&] { return hwnd != nullptr; }); + } + + std::atomic entered_count{0}; + std::atomic moved_count{0}; + std::atomic exited_count{0}; + std::atomic callback_tid{0}; + std::atomic registered{false}; + std::atomic release_isolate{false}; + + // Thread 2: Simulated Dart UI isolate thread (NO Win32 message loop). + std::thread isolate_thread([&] { + auto window = std::make_shared(hwnd); + nativeapi::DropTarget target(window); + target.AddListener([&](const auto&) { + callback_tid.store(GetCurrentThreadId(), std::memory_order_release); + ++entered_count; + }); + target.AddListener([&](const auto&) { ++moved_count; }); + target.AddListener([&](const auto&) { ++exited_count; }); + registered.store(target.IsActive(), std::memory_order_release); + + // Deliberately do NOT pump Win32 messages while the drag source calls in. + while (!release_isolate.load(std::memory_order_acquire)) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + }); + + // Wait for Thread 2 to finish registering DropTarget. + for (int i = 0; i < 200 && !registered.load(std::memory_order_acquire); ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + Check(registered.load(), "DropTarget registered successfully from non-UI thread"); + + // Thread 3: Simulated drag source (explorer.exe) in a separate STA apartment. + // Marshal the registered IDropTarget from the platform thread to Thread 3 + // and invoke DragEnter / DragOver / DragLeave while Thread 2 is not pumping. + IStream* marshaled_stream = nullptr; + { + std::mutex m; + std::condition_variable cv; + bool done = false; + nativeapi::detail::PostToThread(platform_tid, [&] { + auto* raw_target = + reinterpret_cast(GetPropW(hwnd, L"OleDropTargetInterface")); + if (raw_target) { + CoMarshalInterThreadInterfaceInStream(IID_IDropTarget, raw_target, &marshaled_stream); + } + { + std::lock_guard lk(m); + done = true; + } + cv.notify_one(); + }); + std::unique_lock lk(m); + cv.wait_for(lk, std::chrono::seconds(5), [&] { return done; }); + } + Check(marshaled_stream != nullptr, "OleDropTargetInterface registered on HWND"); + + std::atomic source_done{false}; + HRESULT enter_hr = E_FAIL; + HRESULT over_hr = E_FAIL; + HRESULT leave_hr = E_FAIL; + DWORD enter_effect = 0; + DWORD over_effect = 0; + + std::thread source_thread([&] { + OleInitialize(nullptr); + IDropTarget* proxy = nullptr; + if (marshaled_stream && + SUCCEEDED(CoGetInterfaceAndReleaseStream(marshaled_stream, IID_IDropTarget, + reinterpret_cast(&proxy))) && + proxy) { + auto* data = new DummyTextDataObject(); + enter_effect = DROPEFFECT_COPY; + enter_hr = proxy->DragEnter(data, MK_LBUTTON, POINTL{150, 150}, &enter_effect); + over_effect = DROPEFFECT_COPY; + over_hr = proxy->DragOver(MK_LBUTTON, POINTL{180, 180}, &over_effect); + leave_hr = proxy->DragLeave(); + data->Release(); + proxy->Release(); + } + OleUninitialize(); + source_done.store(true, std::memory_order_release); + }); + + // If DropTarget had been registered in Thread 2's unpumped STA, source_thread + // would deadlock forever here. With the fix, it completes in milliseconds. + for (int i = 0; i < 300 && !source_done.load(std::memory_order_acquire); ++i) { + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + Check(source_done.load(), "cross-apartment DragEnter/DragOver/DragLeave completed without freezing"); + Check(SUCCEEDED(enter_hr) && enter_effect == DROPEFFECT_COPY, "DragEnter accepted copy"); + Check(SUCCEEDED(over_hr) && over_effect == DROPEFFECT_COPY, "DragOver accepted copy"); + Check(SUCCEEDED(leave_hr), "DragLeave succeeded"); + Check(entered_count.load() == 1, "DropTargetEnteredEvent delivered"); + Check(moved_count.load() == 1, "DropTargetMovedEvent delivered"); + Check(exited_count.load() == 1, "DropTargetExitedEvent delivered"); + Check(callback_tid.load() == platform_tid, "IDropTarget callbacks ran on platform thread"); + + release_isolate.store(true, std::memory_order_release); + if (source_thread.joinable()) source_thread.join(); + if (isolate_thread.joinable()) isolate_thread.join(); + + // Verify DropTarget revoked its registration on teardown. + { + std::mutex m; + std::condition_variable cv; + bool done = false; + HANDLE remaining = nullptr; + nativeapi::detail::PostToThread(platform_tid, [&] { + remaining = GetPropW(hwnd, L"OleDropTargetInterface"); + { + std::lock_guard lk(m); + done = true; + } + cv.notify_one(); + }); + std::unique_lock lk(m); + cv.wait_for(lk, std::chrono::seconds(5), [&] { return done; }); + Check(remaining == nullptr, "RevokeDragDrop cleaned up on platform thread"); + } + + stop_platform.store(true, std::memory_order_release); + if (platform_thread.joinable()) platform_thread.join(); + + if (g_failures == 0) { + std::printf("PASS: drop_target_ui_thread_windows_test\n"); + } + return g_failures == 0 ? 0 : 1; +}