Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 164 additions & 35 deletions src/platform/windows/drop_target_windows.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@
#include <shlobj.h>
// clang-format on

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <vector>
Expand All @@ -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 {
Expand Down Expand Up @@ -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 {
Expand All @@ -112,55 +120,119 @@ 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;
}

HRESULT STDMETHODCALLTYPE Drop(IDataObject* data,
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<bool> 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 <typename Work>
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<SyncState>();
if (!detail::PostToThread(thread_id, [sync, work = std::move(work)]() mutable {
const bool ok = work();
{
std::lock_guard<std::mutex> lock(sync->mutex);
sync->result = ok;
sync->done = true;
}
sync->ready.notify_one();
})) {
return false;
}
std::unique_lock<std::mutex> 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 {
Expand All @@ -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) {
Expand All @@ -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<std::atomic<bool>> alive = std::make_shared<std::atomic<bool>>(true);
HWND hwnd = nullptr;
DWORD owner_thread_id = 0;
DropTargetCom* com = nullptr;
std::optional<ScopedOleInitialize> ole;
double cached_scale = 1.0;
ULONGLONG last_move_emit_tick = 0;
Point last_position{0, 0};
};

Expand All @@ -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
4 changes: 4 additions & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Loading