Files
lingjhf 27e77fff39 feat: initial Cutdex application
Add the Flutter video editing application with project management, media
import, timeline editing, preview, AI assistance, diagnostics and settings.

Include shared UI and native host packages, platform runners, application
tests and release tooling.

Provide usage and contribution guides, the MIT license and third-party
notices. Exclude local credentials, build outputs and validation data.
2026-10-05 23:36:23 +08:00

368 lines
12 KiB
C++

#include "native_file_drop.h"
#include <flutter/encodable_value.h>
#include <flutter/method_channel.h>
#include <flutter/standard_method_codec.h>
#include <flutter_windows.h>
#include <ole2.h>
#include <shellapi.h>
#include <algorithm>
#include <map>
#include <atomic>
#include <cmath>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <vector>
namespace {
using Value = flutter::EncodableValue;
using Map = flutter::EncodableMap;
using List = flutter::EncodableList;
using Channel = flutter::MethodChannel<Value>;
struct Region {
double x;
double y;
double width;
double height;
std::optional<std::vector<std::string>> allowed_extensions;
std::optional<int64_t> maximum_file_count;
bool Contains(double px, double py) const {
return px >= x && py >= y && px < x + width && py < y + height;
}
};
std::optional<double> 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<double>(&value)) return *n;
if (const auto* n = std::get_if<int32_t>(&value)) return *n;
if (const auto* n = std::get_if<int64_t>(&value)) {
return static_cast<double>(*n);
}
return std::nullopt;
}
std::optional<Region> ReadRegion(const Value* value) {
const auto* map = value ? std::get_if<Map>(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<std::monostate>(extensions->second)) {
const auto* values = std::get_if<List>(&extensions->second);
if (!values) return std::nullopt;
region.allowed_extensions.emplace();
for (const auto& entry : *values) {
const auto* extension = std::get_if<std::string>(&entry);
if (!extension || extension->empty()) return std::nullopt;
region.allowed_extensions->push_back(*extension);
}
}
if (!std::holds_alternative<std::monostate>(count->second)) {
if (const auto* count32 = std::get_if<int32_t>(&count->second)) {
region.maximum_file_count = *count32;
} else if (const auto* count64 = std::get_if<int64_t>(&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<int>(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_t>(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<HDROP>(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<wchar_t> buffer(static_cast<size_t>(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<uint64_t>(*region.maximum_file_count))) {
return false;
}
if (!region.allowed_extensions) return true;
for (const auto& entry : files) {
const auto& file = std::get<Map>(entry);
const auto& path = std::get<std::string>(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<char>(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<Channel>(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<Map>(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<std::string>(&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<Channel>(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<int>(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<IDropTarget*>(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<int>(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<size_t>(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<Value>(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<ULONG> references_{1};
HWND view_;
flutter::BinaryMessenger* messenger_;
std::unique_ptr<Channel> manager_;
std::map<std::string, size_t> ids_;
std::vector<std::unique_ptr<Channel>> channels_;
std::vector<std::optional<Region>> 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();
}