#include "native_file_drop.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include namespace { using Value = flutter::EncodableValue; using Map = flutter::EncodableMap; using List = flutter::EncodableList; using Channel = flutter::MethodChannel; struct Region { double x; double y; double width; double height; std::optional> allowed_extensions; std::optional maximum_file_count; bool Contains(double px, double py) const { return px >= x && py >= y && px < x + width && py < y + height; } }; std::optional Number(const Map& map, const char* key) { const auto entry = map.find(Value(key)); if (entry == map.end()) return std::nullopt; const auto& value = entry->second; if (const auto* n = std::get_if(&value)) return *n; if (const auto* n = std::get_if(&value)) return *n; if (const auto* n = std::get_if(&value)) { return static_cast(*n); } return std::nullopt; } std::optional ReadRegion(const Value* value) { const auto* map = value ? std::get_if(value) : nullptr; if (!map) return std::nullopt; const auto x = Number(*map, "x"); const auto y = Number(*map, "y"); const auto w = Number(*map, "width"); const auto h = Number(*map, "height"); if (!x || !y || !w || !h || !std::isfinite(*x) || !std::isfinite(*y) || !std::isfinite(*w) || !std::isfinite(*h) || *w <= 0 || *h <= 0) { return std::nullopt; } const auto extensions = map->find(Value("allowedExtensions")); const auto count = map->find(Value("maximumFileCount")); if (extensions == map->end() || count == map->end()) return std::nullopt; Region region{*x, *y, *w, *h, std::nullopt, std::nullopt}; if (!std::holds_alternative(extensions->second)) { const auto* values = std::get_if(&extensions->second); if (!values) return std::nullopt; region.allowed_extensions.emplace(); for (const auto& entry : *values) { const auto* extension = std::get_if(&entry); if (!extension || extension->empty()) return std::nullopt; region.allowed_extensions->push_back(*extension); } } if (!std::holds_alternative(count->second)) { if (const auto* count32 = std::get_if(&count->second)) { region.maximum_file_count = *count32; } else if (const auto* count64 = std::get_if(&count->second)) { region.maximum_file_count = *count64; } else { return std::nullopt; } if (*region.maximum_file_count <= 0) return std::nullopt; } return region; } std::string Utf8(const std::wstring& text) { const int count = static_cast(text.size()); const int size = WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, text.data(), count, nullptr, 0, nullptr, nullptr); if (size <= 0) return {}; std::string result(static_cast(size), '\0'); if (WideCharToMultiByte(CP_UTF8, WC_ERR_INVALID_CHARS, text.data(), count, result.data(), size, nullptr, nullptr) != size) { return {}; } return result; } List ReadFiles(IDataObject* data) { List files; if (!data) return files; // Only existing file references are accepted. Virtual file descriptors and // promised contents are not existing local file references. FORMATETC format{CF_HDROP, nullptr, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; STGMEDIUM medium{}; if (FAILED(data->GetData(&format, &medium))) return files; if (medium.tymed == TYMED_HGLOBAL && medium.hGlobal) { const auto drop = static_cast(medium.hGlobal); const UINT count = DragQueryFileW(drop, 0xFFFFFFFF, nullptr, 0); for (UINT i = 0; i < count; ++i) { const UINT size = DragQueryFileW(drop, i, nullptr, 0); std::vector buffer(static_cast(size) + 1); if (size == 0 || DragQueryFileW(drop, i, buffer.data(), size + 1) != size) { files.clear(); break; } const DWORD attributes = GetFileAttributesW(buffer.data()); const auto path = Utf8(std::wstring(buffer.data(), size)); if (path.empty() || attributes == INVALID_FILE_ATTRIBUTES || (attributes & FILE_ATTRIBUTE_DIRECTORY) != 0) { files.clear(); break; } files.emplace_back(Map{{Value("path"), Value(path)}}); } } ReleaseStgMedium(&medium); return files; } bool Accepts(const Region& region, const List& files) { if (files.empty() || (region.maximum_file_count && files.size() > static_cast(*region.maximum_file_count))) { return false; } if (!region.allowed_extensions) return true; for (const auto& entry : files) { const auto& file = std::get(entry); const auto& path = std::get(file.at(Value("path"))); const auto separator = path.find_last_of("/\\"); const auto dot = path.find_last_of('.'); if (dot == std::string::npos || (separator != std::string::npos && dot <= separator)) return false; auto extension = path.substr(dot + 1); for (char& c : extension) { if (c >= 'A' && c <= 'Z') c = static_cast(c + ('a' - 'A')); } const auto& allowed = *region.allowed_extensions; if (std::find(allowed.begin(), allowed.end(), extension) == allowed.end()) { return false; } } return true; } } // namespace class NativeFileDrop::Target : public IDropTarget { public: Target(HWND view, flutter::BinaryMessenger* messenger) : view_(view), messenger_(messenger) { manager_ = std::make_unique(messenger, "cutdex_native/file_drop", &flutter::StandardMethodCodec::GetInstance()); manager_->SetMethodCallHandler([this](const auto& call, auto result) { const auto* args = call.arguments(); const auto* map = args ? std::get_if(args) : nullptr; if (call.method_name() != "ensureRegion" || !map) { result->NotImplemented(); return; } const auto entry = map->find(Value("id")); const auto* id = entry == map->end() ? nullptr : std::get_if(&entry->second); if (!id || id->empty()) { result->Error("invalid_arguments", "Expected a region id"); return; } if (ids_.find(*id) == ids_.end()) { const size_t i = channels_.size(); ids_[*id] = i; regions_.emplace_back(); channels_.push_back(std::make_unique(messenger_, "cutdex_native/file_drop/" + *id, &flutter::StandardMethodCodec::GetInstance())); channels_[i]->SetMethodCallHandler([this, i](const auto& call, auto result) { if (call.method_name() == "setRegion") { regions_[i] = ReadRegion(call.arguments()); if (active_ == static_cast(i) && (!regions_[i] || !Accepts(*regions_[i], files_))) LeaveRegion(); result->Success(); } else if (call.method_name() == "release") { result->Success(); } else { result->NotImplemented(); } }); } result->Success(); }); } virtual ~Target() = default; void Detach() { LeaveRegion(); manager_->SetMethodCallHandler(nullptr); for (auto& channel : channels_) channel->SetMethodCallHandler(nullptr); } HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, void** object) override { if (!object) return E_POINTER; *object = nullptr; if (IsEqualIID(iid, IID_IUnknown) || IsEqualIID(iid, IID_IDropTarget)) { *object = static_cast(this); AddRef(); return S_OK; } return E_NOINTERFACE; } ULONG STDMETHODCALLTYPE AddRef() override { return ++references_; } ULONG STDMETHODCALLTYPE Release() override { const ULONG remaining = --references_; if (remaining == 0) delete this; return remaining; } HRESULT STDMETHODCALLTYPE DragEnter(IDataObject* data, DWORD, POINTL point, DWORD* effect) override { if (!effect) return E_POINTER; Reset(); files_ = ReadFiles(data); Update(point, (*effect & DROPEFFECT_COPY) != 0); *effect = active_ >= 0 ? DROPEFFECT_COPY : DROPEFFECT_NONE; return S_OK; } HRESULT STDMETHODCALLTYPE DragOver(DWORD, POINTL point, DWORD* effect) override { if (!effect) return E_POINTER; Update(point, (*effect & DROPEFFECT_COPY) != 0); *effect = active_ >= 0 ? DROPEFFECT_COPY : DROPEFFECT_NONE; return S_OK; } HRESULT STDMETHODCALLTYPE DragLeave() override { Reset(); return S_OK; } HRESULT STDMETHODCALLTYPE Drop(IDataObject* data, DWORD, POINTL point, DWORD* effect) override { if (!effect) return E_POINTER; // Confirm the same paths still exist when the user releases the mouse. const auto current = ReadFiles(data); Update(point, (*effect & DROPEFFECT_COPY) != 0 && current == files_); if (active_ >= 0) { Emit("drop"); *effect = DROPEFFECT_COPY; // Dart keeps this session until its asynchronous import has completed. // Do not send exit here: asynchronous file preparation can still be pending. active_ = -1; files_.clear(); } else { *effect = DROPEFFECT_NONE; Reset(); } return S_OK; } private: void Update(POINTL point, bool copy_allowed) { POINT client{point.x, point.y}; if (!ScreenToClient(view_, &client)) { LeaveRegion(); return; } const UINT dpi = FlutterDesktopGetDpiForMonitor( MonitorFromWindow(view_, MONITOR_DEFAULTTONEAREST)); const double scale = dpi > 0 ? dpi / 96.0 : 1.0; x_ = client.x / scale; y_ = client.y / scale; int next = -1; if (copy_allowed && !files_.empty()) { for (int i = static_cast(regions_.size()) - 1; i >= 0; --i) { if (regions_[i] && regions_[i]->Contains(x_, y_) && Accepts(*regions_[i], files_)) { next = i; break; } } } if (next != active_) { LeaveRegion(); active_ = next; if (active_ >= 0) { ++session_; Emit("enter"); } } else if (active_ >= 0) { Emit("move"); } } void Emit(const char* phase) { if (active_ < 0) return; const auto i = static_cast(active_); const auto& region = regions_[i]; const bool include_files = std::string(phase) == "enter" || std::string(phase) == "drop"; channels_[i]->InvokeMethod("event", std::make_unique(Map{ {Value("phase"), Value(phase)}, {Value("session"), Value(session_)}, {Value("x"), Value(x_ - (region ? region->x : 0))}, {Value("y"), Value(y_ - (region ? region->y : 0))}, {Value("files"), Value(include_files ? files_ : List{})}, })); } void LeaveRegion() { Emit("exit"); active_ = -1; } void Reset() { LeaveRegion(); files_.clear(); } std::atomic references_{1}; HWND view_; flutter::BinaryMessenger* messenger_; std::unique_ptr manager_; std::map ids_; std::vector> channels_; std::vector> regions_; List files_; int active_ = -1; int64_t session_ = 0; double x_ = 0; double y_ = 0; }; NativeFileDrop::NativeFileDrop(HWND view, flutter::BinaryMessenger* messenger) : view_(view) { // CoInitializeEx alone does not initialize OLE drag-and-drop support. ole_initialized_ = SUCCEEDED(OleInitialize(nullptr)); if (!ole_initialized_) { OutputDebugStringW(L"Cutdex: OLE file drop initialization failed.\n"); return; } target_ = new Target(view, messenger); registered_ = SUCCEEDED(RegisterDragDrop(view, target_)); if (!registered_) { OutputDebugStringW(L"Cutdex: native file drop registration failed.\n"); } } NativeFileDrop::~NativeFileDrop() { if (registered_) RevokeDragDrop(view_); if (target_) { target_->Detach(); target_->Release(); } if (ole_initialized_) OleUninitialize(); }