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.
This commit is contained in:
lingjhf committed 2026-10-05 23:36:23 +08:00
commit 27e77fff39
718 files changed
+183958

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.flutter-plugins-dependencies
/build/
/coverage/
+39
View File
@@ -0,0 +1,39 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "6a19cca56475dbfba1478ee68d7bd0c2ef891da1"
channel: "stable"
project_type: plugin
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
- platform: android
create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
- platform: ios
create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
- platform: macos
create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
- platform: windows
create_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
base_revision: 6a19cca56475dbfba1478ee68d7bd0c2ef891da1
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
+65
View File
@@ -0,0 +1,65 @@
# cutdex_native
Cutdex workspace 内部 Flutter 原生插件,暂不发布。
| 能力 | macOS | Windows |
| --- | --- | --- |
| 窗口标题栏、拖动区域与关闭请求拦截 | 支持 | 支持 |
| 本地文件拖放区域 | 支持 | 支持 |
| 原生上下文菜单 | 支持 | 由 UI 包回退为 Flutter 菜单 |
| 原生窗口全屏会话 | 支持 | 未提供 |
Android、iOS 注册设备信息查询;窗口、拖放、菜单与全屏能力仍由对应桌面平台提供。
## 设备信息
`NativeDeviceInfo.read()` 在 Android 返回最大显示区域的最短边(逻辑像素),在 iOS 返回 `NativeInterfaceIdiom`。无法查询时返回 `null`。插件不使用当前应用窗口大小,也不决定手机、平板或桌面布局;分类阈值、回退规则与状态装配由应用维护。
## 窗口
Dart 使用 `WindowChromeSession`、`HeaderControlRegion` 与 `WindowHeaderLayout`。关闭请求通过回调交给应用处理,插件不决定项目保存、路由、退出行为或应用最小窗口尺寸。坐标上报统一使用 `NativeBoundsReporter`,按绘制变换计算窗口逻辑坐标中的外接矩形。
macOS 宿主窗口继承 `CutdexNativeWindow`,导入 `cutdex_native` 后按 Flutter 常规流程注册插件。该窗口类负责 AppKit 响应链与标题栏手势,宿主只负责创建 Flutter 控制器和应用生命周期接线。Windows 由插件注册自动接入。
## 文件拖放
`NativeFileDropRegion` 接收稳定的 `regionId`、`NativeDropConfiguration`、启用状态与回调,回调中的文件是原始路径列表。扩展名白名单与数量上限由调用方提供。
两端均拒绝目录和不存在的文件,并在落下时重新检查文件引用。
`NativeDropConfiguration` 拷贝并规范化白名单,按值比较;输入列表的后续修改不会改变规则。无约束配置使用 `NativeDropConfiguration.unrestricted`。标题栏命中区域与拖放区域随 `TickerMode` 停用和恢复;隐藏页面拒绝迟到的拖放事件。
需要拖动位置和自定义异步准备流程时,使用 `NativeFileDropConnection`。其事件包含阶段、会话编号、区域内坐标和路径;调用方在文件使用完成后调用 `release`。macOS 的安全作用域权限持续到释放,销毁区域不会提前释放正在处理的拖放会话。
同一 `regionId` 的替换连接取得事件所有权,旧连接不能清除新区域或修改其选项。连接销毁后不能再次绑定,但仍可释放未完成文件操作的权限。区域标识用于重复使用同一目的地,不应每帧生成新标识。macOS 拖动源图像是否隐藏由 `hidesSourceImage` 控制。
插件不导入媒体,不识别项目、时间线或聊天,也不创建临时素材副本。
## 菜单与全屏
`NativeContextMenu.show` 接收 `NativeMenuEntry` 和位置,返回选中的操作编号;应用或 UI 包负责执行操作。`NativeFullscreenSession` 接收退出回调,按顺序处理窗口全屏请求。使用 `dispose(exitFullscreen: true)` 在未被替换时恢复窗口;恢复会等待正在进行的转换完成。预览内容和布局由应用管理。
在应用根目录执行 `flutter pub get`;在本包目录执行 `flutter test`。真实窗口与系统拖放还需在对应桌面平台验证。
## 原生回归
以下命令在应用根目录执行,先退出占用同一构建目录的应用。
macOS 标题栏手势使用真实 AppKit 响应链,文件引用策略使用临时文件与目录:
```sh
flutter build macos --debug --flavor development
bash packages/cutdex_native/tool/macos/test_header_control_gestures.sh
bash packages/cutdex_native/tool/macos/test_file_drop_policy.sh
```
Windows 标题栏回归验证真实 HWND、命中区域、最大化、DPI 与标题栏恢复;先准备 Flutter C++ wrapper:
```sh
flutter build windows --debug --flavor development
cmake -S packages/cutdex_native/tool/windows/window_chrome_tests -B build/window_chrome_tests -A x64
cmake --build build/window_chrome_tests --config Release
ctest --test-dir build/window_chrome_tests -C Release --output-on-failure
```
原生回归不替代 Finder/Explorer 的真实文件拖放验收。
@@ -0,0 +1,12 @@
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- build/**
- windows/**
- macos/**
- android/**
- ios/**
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
@@ -0,0 +1,9 @@
*.iml
.gradle
/local.properties
/.idea/workspace.xml
/.idea/libraries
.DS_Store
/build
/captures
.cxx
@@ -0,0 +1,53 @@
group = "dev.cutdex.cutdex_native"
version = "0.1.0"
buildscript {
val kotlinVersion = "2.4.0"
repositories {
google()
mavenCentral()
}
dependencies {
classpath("com.android.tools.build:gradle:9.1.0")
classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion")
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
plugins {
id("com.android.library")
}
android {
namespace = "dev.cutdex.cutdex_native"
compileSdk = 36
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
sourceSets {
getByName("main") {
java.srcDirs("src/main/kotlin")
}
}
defaultConfig {
minSdk = 24
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
@@ -0,0 +1 @@
rootProject.name = "cutdex_native"
@@ -0,0 +1 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
@@ -0,0 +1,84 @@
package dev.cutdex.cutdex_native
import android.app.Activity
import android.content.Context
import android.os.Build
import android.util.DisplayMetrics
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
class CutdexNativePlugin : FlutterPlugin, ActivityAware, MethodChannel.MethodCallHandler {
private var channel: MethodChannel? = null
private var activity: Activity? = null
private var context: Context? = null
override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
context = binding.applicationContext
channel = MethodChannel(binding.binaryMessenger, "cutdex_native/device_info").also {
it.setMethodCallHandler(this)
}
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
if (call.method == "getApplicationInfo") {
val host = context ?: return result.error("unavailable", "No application context.", null)
try {
@Suppress("DEPRECATION")
val info = host.packageManager.getPackageInfo(host.packageName, 0)
@Suppress("DEPRECATION")
val build = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) info.longVersionCode else info.versionCode.toLong()
result.success(mapOf("appVersion" to (info.versionName ?: "unknown"), "appBuild" to build.toString()))
} catch (error: Exception) {
result.error("unavailable", "Application metadata unavailable.", null)
}
return
}
if (call.method != "getDeviceInfo") {
result.notImplemented()
return
}
val host = activity
if (host == null) {
result.error("unavailable", "No activity is attached.", null)
return
}
// Maximum bounds do not shrink with the app's split-screen window.
val shortestSideDp = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val bounds = host.windowManager.maximumWindowMetrics.bounds
minOf(bounds.width(), bounds.height()) / host.resources.displayMetrics.density
} else {
@Suppress("DEPRECATION")
val metrics = DisplayMetrics().also {
host.windowManager.defaultDisplay.getRealMetrics(it)
}
minOf(metrics.widthPixels, metrics.heightPixels) / metrics.density
}
result.success(mapOf("displayShortestSideDp" to shortestSideDp.toDouble()))
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivityForConfigChanges() {
activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
activity = binding.activity
}
override fun onDetachedFromActivity() {
activity = null
}
override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
channel?.setMethodCallHandler(null)
channel = null
activity = null
context = null
}
}
+38
View File
@@ -0,0 +1,38 @@
.idea/
.vagrant/
.sconsign.dblite
.svn/
.DS_Store
*.swp
profile
DerivedData/
build/
GeneratedPluginRegistrant.h
GeneratedPluginRegistrant.m
.generated/
*.pbxuser
*.mode1v3
*.mode2v3
*.perspectivev3
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3
xcuserdata
*.moved-aside
*.pyc
*sync/
Icon?
.tags*
/Flutter/Generated.xcconfig
/Flutter/ephemeral/
/Flutter/flutter_export_environment.sh
@@ -0,0 +1,15 @@
Pod::Spec.new do |s|
s.name = 'cutdex_native'
s.version = '0.1.0'
s.summary = 'Cutdex native device information.'
s.description = 'Native device facts for application layout policy.'
s.homepage = 'https://github.com/lingjhf/cutdex'
s.license = { :type => 'MIT', :file => '../../../LICENSE' }
s.authors = 'Cutdex contributors'
s.source = { :path => '.' }
s.source_files = 'cutdex_native/Sources/cutdex_native/**/*.swift'
s.dependency 'Flutter'
s.platform = :ios, '15.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.swift_version = '5.0'
end
@@ -0,0 +1,15 @@
// swift-tools-version: 5.9
import PackageDescription
let package = Package(
name: "cutdex_native",
platforms: [.iOS("15.0")],
products: [.library(name: "cutdex-native", targets: ["cutdex_native"])],
dependencies: [.package(name: "FlutterFramework", path: "../FlutterFramework")],
targets: [
.target(
name: "cutdex_native",
dependencies: [.product(name: "FlutterFramework", package: "FlutterFramework")]
)
]
)
@@ -0,0 +1,31 @@
import Flutter
import UIKit
public class CutdexNativePlugin: NSObject, FlutterPlugin {
public static func register(with registrar: FlutterPluginRegistrar) {
let channel = FlutterMethodChannel(
name: "cutdex_native/device_info",
binaryMessenger: registrar.messenger()
)
registrar.addMethodCallDelegate(CutdexNativePlugin(), channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getApplicationInfo" {
result(["appVersion": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown",
"appBuild": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"])
return
}
guard call.method == "getDeviceInfo" else {
result(FlutterMethodNotImplemented)
return
}
let idiom: String
switch UIDevice.current.userInterfaceIdiom {
case .pad: idiom = "pad"
case .mac: idiom = "mac"
default: idiom = "phone"
}
result(["interfaceIdiom": idiom])
}
}
@@ -0,0 +1,9 @@
export 'src/bounds_reporter.dart';
export 'src/header_control_region.dart';
export 'src/window_chrome_session.dart';
export 'src/window_header_layout.dart';
export 'src/fullscreen.dart';
export 'src/file_drop.dart';
export 'src/file_drop_region.dart';
export 'src/context_menu.dart';
export 'src/device_info.dart';
@@ -0,0 +1,63 @@
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// Reports laid-out window coordinates after layout and movement.
class NativeBoundsReporter extends SingleChildRenderObjectWidget {
const NativeBoundsReporter({
super.key,
required this.onBounds,
required super.child,
});
final ValueChanged<Rect> onBounds;
@override
RenderObject createRenderObject(BuildContext context) =>
_RenderBoundsReporter(onBounds);
@override
void updateRenderObject(
BuildContext context,
covariant RenderObject renderObject,
) {
(renderObject as _RenderBoundsReporter).updateCallback(onBounds);
}
}
class _RenderBoundsReporter extends RenderProxyBox {
_RenderBoundsReporter(this.onBounds);
ValueChanged<Rect> onBounds;
void updateCallback(ValueChanged<Rect> callback) {
onBounds = callback;
_lastBounds = null;
_scheduleReport();
}
bool _scheduled = false;
Rect? _lastBounds;
void _scheduleReport() {
if (_scheduled || !attached) return;
_scheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false;
if (!attached) return;
if (hasSize) {
final bounds = MatrixUtils.transformRect(
getTransformTo(null),
Offset.zero & size,
);
if (bounds != _lastBounds) {
_lastBounds = bounds;
onBounds(bounds);
}
}
// Ancestors can move retained layers without laying out or repainting
// this box. Observe the next frame without requesting an idle frame.
_scheduleReport();
});
}
@override
void attach(PipelineOwner owner) {
super.attach(owner);
_lastBounds = null;
_scheduleReport();
}
}
@@ -0,0 +1,58 @@
import 'package:flutter/services.dart';
class NativeMenuEntry {
const NativeMenuEntry({
required String this.label,
this.id,
this.enabled = true,
this.selected = false,
this.children,
}) : separator = false;
const NativeMenuEntry.separator()
: separator = true,
label = null,
id = null,
enabled = false,
selected = false,
children = null;
final String? label;
final int? id;
final bool separator;
final bool enabled;
final bool selected;
final List<NativeMenuEntry>? children;
Map<String, Object?> _encode() => separator
? {'separator': true}
: {
'label': label,
if (id != null) 'id': id,
'enabled': enabled,
'selected': selected,
if (children != null)
'children': [for (final child in children!) child._encode()],
};
}
class NativeMenuUnavailableException implements Exception {
const NativeMenuUnavailableException();
}
abstract final class NativeContextMenu {
static Future<int?> show(List<NativeMenuEntry> items, Offset position) async {
try {
return await const MethodChannel('cutdex_native/context_menu')
.invokeMethod<int>('show', {
'x': position.dx,
'y': position.dy,
'items': [for (final item in items) item._encode()],
});
} on MissingPluginException {
throw const NativeMenuUnavailableException();
} on PlatformException {
throw const NativeMenuUnavailableException();
}
}
}
@@ -0,0 +1,55 @@
import 'package:flutter/services.dart';
/// The interface idiom reported by iOS.
enum NativeInterfaceIdiom { phone, pad, mac }
/// Device facts used by the caller to select its layout policy.
final class NativeDeviceInfo {
const NativeDeviceInfo({this.interfaceIdiom, this.displayShortestSideDp});
/// The iOS interface idiom, independent of the current window size.
final NativeInterfaceIdiom? interfaceIdiom;
/// The shortest side of Android's maximum display bounds in logical pixels.
final double? displayShortestSideDp;
static const _channel = MethodChannel('cutdex_native/device_info');
/// The installed application's version and build, supplied by the host.
static Future<Map<String, String>> readApplicationInfo() async {
final result = await _channel.invokeMapMethod<String, String>(
'getApplicationInfo',
);
return Map.unmodifiable(result ?? const <String, String>{});
}
/// Reads device facts on Android and iOS.
///
/// Returns `null` when the host cannot provide usable information.
/// The caller decides how to classify the device and how to fall back.
static Future<NativeDeviceInfo?> read() async {
try {
final result = await _channel.invokeMethod<Object?>('getDeviceInfo');
if (result is! Map) return null;
final idiom = switch (result['interfaceIdiom']) {
'phone' => NativeInterfaceIdiom.phone,
'pad' => NativeInterfaceIdiom.pad,
'mac' => NativeInterfaceIdiom.mac,
_ => null,
};
final value = result['displayShortestSideDp'];
final shortestSide = value is num && value.isFinite && value > 0
? value.toDouble()
: null;
if (idiom == null && shortestSide == null) return null;
return NativeDeviceInfo(
interfaceIdiom: idiom,
displayShortestSideDp: shortestSide,
);
} on MissingPluginException {
return null;
} on PlatformException {
return null;
}
}
}
@@ -0,0 +1,178 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'native_channel_binding.dart';
class NativeDropConfiguration {
NativeDropConfiguration({
Iterable<String>? allowedExtensions,
this.maximumFileCount,
}) : allowedExtensions = allowedExtensions == null
? null
: List.unmodifiable(
allowedExtensions
.map((extension) => extension.toLowerCase())
.toSet()
.toList()
..sort(),
) {
if (maximumFileCount != null && maximumFileCount! <= 0) {
throw ArgumentError.value(
maximumFileCount,
'maximumFileCount',
'Must be positive',
);
}
if (this.allowedExtensions?.any((extension) => extension.isEmpty) == true) {
throw ArgumentError.value(
allowedExtensions,
'allowedExtensions',
'Extensions must not be empty',
);
}
}
const NativeDropConfiguration._unrestricted()
: allowedExtensions = null,
maximumFileCount = null;
static const unrestricted = NativeDropConfiguration._unrestricted();
final List<String>? allowedExtensions;
final int? maximumFileCount;
@override
bool operator ==(Object other) =>
other is NativeDropConfiguration &&
maximumFileCount == other.maximumFileCount &&
listEquals(allowedExtensions, other.allowedExtensions);
@override
int get hashCode => Object.hash(
maximumFileCount,
allowedExtensions == null ? null : Object.hashAll(allowedExtensions!),
);
bool accepts(List<String> paths) =>
paths.isNotEmpty &&
(maximumFileCount == null || paths.length <= maximumFileCount!) &&
paths.every((path) {
if (path.isEmpty) return false;
final extension = p.extension(path).toLowerCase().replaceFirst('.', '');
return allowedExtensions == null ||
allowedExtensions!.contains(extension);
});
Map<String, Object?> regionArguments(Rect bounds) => {
'x': bounds.left,
'y': bounds.top,
'width': bounds.width,
'height': bounds.height,
'allowedExtensions': allowedExtensions,
'maximumFileCount': maximumFileCount,
};
}
enum NativeFileDropPhase { enter, move, exit, drop }
class NativeFileDropEvent {
const NativeFileDropEvent({
required this.phase,
required this.session,
required this.position,
required this.paths,
});
final NativeFileDropPhase phase;
final int session;
final Offset position;
final List<String> paths;
}
/// A named drop destination. Keep grants until asynchronous file use finishes.
class NativeFileDropConnection {
NativeFileDropConnection({
required this.regionId,
required this.onEvent,
this.hidesSourceImage = false,
}) : assert(regionId != '');
static const _manager = MethodChannel('cutdex_native/file_drop');
final String regionId;
final bool hidesSourceImage;
final Future<void> Function(NativeFileDropEvent) onEvent;
late final _channel = MethodChannel('cutdex_native/file_drop/$regionId');
late final _binding = NativeChannelBinding(_channel);
bool _disposed = false;
int _revision = 0;
bool get isOwner => !_disposed && _binding.isOwner;
void bind() {
if (_disposed) throw StateError('Cannot bind a disposed drop connection');
_binding.bind((call) async {
if (!isOwner || call.method != 'event') return;
final args = call.arguments as Map;
await onEvent(
NativeFileDropEvent(
phase: NativeFileDropPhase.values.byName(args['phase'] as String),
session: args['session'] as int,
position: Offset(
(args['x'] as num? ?? 0).toDouble(),
(args['y'] as num? ?? 0).toDouble(),
),
paths: [
for (final file in args['files'] as List? ?? const [])
(file as Map)['path'] as String,
],
),
);
});
}
Future<void> setRegion(
Rect? bounds,
NativeDropConfiguration configuration,
) async {
if (!isOwner) return;
final revision = ++_revision;
try {
await _manager.invokeMethod<void>('ensureRegion', {
'id': regionId,
'hidesSourceImage': hidesSourceImage,
});
if (revision != _revision || !isOwner) return;
await _channel.invokeMethod<void>(
'setRegion',
bounds == null ? null : configuration.regionArguments(bounds),
);
} on MissingPluginException {
// Native destinations are available only on registered desktop hosts.
}
}
Future<void> release(int session) =>
_channel.invokeMethod<void>('release', {'session': session});
void dispose() {
if (_disposed) return;
_disposed = true;
++_revision;
if (_binding.unbind()) {
// Callers may still release security-scoped grants after disposal.
unawaited(_clearRegion());
}
}
Future<void> _clearRegion() async {
// Let a replacement bind before clearing native state. Cleanup must not
// register a destination or change its options through the manager.
await Future<void>.value();
if (_binding.hasOwner) return;
try {
await _channel.invokeMethod<void>('setRegion', null);
} on MissingPluginException {
// The native destination may never have been registered.
}
}
}
@@ -0,0 +1,148 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'bounds_reporter.dart';
import 'file_drop.dart';
/// Existing local file references from the macOS and Windows native hosts.
class NativeFileDropRegion extends StatefulWidget {
const NativeFileDropRegion({
super.key,
required this.regionId,
this.configuration = NativeDropConfiguration.unrestricted,
this.hidesSourceImage = false,
required this.enabled,
required this.onEnter,
required this.onExit,
required this.onDrop,
required this.child,
});
final String regionId;
final bool hidesSourceImage;
final NativeDropConfiguration configuration;
final bool enabled;
final ValueChanged<List<String>> onEnter;
final VoidCallback onExit;
final Future<void> Function(List<String>) onDrop;
final Widget child;
@override
State<NativeFileDropRegion> createState() => _RegionState();
}
class _RegionState extends State<NativeFileDropRegion> {
late var connection = createConnection();
NativeFileDropConnection createConnection() => NativeFileDropConnection(
regionId: widget.regionId,
hidesSourceImage: widget.hidesSourceImage,
onEvent: event,
);
Rect? region;
NativeDropConfiguration? reportedPolicy;
int? session;
bool get active => widget.enabled && TickerMode.valuesOf(context).enabled;
@override
void initState() {
super.initState();
connection.bind();
}
@override
void didUpdateWidget(covariant NativeFileDropRegion oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.regionId == oldWidget.regionId &&
widget.hidesSourceImage == oldWidget.hidesSourceImage) {
return;
}
if (session != null) {
unawaited(connection.release(session!));
oldWidget.onExit();
}
connection.dispose();
session = null;
region = null;
reportedPolicy = null;
connection = createConnection()..bind();
}
Future<void> release(int id) => connection.release(id);
Future<void> event(NativeFileDropEvent event) async {
if (!mounted || !connection.isOwner) return;
final owner = connection;
final id = event.session;
if (event.phase == NativeFileDropPhase.exit) {
if (session == id) {
session = null;
widget.onExit();
await release(id);
}
} else if (event.phase == NativeFileDropPhase.enter) {
if (!active || !widget.configuration.accepts(event.paths)) {
await release(id);
return;
}
if (session case final previous? when previous != id) {
widget.onExit();
unawaited(owner.release(previous));
}
session = id;
widget.onEnter(event.paths);
} else if (event.phase == NativeFileDropPhase.drop && session == id) {
// A pending file operation owns its grant independently of the next drag.
session = null;
try {
if (active && widget.configuration.accepts(event.paths)) {
await widget.onDrop(event.paths);
} else {
widget.onExit();
}
} finally {
await owner.release(id);
}
}
}
Future<void> send(Rect? bounds) =>
connection.setRegion(bounds, widget.configuration);
void report(Rect r) {
if (!mounted || !connection.isOwner) return;
final next = active ? r : null;
if (region == next && reportedPolicy == widget.configuration) return;
region = next;
reportedPolicy = widget.configuration;
if (next == null && session != null) {
final id = session!;
session = null;
widget.onExit();
unawaited(release(id));
}
unawaited(send(next));
}
@override
void dispose() {
connection.dispose();
if (session case final id?) unawaited(release(id));
super.dispose();
}
@override
Widget build(BuildContext context) {
TickerMode.valuesOf(context);
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !connection.isOwner) return;
if (!active && session != null) {
final id = session!;
session = null;
widget.onExit();
unawaited(release(id));
region = null;
unawaited(send(null));
} else if (region != null) {
report(region!);
}
});
return NativeBoundsReporter(onBounds: report, child: widget.child);
}
}
@@ -0,0 +1,71 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import 'native_channel_binding.dart';
class NativeFullscreenSession {
NativeFullscreenSession({required this.onExit});
static const _channel = MethodChannel('cutdex_native/fullscreen');
static Future<void>? _request;
final void Function() onExit;
final _binding = NativeChannelBinding(_channel);
bool _disposed = false;
void attach() {
if (_disposed) {
throw StateError('Cannot attach a disposed fullscreen session');
}
_binding.bind((call) async {
if (_binding.isOwner && call.method == 'exited') onExit();
});
}
Future<void> setFullscreen(bool enabled) => _enqueue(enabled);
Future<void> _enqueue(bool enabled, {bool restoring = false}) {
// AppKit completes a request after its window transition. Serialize across
// owners so retiring and newly mounted routes cannot overlap transitions.
Future<void> invoke() async {
if (restoring ? _binding.hasOwner : _disposed || !_binding.isOwner) {
return;
}
await _channel.invokeMethod<void>('setFullscreen', enabled);
}
final previous = _request;
final request = previous == null
? invoke()
: previous.then(
(_) => invoke(),
onError: (Object _, StackTrace _) => invoke(),
);
_request = request;
// A failed transition must not poison the next owner's request queue.
void clear() {
if (identical(_request, request)) _request = null;
}
unawaited(
request.then<void>(
(_) => clear(),
onError: (Object _, StackTrace _) => clear(),
),
);
return request;
}
void dispose({bool exitFullscreen = false}) {
if (_disposed) return;
_disposed = true;
if (_binding.unbind() && exitFullscreen) {
unawaited(
_enqueue(false, restoring: true).catchError((Object error) {
debugPrint('Could not restore native fullscreen: $error');
}),
);
}
}
}
@@ -0,0 +1,57 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'bounds_reporter.dart';
import 'window_chrome_session.dart';
export 'window_chrome_session.dart' show HeaderControlRole;
/// Reports actual Flutter control bounds so native windows drag empty header space.
class HeaderControlRegion extends StatefulWidget {
const HeaderControlRegion({
super.key,
required this.child,
this.role = HeaderControlRole.control,
});
final Widget child;
final HeaderControlRole role;
@override
State<HeaderControlRegion> createState() => _HeaderControlRegionState();
}
class _HeaderControlRegionState extends State<HeaderControlRegion> {
static int _nextId = 0;
late final _id = 'control-${_nextId++}';
Rect? _lastRect;
Future<void> _send(Rect? rect) =>
WindowChromeSession.reportControl(_id, rect, widget.role);
void _report(Rect rect) {
if (!mounted || !WindowChromeSession.supported) return;
final next = TickerMode.valuesOf(context).enabled ? rect : null;
if (next == _lastRect) return;
_lastRect = next;
unawaited(_send(next));
}
@override
void didUpdateWidget(covariant HeaderControlRegion oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.role != widget.role && _lastRect != null) {
unawaited(_send(_lastRect));
}
}
@override
void dispose() {
if (_lastRect != null) unawaited(_send(null));
super.dispose();
}
@override
Widget build(BuildContext context) {
TickerMode.valuesOf(context);
return NativeBoundsReporter(onBounds: _report, child: widget.child);
}
}
@@ -0,0 +1,26 @@
import 'package:flutter/services.dart';
// A replacement widget can bind before Flutter disposes its predecessor.
// Only the current binding may clear the shared channel or native UI state.
class NativeChannelBinding {
NativeChannelBinding(this.channel);
static final _owners = <(BinaryMessenger, String), Object>{};
final MethodChannel channel;
final _token = Object();
(BinaryMessenger, String) get _key => (channel.binaryMessenger, channel.name);
bool get isOwner => identical(_owners[_key], _token);
bool get hasOwner => _owners.containsKey(_key);
void bind(Future<dynamic> Function(MethodCall) handler) {
_owners[_key] = _token;
channel.setMethodCallHandler(handler);
}
bool unbind() {
if (!isOwner) return false;
_owners.remove(_key);
channel.setMethodCallHandler(null);
return true;
}
}
@@ -0,0 +1,167 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
enum WindowCaptionCommand { minimize, toggleMaximize, close }
enum HeaderControlRole { control, maximize }
/// Owns native window chrome while its Flutter owner is active.
class WindowChromeSession extends ChangeNotifier {
WindowChromeSession({required this._headerHeight, this._onCloseRequested});
static const _chrome = MethodChannel('cutdex_native/window');
static const _controls = MethodChannel('cutdex_native/window_controls');
static final _sessions = <WindowChromeSession>[];
static WindowChromeSession? _owner;
static bool get isWindows =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.windows;
static bool get supported =>
!kIsWeb && (defaultTargetPlatform == TargetPlatform.macOS || isWindows);
double _headerHeight;
VoidCallback? _onCloseRequested;
bool _interactive = true;
bool _disposed = false;
int _revision = 0;
bool _integrated = false;
bool _maximized = false;
bool _maximizeHovered = false;
bool get integrated => _integrated;
bool get maximized => _maximized;
bool get maximizeHovered => _maximizeHovered;
void attach() {
if (!supported || _disposed || _sessions.contains(this)) return;
_sessions.add(this);
_activate();
}
void _activate() {
_owner = this;
_chrome.setMethodCallHandler(_handleMethodCall);
unawaited(_enable());
}
void configure({
required double headerHeight,
VoidCallback? onCloseRequested,
}) {
final changed =
_headerHeight != headerHeight ||
(_onCloseRequested == null) != (onCloseRequested == null);
_headerHeight = headerHeight;
_onCloseRequested = onCloseRequested;
if (changed && identical(_owner, this)) unawaited(_enable());
}
void setInteractive(bool interactive) {
if (_interactive == interactive) return;
_interactive = interactive;
if (isWindows && identical(_owner, this)) {
unawaited(_invoke<void>('setHeaderInteractive', interactive));
}
}
Future<void> perform(WindowCaptionCommand command) async {
if (!_disposed && identical(_owner, this)) {
await _invoke<void>(command.name);
}
}
Future<bool> _handleMethodCall(MethodCall call) async {
if (_disposed || !identical(_owner, this)) return false;
switch (call.method) {
case 'windowState':
final state = call.arguments as Map;
final maximized = state['maximized'] == true;
final hovered = state['maximizeHovered'] == true;
if (_maximized != maximized || _maximizeHovered != hovered) {
_maximized = maximized;
_maximizeHovered = hovered;
notifyListeners();
}
return true;
case 'requestClose':
if (_onCloseRequested == null) return false;
_onCloseRequested!();
return true;
default:
throw MissingPluginException('Unsupported window chrome method');
}
}
Future<void> _enable() async {
final revision = ++_revision;
final enabled = await _invoke<bool>('configureChrome', {
'enabled': true,
'headerHeight': _headerHeight,
'interceptClose': _onCloseRequested != null,
if (isWindows) 'headerInteractive': _interactive,
});
if (!_disposed &&
identical(_owner, this) &&
revision == _revision &&
_integrated != (enabled == true)) {
_integrated = enabled == true;
notifyListeners();
}
}
static Future<T?> _invoke<T>(String method, [Object? arguments]) async {
try {
return await _chrome.invokeMethod<T>(method, arguments);
} on MissingPluginException {
// Widget tests without native plugins keep the standard header.
} on PlatformException catch (error) {
debugPrint('Could not update window chrome: ${error.code}');
}
return null;
}
static Future<void> reportControl(
String id,
Rect? rect,
HeaderControlRole role,
) async {
try {
await _controls.invokeMethod<void>('setHeaderControlRegion', {
'id': id,
'role': role.name,
'rect': rect == null
? null
: {
'x': rect.left,
'y': rect.top,
'width': rect.width,
'height': rect.height,
},
});
} on MissingPluginException {
// Widget tests do not register native plugins.
} on PlatformException catch (error) {
debugPrint('Could not update titlebar controls: ${error.code}');
}
}
@override
void dispose() {
_disposed = true;
_sessions.remove(this);
if (identical(_owner, this)) {
_owner = null;
_chrome.setMethodCallHandler(null);
if (_sessions.isNotEmpty) {
_sessions.last._activate();
} else {
scheduleMicrotask(() {
if (_owner == null) {
unawaited(_invoke<bool>('configureChrome', {'enabled': false}));
}
});
}
}
super.dispose();
}
}
@@ -0,0 +1,68 @@
import 'package:flutter/widgets.dart';
/// Shares caption bounds in each workspace pane's local layout coordinates.
class WindowHeaderLayout extends InheritedWidget {
const WindowHeaderLayout({
super.key,
required this.captionBounds,
required super.child,
});
final Rect captionBounds;
static Rect? _boundsOf(BuildContext context) => context
.dependOnInheritedWidgetOfExactType<WindowHeaderLayout>()
?.captionBounds;
@override
bool updateShouldNotify(WindowHeaderLayout oldWidget) =>
captionBounds != oldWidget.captionBounds;
}
/// Translates the shared caption bounds at a workspace pane boundary.
class WindowHeaderPane extends StatelessWidget {
const WindowHeaderPane({
super.key,
required this.offset,
required this.child,
});
final Offset offset;
final Widget child;
@override
Widget build(BuildContext context) {
final bounds = WindowHeaderLayout._boundsOf(context);
if (bounds == null) return child;
return WindowHeaderLayout(
captionBounds: bounds.shift(-offset),
child: child,
);
}
}
/// Reserves overlapping caption space directly from layout constraints.
class WindowHeaderPadding extends StatelessWidget {
const WindowHeaderPadding({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
final bounds = WindowHeaderLayout._boundsOf(context);
if (bounds == null) return child;
return LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth;
final right =
bounds.top <= 0 &&
bounds.bottom > 0 &&
bounds.left < width &&
bounds.right > 0
? (width - bounds.left).clamp(0.0, width)
: 0.0;
return Padding(
padding: EdgeInsets.only(right: right),
child: right >= width ? const SizedBox.shrink() : child,
);
},
);
}
}
@@ -0,0 +1,15 @@
Pod::Spec.new do |s|
s.name = 'cutdex_native'
s.version = '0.1.0'
s.summary = 'Cutdex desktop platform integration.'
s.description = 'Native window chrome, file drops, context menus and fullscreen.'
s.homepage = 'https://github.com/lingjhf/cutdex'
s.license = { :type => 'MIT', :file => '../../../LICENSE' }
s.authors = 'Cutdex contributors'
s.source = { :path => '.' }
s.source_files = 'cutdex_native/Sources/cutdex_native/**/*.swift'
s.dependency 'FlutterMacOS'
s.platform = :osx, '14.0'
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES' }
s.swift_version = '5.0'
end
@@ -0,0 +1,25 @@
// swift-tools-version: 5.9
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "cutdex_native",
platforms: [
.macOS("14.0")
],
products: [
.library(name: "cutdex-native", targets: ["cutdex_native"])
],
dependencies: [
.package(name: "FlutterFramework", path: "../FlutterFramework")
],
targets: [
.target(
name: "cutdex_native",
dependencies: [
.product(name: "FlutterFramework", package: "FlutterFramework")
]
)
]
)
@@ -0,0 +1,49 @@
import Cocoa
import FlutterMacOS
public final class CutdexNativePlugin: NSObject, FlutterPlugin {
private let view: NSView
private let messenger: FlutterBinaryMessenger
private let menu: NativeContextMenuBridge
private var drops: [String: NativeFileDropView] = [:]
private init(view: NSView, messenger: FlutterBinaryMessenger) {
self.view = view
self.messenger = messenger
menu = NativeContextMenuBridge(view: view, messenger: messenger)
super.init()
(view.window as? CutdexNativeWindow)?.configureNative(messenger: messenger)
}
public static func register(with registrar: FlutterPluginRegistrar) {
guard let view = registrar.view else { return }
let instance = CutdexNativePlugin(view: view, messenger: registrar.messenger)
let channel = FlutterMethodChannel(name: "cutdex_native/file_drop",
binaryMessenger: registrar.messenger)
registrar.addMethodCallDelegate(instance, channel: channel)
registrar.addMethodCallDelegate(instance, channel: FlutterMethodChannel(
name: "cutdex_native/device_info", binaryMessenger: registrar.messenger))
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
if call.method == "getApplicationInfo" {
result(["appVersion": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown",
"appBuild": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown"])
return
}
guard call.method == "ensureRegion",
let args = call.arguments as? [String: Any], let id = args["id"] as? String,
!id.isEmpty, let hidesImage = args["hidesSourceImage"] as? Bool else {
return result(FlutterMethodNotImplemented)
}
if let drop = drops[id] {
drop.hidesSourceImage = hidesImage
} else {
let drop = NativeFileDropView(view: view, messenger: messenger,
channelName: "cutdex_native/file_drop/" + id, hidesSourceImage: hidesImage)
view.addSubview(drop)
drops[id] = drop
}
result(nil)
}
}
@@ -0,0 +1,323 @@
import Cocoa
import FlutterMacOS
open class CutdexNativeWindow: NSWindow {
private var chromeChannel: FlutterMethodChannel?
private var controlsChannel: FlutterMethodChannel?
private var fullscreenChannel: FlutterMethodChannel?
private var ownsFullscreen = false
private var fullscreenReply: FlutterResult?
var headerControlRegions: [String: NSRect] = [:]
private var chromeObservers: [NSObjectProtocol] = []
private(set) var chromeEnabled = false
private var interceptClose = true
private var headerHeight: CGFloat = 40
private var originalButtonOrigins: [NSWindow.ButtonType: NSPoint] = [:]
private var originalTitleVisibility: NSWindow.TitleVisibility = .visible
private var originalTitlebarTransparency = false
private var originallyFullSize = false
private weak var originalCloseButtonTarget: AnyObject?
private var originalCloseButtonAction: Selector?
private weak var headerMouseTarget: NSView?
private var headerControlGestureActive = false
private var emptyHeaderDragActive = false
private var originalWindowMovable = true
private var originalBackgroundMovable = false
func configureNative(messenger: FlutterBinaryMessenger) {
let channel = FlutterMethodChannel(
name: "cutdex_native/window", binaryMessenger: messenger)
chromeChannel = channel
channel.setMethodCallHandler { [weak self] call, result in
guard let self else { return result(nil) }
switch call.method {
case "minimize": self.miniaturize(nil); return result(nil)
case "toggleMaximize": self.performZoom(nil); return result(nil)
case "close": self.performClose(nil); return result(nil)
default: break
}
guard call.method == "configureChrome" else {
return result(FlutterMethodNotImplemented)
}
guard let args = call.arguments as? [String: Any],
let enabled = args["enabled"] as? Bool else {
return result(FlutterError(code: "invalidArgument", message: "Missing enabled flag", details: nil))
}
let height = (args["headerHeight"] as? NSNumber)?.doubleValue ?? 40
guard height.isFinite, height > 0 else {
return result(FlutterError(code: "invalidArgument", message: "Invalid header height", details: nil))
}
self.configureChrome(enabled, headerHeight: height,
interceptClose: args["interceptClose"] as? Bool ?? true)
result(enabled)
}
let controls = FlutterMethodChannel(
name: "cutdex_native/window_controls", binaryMessenger: messenger)
controlsChannel = controls
controls.setMethodCallHandler { [weak self] call, result in
guard let self else { return result(nil) }
guard call.method == "setHeaderControlRegion",
let args = call.arguments as? [String: Any], let id = args["id"] as? String else {
return result(FlutterMethodNotImplemented)
}
if let rect = args["rect"] as? [String: NSNumber],
let x = rect["x"]?.doubleValue, let y = rect["y"]?.doubleValue,
let width = rect["width"]?.doubleValue, let height = rect["height"]?.doubleValue,
[x, y, width, height].allSatisfy({ $0.isFinite }), width >= 0, height >= 0 {
self.headerControlRegions[id] = NSRect(x: x, y: y, width: width, height: height)
} else {
self.headerControlRegions.removeValue(forKey: id)
}
result(nil)
}
for name in [NSWindow.didResizeNotification, NSWindow.didEndLiveResizeNotification,
NSWindow.didExitFullScreenNotification] {
chromeObservers.append(NotificationCenter.default.addObserver(
forName: name, object: self, queue: .main
) { [weak self] _ in
self?.positionWindowButtons()
DispatchQueue.main.async { [weak self] in self?.positionWindowButtons() }
})
}
let fullscreen = FlutterMethodChannel(
name: "cutdex_native/fullscreen", binaryMessenger: messenger)
fullscreenChannel = fullscreen
fullscreen.setMethodCallHandler { [weak self] call, result in
guard let self else { return result(nil) }
guard call.method == "setFullscreen", let enabled = call.arguments as? Bool else {
return result(FlutterMethodNotImplemented)
}
guard self.fullscreenReply == nil else {
return result(FlutterError(code: "busy", message: "Fullscreen transition in progress", details: nil))
}
if enabled {
guard !self.styleMask.contains(.fullScreen) else { return result(nil) }
self.ownsFullscreen = true
} else {
guard self.ownsFullscreen else { return result(nil) }
self.ownsFullscreen = false
guard self.styleMask.contains(.fullScreen) else { return result(nil) }
}
self.fullscreenReply = result
self.toggleFullScreen(nil)
}
for name in [NSWindow.didEnterFullScreenNotification, NSWindow.didExitFullScreenNotification] {
chromeObservers.append(NotificationCenter.default.addObserver(
forName: name, object: self, queue: .main
) { [weak self] notification in
guard let self else { return }
let reply = self.fullscreenReply
self.fullscreenReply = nil
reply?(nil)
if notification.name == NSWindow.didExitFullScreenNotification {
self.ownsFullscreen = false
self.fullscreenChannel?.invokeMethod("exited", arguments: nil)
}
})
}
}
deinit {
for observer in chromeObservers { NotificationCenter.default.removeObserver(observer) }
}
/// Keep a titled, resizable AppKit window; only its content/titlebar layout changes.
public func configureChrome(_ enabled: Bool, headerHeight: CGFloat = 40,
interceptClose: Bool = true) {
self.headerHeight = headerHeight
self.interceptClose = interceptClose
guard enabled != chromeEnabled else {
if enabled, let button = standardWindowButton(.closeButton) {
configureCloseButton(button)
}
positionWindowButtons()
return
}
let preservedFrame = frame
if enabled {
originalTitleVisibility = titleVisibility
originalTitlebarTransparency = titlebarAppearsTransparent
originallyFullSize = styleMask.contains(.fullSizeContentView)
originalWindowMovable = isMovable
originalBackgroundMovable = isMovableByWindowBackground
originalButtonOrigins = [:]
for type in [NSWindow.ButtonType.closeButton, .miniaturizeButton, .zoomButton] {
originalButtonOrigins[type] = standardWindowButton(type)?.frame.origin
}
if let closeButton = standardWindowButton(.closeButton) {
originalCloseButtonTarget = closeButton.target as AnyObject?
originalCloseButtonAction = closeButton.action
configureCloseButton(closeButton)
}
chromeEnabled = true
// Disable server-side dragging before the mouse press reaches sendEvent.
// Only our explicit empty-titlebar drag path temporarily enables movement.
isMovable = false
isMovableByWindowBackground = false
titleVisibility = .hidden
titlebarAppearsTransparent = true
styleMask.insert(.fullSizeContentView)
} else {
chromeEnabled = false
isMovable = originalWindowMovable
isMovableByWindowBackground = originalBackgroundMovable
titleVisibility = originalTitleVisibility
titlebarAppearsTransparent = originalTitlebarTransparency
if !originallyFullSize { styleMask.remove(.fullSizeContentView) }
for (type, origin) in originalButtonOrigins {
standardWindowButton(type)?.setFrameOrigin(origin)
}
if let closeButton = standardWindowButton(.closeButton) {
closeButton.target = originalCloseButtonTarget
closeButton.action = originalCloseButtonAction
}
}
setFrame(preservedFrame, display: true)
positionWindowButtons()
DispatchQueue.main.async { [weak self] in self?.positionWindowButtons() }
}
func positionWindowButtons() {
// AppKit owns the fullscreen titlebar and its reveal/hide animation.
guard chromeEnabled, !styleMask.contains(.fullScreen), let contentView else { return }
let types: [NSWindow.ButtonType] = [.closeButton, .miniaturizeButton, .zoomButton]
for (index, type) in types.enumerated() {
guard let button = standardWindowButton(type), let parent = button.superview else { continue }
if type == .closeButton { configureCloseButton(button) }
let center = NSPoint(x: 19 + CGFloat(index) * 20,
y: contentView.isFlipped ? headerHeight / 2 : contentView.bounds.height - headerHeight / 2)
let target = parent.convert(center, from: contentView)
button.setFrameOrigin(NSPoint(x: target.x - button.frame.width / 2,
y: target.y - button.frame.height / 2))
}
}
open override func performClose(_ sender: Any?) {
guard chromeEnabled, interceptClose else {
super.performClose(sender)
return
}
requestClose()
}
/// The Flutter owner decides how to handle an intercepted close request.
func requestClose() {
chromeChannel?.invokeMethod("requestClose", arguments: nil)
}
private func configureCloseButton(_ button: NSButton) {
guard interceptClose else {
button.target = originalCloseButtonTarget
button.action = originalCloseButtonAction
return
}
button.target = self
button.action = #selector(closeButtonPressed(_:))
}
@objc private func closeButtonPressed(_ sender: Any?) {
requestClose()
}
private func endHeaderControlGesture() {
headerMouseTarget = nil
headerControlGestureActive = false
}
private func dragEmptyHeader(with event: NSEvent) {
guard !headerControlGestureActive, originalWindowMovable else { return }
emptyHeaderDragActive = true
isMovable = true
defer {
emptyHeaderDragActive = false
isMovable = chromeEnabled ? false : originalWindowMovable
}
performDrag(with: event)
}
open override func resignKey() {
endHeaderControlGesture()
super.resignKey()
}
// Flutter can forward an unhandled event through NSResponder to this window.
// Keep that fallback from interpreting a control gesture as a titlebar action.
open override func mouseDown(with event: NSEvent) {
guard !headerControlGestureActive else { return }
super.mouseDown(with: event)
}
open override func mouseDragged(with event: NSEvent) {
guard !headerControlGestureActive else { return }
super.mouseDragged(with: event)
}
open override func mouseUp(with event: NSEvent) {
guard !headerControlGestureActive else { return }
super.mouseUp(with: event)
}
open override func performDrag(with event: NSEvent) {
guard !headerControlGestureActive, !chromeEnabled || emptyHeaderDragActive else { return }
super.performDrag(with: event)
}
open override func performZoom(_ sender: Any?) {
guard !headerControlGestureActive else { return }
super.performZoom(sender)
}
open override func zoom(_ sender: Any?) {
guard !headerControlGestureActive else { return }
super.zoom(sender)
}
open override func sendEvent(_ event: NSEvent) {
if event.type == .leftMouseDown { endHeaderControlGesture() }
if headerControlGestureActive {
if event.type == .leftMouseUp {
defer { endHeaderControlGesture() }
headerMouseTarget?.mouseUp(with: event)
return
}
if event.type == .leftMouseDragged {
headerMouseTarget?.mouseDragged(with: event)
return
}
}
if chromeEnabled, !styleMask.contains(.fullScreen), event.type == .leftMouseDown,
let contentView {
let point = contentView.convert(event.locationInWindow, from: nil)
let top = contentView.isFlipped ? point.y : contentView.bounds.height - point.y
let controlPoint = NSPoint(x: point.x, y: top)
let isHeaderControl = headerControlRegions.values.contains { $0.contains(controlPoint) }
if top >= 0, top < headerHeight, isHeaderControl,
let target = contentViewController?.view {
// Falling through to AppKit lets its transparent titlebar interpret
// a second click as window zoom before Flutter receives the gesture.
if !isKeyWindow { makeKeyAndOrderFront(nil) }
// Keep the control gesture in Flutter even after leaving its bounds.
headerControlGestureActive = true
headerMouseTarget = target
target.mouseDown(with: event)
return
}
if top >= 0, top < headerHeight, point.x >= 88 {
if event.clickCount == 2 {
switch UserDefaults.standard.string(forKey: "AppleActionOnDoubleClick") {
case "Minimize": miniaturize(nil)
case "None": break
default: performZoom(nil)
}
} else {
dragEmptyHeader(with: event)
}
return
}
}
super.sendEvent(event)
}
}
@@ -0,0 +1,270 @@
import Cocoa
import FlutterMacOS
/// AppKit owns menu tracking; Dart receives an action only after tracking ends.
final class NativeContextMenuBridge: NSObject {
private let channel: FlutterMethodChannel
private weak var view: NSView?
private var selectedID: Int?
private var tracking = false
init(view: NSView, messenger: FlutterBinaryMessenger) {
self.view = view
channel = FlutterMethodChannel(name: "cutdex_native/context_menu",
binaryMessenger: messenger)
super.init()
channel.setMethodCallHandler { [weak self] call, result in
guard let self else { return result(nil) }
guard call.method == "show" else { return result(FlutterMethodNotImplemented) }
guard let args = call.arguments as? [String: Any],
let x = args["x"] as? NSNumber, let y = args["y"] as? NSNumber,
x.doubleValue.isFinite, y.doubleValue.isFinite,
let entries = args["items"] as? [[String: Any]],
let view = self.view, view.window != nil, !self.tracking else {
return result(FlutterError(code: "unavailable", message: "Cannot open context menu", details: nil))
}
self.tracking = true
self.selectedID = nil
let menu = self.makeMenu(entries)
let point = NSPoint(x: view.bounds.minX + CGFloat(x.doubleValue),
y: view.isFlipped ? view.bounds.minY + CGFloat(y.doubleValue)
: view.bounds.maxY - CGFloat(y.doubleValue))
menu.popUp(positioning: nil, at: point, in: view)
self.tracking = false
result(self.selectedID)
}
}
private func makeMenu(_ entries: [[String: Any]]) -> NSMenu {
let menu = NSMenu()
menu.autoenablesItems = false
for entry in entries {
if entry["separator"] as? Bool == true {
menu.addItem(.separator())
continue
}
guard let label = entry["label"] as? String else { continue }
let item = NSMenuItem(title: label, action: nil, keyEquivalent: "")
item.isEnabled = entry["enabled"] as? Bool ?? true
item.state = entry["selected"] as? Bool == true ? .on : .off
if let children = entry["children"] as? [[String: Any]] {
item.submenu = makeMenu(children)
} else if let id = entry["id"] as? Int {
item.tag = id
item.target = self
item.action = #selector(selectItem(_:))
}
menu.addItem(item)
}
return menu
}
@objc private func selectItem(_ sender: NSMenuItem) {
selectedID = sender.tag
}
}
/// Acceptance is configured by Flutter independently of drag image presentation.
struct NativeFileDropPolicy {
let allowedExtensions: Set<String>?
let maximumFileCount: Int?
init?(arguments: [String: Any]) {
guard let extensions = arguments["allowedExtensions"],
let count = arguments["maximumFileCount"] else { return nil }
if extensions is NSNull {
allowedExtensions = nil
} else if let values = extensions as? [String], values.allSatisfy({ !$0.isEmpty }) {
allowedExtensions = Set(values.map { $0.lowercased() })
} else { return nil }
if count is NSNull {
maximumFileCount = nil
} else if let value = count as? NSNumber,
CFGetTypeID(value) != CFBooleanGetTypeID(),
value.doubleValue.isFinite, value.doubleValue > 0,
value.doubleValue < Double(Int.max),
value.doubleValue.rounded(.towardZero) == value.doubleValue {
maximumFileCount = value.intValue
} else { return nil }
}
func accepts(_ urls: [URL]) -> Bool {
guard !urls.isEmpty, maximumFileCount.map({ urls.count <= $0 }) ?? true else {
return false
}
return urls.allSatisfy {
var isDirectory = ObjCBool(false)
return $0.isFileURL
&& FileManager.default.fileExists(atPath: $0.path, isDirectory: &isDirectory)
&& !isDirectory.boolValue
&& (allowedExtensions?.contains($0.pathExtension.lowercased()) ?? true)
}
}
}
/// A destination over a configured Flutter region; ordinary mouse events pass through.
final class NativeFileDropView: NSView {
private let channel: FlutterMethodChannel
var hidesSourceImage: Bool
private var policy: NativeFileDropPolicy?
private weak var root: NSView?
private var urls: [URL] = []
private var grants: [Int: [URL]] = [:]
private var sequence: Int = 0
private var didDrop = false
private var sourceDragImages: [Int: [NSDraggingImageComponent]] = [:]
private var sourceAnimatesToDestination: Bool?
private let transparentDragImage = NSImage(size: NSSize(width: 1, height: 1),
flipped: false) { rect in
NSColor.clear.setFill()
rect.fill(using: .copy)
return true
}
override var isFlipped: Bool { true }
init(view: NSView, messenger: FlutterBinaryMessenger, channelName: String, hidesSourceImage: Bool) {
self.hidesSourceImage = hidesSourceImage
root = view
channel = FlutterMethodChannel(name: channelName,
binaryMessenger: messenger)
super.init(frame: .zero)
registerForDraggedTypes([.fileURL])
channel.setMethodCallHandler { [weak self] call, result in
guard let self else { return result(nil) }
switch call.method {
case "setRegion":
if let a = call.arguments as? [String: Any], let root = self.root,
let policy = NativeFileDropPolicy(arguments: a),
let x = (a["x"] as? NSNumber)?.doubleValue,
let y = (a["y"] as? NSNumber)?.doubleValue,
let w = (a["width"] as? NSNumber)?.doubleValue,
let h = (a["height"] as? NSNumber)?.doubleValue,
[x, y, w, h].allSatisfy({ $0.isFinite }), w > 0, h > 0 {
self.policy = policy
self.frame = NSRect(x: x, y: root.isFlipped ? y : root.bounds.height - y - h,
width: w, height: h)
if !self.didDrop && !self.urls.isEmpty && !policy.accepts(self.urls) {
self.emit("exit", nil)
self.urls.removeAll()
}
} else {
self.emit("exit", nil)
self.policy = nil
self.urls.removeAll()
self.frame = .zero
}
result(nil)
case "release":
if let a = call.arguments as? [String: NSNumber], let id = a["session"]?.intValue {
self.releaseGrants(id)
}
result(nil)
default: result(FlutterMethodNotImplemented)
}
}
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
private func releaseGrants(_ id: Int) {
for url in grants.removeValue(forKey: id) ?? [] { url.stopAccessingSecurityScopedResource() }
}
private func emit(_ phase: String, _ sender: NSDraggingInfo?) {
let point = sender.map { convert($0.draggingLocation, from: nil) } ?? .zero
channel.invokeMethod("event", arguments: ["phase": phase, "session": sequence,
"x": point.x, "y": point.y,
"files": (phase == "enter" || phase == "drop" ? urls : []).map { ["path": $0.path] }])
}
// Flutter renders the provisional clip, so suppress Finder's overlapping
// file icon and label. Keep components, never the transient NSDraggingItem.
private func hideSourceDragImages(_ sender: NSDraggingInfo) {
guard hidesSourceImage else { return }
if sourceAnimatesToDestination == nil {
sourceAnimatesToDestination = sender.animatesToDestination
}
sender.animatesToDestination = false
sender.enumerateDraggingItems(options: [], for: self, classes: [NSURL.self],
searchOptions: [.urlReadingFileURLsOnly: true]) { [self] item, index, _ in
if sourceDragImages[index] == nil {
sourceDragImages[index] = item.imageComponents ?? []
}
// Keep a concrete destination-owned image instead of removing the
// provider. Finder can regenerate its source image during drag updates.
let component = NSDraggingImageComponent(key: .icon)
component.contents = transparentDragImage
component.frame = NSRect(origin: .zero, size: item.draggingFrame.size)
item.imageComponentsProvider = { [component] in [component] }
}
}
private func restoreSourceDragImages(_ sender: NSDraggingInfo?) {
guard let sender, !sourceDragImages.isEmpty else { return }
if let animates = sourceAnimatesToDestination {
sender.animatesToDestination = animates
}
sourceAnimatesToDestination = nil
let images = sourceDragImages
sender.enumerateDraggingItems(options: [], for: self, classes: [NSURL.self],
searchOptions: [.urlReadingFileURLsOnly: true]) { item, index, _ in
if let components = images[index] {
item.imageComponentsProvider = { components }
}
}
sourceDragImages.removeAll()
}
override func updateDraggingItemsForDrag(_ sender: NSDraggingInfo?) {
guard let sender, !urls.isEmpty, !didDrop else { return }
hideSourceDragImages(sender)
}
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation {
sequence += 1
didDrop = false
sourceDragImages.removeAll()
sourceAnimatesToDestination = nil
urls = (sender.draggingPasteboard.readObjects(forClasses: [NSURL.self],
options: [.urlReadingFileURLsOnly: true]) as? [URL]) ?? []
guard sender.draggingSourceOperationMask.contains(.copy) else {
urls.removeAll(); return []
}
if grants[sequence] == nil {
grants[sequence] = urls.filter { $0.startAccessingSecurityScopedResource() }
}
// Acquire sandbox access before checking file metadata. Rejected references
// never reach Dart, so their access can be released immediately.
guard policy?.accepts(urls) == true else {
releaseGrants(sequence)
urls.removeAll()
return []
}
hideSourceDragImages(sender)
emit("enter", sender)
return .copy
}
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation {
guard !urls.isEmpty else { return [] }
// Position updates only drive Flutter's ghost. AppKit requests image
// updates through updateDraggingItemsForDrag; do not restart them per move.
emit("move", sender)
return .copy
}
override func draggingExited(_ sender: NSDraggingInfo?) {
restoreSourceDragImages(sender)
emit("exit", sender)
// Dart releases access after its pending decoding finishes.
}
override func draggingEnded(_ sender: NSDraggingInfo) {
if !didDrop {
restoreSourceDragImages(sender)
emit("exit", sender)
}
sourceDragImages.removeAll()
}
override func wantsPeriodicDraggingUpdates() -> Bool { true }
override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool {
policy?.accepts(urls) == true
}
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
guard policy?.accepts(urls) == true else { return false }
didDrop = true
emit("drop", sender)
return true
}
deinit { for id in Array(grants.keys) { releaseGrants(id) } }
}
+27
View File
@@ -0,0 +1,27 @@
name: cutdex_native
description: Cutdex device information and desktop platform integration.
version: 0.1.0
publish_to: none
resolution: workspace
environment:
sdk: ^3.13.2
dependencies:
flutter:
sdk: flutter
path: ^1.9.1
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
flutter:
plugin:
platforms:
android:
package: dev.cutdex.cutdex_native
pluginClass: CutdexNativePlugin
ios:
pluginClass: CutdexNativePlugin
macos:
pluginClass: CutdexNativePlugin
windows:
pluginClass: CutdexNativePluginCApi
@@ -0,0 +1,86 @@
import 'dart:math' as math;
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('moving a cached layer updates native bounds', (tester) async {
final offset = ValueNotifier(Offset.zero);
addTearDown(offset.dispose);
final reports = <Rect>[];
final content = RepaintBoundary(
child: NativeBoundsReporter(
onBounds: reports.add,
child: const SizedBox(width: 100, height: 40),
),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: ValueListenableBuilder(
valueListenable: offset,
child: content,
builder: (_, position, child) =>
Transform.translate(offset: position, child: child),
),
),
),
);
expect(reports.last, const Rect.fromLTWH(0, 0, 100, 40));
offset.value = const Offset(50, 25);
await tester.pump();
expect(reports.last, const Rect.fromLTWH(50, 25, 100, 40));
final count = reports.length;
await tester.pump();
expect(reports, hasLength(count));
expect(tester.binding.hasScheduledFrame, isFalse);
await tester.pumpWidget(const SizedBox());
await tester.pump();
expect(reports, hasLength(count));
});
for (final rotated in [false, true]) {
testWidgets('native bounds include ${rotated ? 'rotation' : 'scaling'}', (
tester,
) async {
Rect? bounds;
final reporter = NativeBoundsReporter(
onBounds: (rect) => bounds = rect,
child: const SizedBox(width: 100, height: 40),
);
await tester.pumpWidget(
Directionality(
textDirection: TextDirection.ltr,
child: Align(
alignment: Alignment.topLeft,
child: Padding(
padding: const EdgeInsets.only(left: 120, top: 100),
child: rotated
? Transform.rotate(
angle: math.pi / 2,
alignment: Alignment.topLeft,
child: reporter,
)
: Transform.scale(
scale: 2,
alignment: Alignment.topLeft,
child: reporter,
),
),
),
),
);
expect(bounds, isNotNull);
final expected = rotated
? const Rect.fromLTWH(80, 100, 40, 100)
: const Rect.fromLTWH(120, 100, 200, 80);
expect(bounds!.left, closeTo(expected.left, 1e-8));
expect(bounds!.top, closeTo(expected.top, 1e-8));
expect(bounds!.width, closeTo(expected.width, 1e-8));
expect(bounds!.height, closeTo(expected.height, 1e-8));
});
}
}
@@ -0,0 +1,63 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('cutdex_native/device_info');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
test(
'Android display facts accept integer and floating point values',
() async {
for (final value in [600, 599.5]) {
messenger.setMockMethodCallHandler(channel, (call) async {
expect(call.method, 'getDeviceInfo');
return {'displayShortestSideDp': value};
});
final info = await NativeDeviceInfo.read();
expect(info?.displayShortestSideDp, value.toDouble());
expect(info?.interfaceIdiom, isNull);
}
},
);
test('iOS idioms remain raw device facts', () async {
for (final idiom in NativeInterfaceIdiom.values) {
messenger.setMockMethodCallHandler(
channel,
(call) async => {'interfaceIdiom': idiom.name},
);
final info = await NativeDeviceInfo.read();
expect(info?.interfaceIdiom, idiom);
expect(info?.displayShortestSideDp, isNull);
}
});
test('invalid responses do not expose unusable device facts', () async {
for (final value in <Object?>[
null,
'phone',
<String, Object?>{},
{'interfaceIdiom': 'unknown'},
{'displayShortestSideDp': '600'},
{'displayShortestSideDp': 0},
{'displayShortestSideDp': -1},
{'displayShortestSideDp': double.nan},
{'displayShortestSideDp': double.infinity},
]) {
messenger.setMockMethodCallHandler(channel, (call) async => value);
expect(await NativeDeviceInfo.read(), isNull, reason: '$value');
}
});
test('unregistered and unavailable native hosts return no facts', () async {
expect(await NativeDeviceInfo.read(), isNull);
messenger.setMockMethodCallHandler(channel, (call) async {
throw PlatformException(code: 'unavailable');
});
expect(await NativeDeviceInfo.read(), isNull);
});
}
@@ -0,0 +1,41 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
test('invalid policies fail before reaching native registration', () {
expect(
() => NativeDropConfiguration(maximumFileCount: 0),
throwsArgumentError,
);
expect(
() => NativeDropConfiguration(allowedExtensions: ['']),
throwsArgumentError,
);
});
test('configuration owns an immutable extension whitelist', () {
final extensions = ['wav'];
final configuration = NativeDropConfiguration(
allowedExtensions: extensions,
);
extensions[0] = 'mp4';
expect(configuration.accepts(['/sample.wav']), true);
expect(configuration.accepts(['/sample.mp4']), false);
expect(
() => configuration.allowedExtensions!.add('mp4'),
throwsUnsupportedError,
);
});
test('equivalent whitelist sets share equality and hashing', () {
final first = NativeDropConfiguration(
allowedExtensions: ['WAV', 'mp4', 'wav'],
maximumFileCount: 2,
);
final second = NativeDropConfiguration(
allowedExtensions: ['mp4', 'wav'],
maximumFileCount: 2,
);
expect(first, second);
expect(first.hashCode, second.hashCode);
});
}
@@ -0,0 +1,340 @@
import 'dart:async';
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const manager = MethodChannel('cutdex_native/file_drop');
const destination = MethodChannel('cutdex_native/file_drop/test');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
final calls = <MethodCall>[];
setUp(() {
calls.clear();
messenger.setMockMethodCallHandler(manager, (_) async => null);
messenger.setMockMethodCallHandler(destination, (call) async {
calls.add(call);
return null;
});
});
tearDown(() {
messenger.setMockMethodCallHandler(manager, null);
messenger.setMockMethodCallHandler(destination, null);
});
Future<void> event(
String phase,
int session, {
String channelName = 'cutdex_native/file_drop/test',
}) async {
await messenger.handlePlatformMessage(
channelName,
const StandardMethodCodec().encodeMethodCall(
MethodCall('event', {
'phase': phase,
'session': session,
'x': 12.0,
'y': 8.0,
'files': [
{'path': '/example/input.wav'},
],
}),
),
(_) {},
);
}
testWidgets(
'inactive routes reject late drag events and release their grants',
(tester) async {
var entered = 0;
var dropped = 0;
await tester.pumpWidget(
MaterialApp(
home: TickerMode(
enabled: false,
child: NativeFileDropRegion(
regionId: 'test',
enabled: true,
onEnter: (_) => entered++,
onExit: () {},
onDrop: (_) async => dropped++,
child: const SizedBox.expand(),
),
),
),
);
await tester.pumpAndSettle();
await event('enter', 7);
await event('drop', 7);
await tester.pump();
expect(entered, 0);
expect(dropped, 0);
expect(calls.where((c) => c.method == 'release'), hasLength(1));
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
},
);
testWidgets(
'equivalent policies at fixed bounds do not rewrite native state',
(tester) async {
Widget target() => MaterialApp(
home: NativeFileDropRegion(
regionId: 'test',
enabled: true,
configuration: NativeDropConfiguration(
allowedExtensions: ['wav'],
maximumFileCount: 1,
),
onEnter: (_) {},
onExit: () {},
onDrop: (_) async {},
child: const SizedBox.expand(),
),
);
await tester.pumpWidget(target());
await tester.pumpAndSettle();
final reports = calls.where((c) => c.method == 'setRegion').length;
await tester.pumpWidget(target());
await tester.pumpAndSettle();
expect(calls.where((c) => c.method == 'setRegion'), hasLength(reports));
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
},
);
testWidgets('a completed drop cannot erase the next drag session', (
tester,
) async {
final pending = Completer<void>();
var dropped = 0;
await tester.pumpWidget(
MaterialApp(
home: NativeFileDropRegion(
regionId: 'test',
enabled: true,
onEnter: (_) {},
onExit: () {},
onDrop: (_) async {
if (++dropped == 1) await pending.future;
},
child: const SizedBox.expand(),
),
),
);
await tester.pumpAndSettle();
await event('enter', 7);
unawaited(event('drop', 7));
await tester.pump();
await event('enter', 8);
pending.complete();
await tester.pump();
await event('drop', 8);
await tester.pump();
expect(dropped, 2);
expect(
calls
.where((c) => c.method == 'release')
.map((c) => (c.arguments as Map)['session']),
[7, 8],
);
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
});
testWidgets('a disposed connection cannot steal a replacement binding', (
tester,
) async {
final first = NativeFileDropConnection(
regionId: 'test',
onEvent: (_) async {},
);
final events = <NativeFileDropEvent>[];
final second = NativeFileDropConnection(
regionId: 'test',
onEvent: (e) async => events.add(e),
);
first.bind();
first.dispose();
await tester.pump();
second.bind();
expect(first.bind, throwsStateError);
await event('move', 8);
expect(events, hasLength(1));
second.dispose();
await tester.pump();
});
testWidgets('a stale connection cannot change native destination options', (
tester,
) async {
final registrations = <MethodCall>[];
messenger.setMockMethodCallHandler(manager, (call) async {
registrations.add(call);
return null;
});
final first = NativeFileDropConnection(
regionId: 'test',
hidesSourceImage: true,
onEvent: (_) async {},
);
final second = NativeFileDropConnection(
regionId: 'test',
onEvent: (_) async {},
);
first.bind();
second.bind();
await second.setRegion(
const Rect.fromLTWH(0, 0, 200, 100),
NativeDropConfiguration.unrestricted,
);
await first.setRegion(
const Rect.fromLTWH(0, 0, 100, 100),
NativeDropConfiguration.unrestricted,
);
first.dispose();
expect(registrations, hasLength(1));
expect((registrations.single.arguments as Map)['hidesSourceImage'], false);
second.dispose();
await tester.pump();
});
testWidgets(
'security grant survives disposal until the drop callback finishes',
(tester) async {
final pending = Completer<void>();
var dropped = 0;
await tester.pumpWidget(
MaterialApp(
home: NativeFileDropRegion(
regionId: 'test',
enabled: true,
onEnter: (_) {},
onExit: () {},
onDrop: (paths) async {
expect(paths, ['/example/input.wav']);
dropped++;
await pending.future;
},
child: const SizedBox.expand(),
),
),
);
await tester.pumpAndSettle();
await event('enter', 7);
unawaited(event('drop', 7));
await tester.pump();
expect(dropped, 1);
expect(calls.where((call) => call.method == 'release'), isEmpty);
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
expect(calls.where((call) => call.method == 'release'), isEmpty);
pending.complete();
await tester.pump();
expect(calls.where((call) => call.method == 'release'), hasLength(1));
expect((calls.last.arguments as Map)['session'], 7);
},
);
testWidgets('late registration cannot clear a replacement destination', (
tester,
) async {
final registrations = <Completer<void>>[];
messenger.setMockMethodCallHandler(manager, (call) async {
expect((call.arguments as Map)['id'], 'test');
final pending = Completer<void>();
registrations.add(pending);
await pending.future;
return null;
});
final first = NativeFileDropConnection(
regionId: 'test',
onEvent: (_) async {},
);
final events = <NativeFileDropEvent>[];
final second = NativeFileDropConnection(
regionId: 'test',
onEvent: (event) async => events.add(event),
);
first.bind();
final oldReport = first.setRegion(
const Rect.fromLTWH(0, 0, 100, 100),
NativeDropConfiguration.unrestricted,
);
await tester.pump();
second.bind();
first.dispose();
final newReport = second.setRegion(
const Rect.fromLTWH(0, 0, 200, 100),
NativeDropConfiguration.unrestricted,
);
await tester.pump();
for (final pending in registrations) {
pending.complete();
}
await tester.pump();
await Future.wait([oldReport, newReport]);
expect(calls.where((call) => call.method == 'setRegion'), hasLength(1));
expect((calls.single.arguments as Map)['width'], 200.0);
await event('move', 8);
expect(events.single.position, const Offset(12, 8));
expect(events.single.phase, NativeFileDropPhase.move);
messenger.setMockMethodCallHandler(manager, (_) async => null);
second.dispose();
await tester.pump();
});
testWidgets(
'changing destinations preserves a pending drop on its original channel',
(tester) async {
const other = MethodChannel('cutdex_native/file_drop/other');
final otherCalls = <MethodCall>[];
messenger.setMockMethodCallHandler(other, (call) async {
otherCalls.add(call);
return null;
});
addTearDown(() => messenger.setMockMethodCallHandler(other, null));
final pending = Completer<void>();
Widget target(String id) => MaterialApp(
home: NativeFileDropRegion(
regionId: id,
enabled: true,
onEnter: (_) {},
onExit: () {},
onDrop: (_) async {
if (id == 'test') await pending.future;
},
child: const SizedBox.expand(),
),
);
await tester.pumpWidget(target('test'));
await tester.pumpAndSettle();
await event('enter', 7);
unawaited(event('drop', 7));
await tester.pump();
await tester.pumpWidget(target('other'));
await tester.pumpAndSettle();
expect(calls.where((call) => call.method == 'release'), isEmpty);
await event('enter', 8, channelName: other.name);
await event('drop', 8, channelName: other.name);
await tester.pump();
expect(
otherCalls.where((call) => call.method == 'release'),
hasLength(1),
);
pending.complete();
await tester.pump();
expect((calls.last.arguments as Map)['session'], 7);
expect(
otherCalls.where((call) => call.method == 'release'),
hasLength(1),
);
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
},
);
}
@@ -0,0 +1,87 @@
import 'dart:async';
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
const channel = MethodChannel('cutdex_native/fullscreen');
final messenger =
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
final requests = <bool>[];
setUp(() {
requests.clear();
messenger.setMockMethodCallHandler(channel, (call) async {
requests.add(call.arguments as bool);
return null;
});
});
tearDown(() => messenger.setMockMethodCallHandler(channel, null));
testWidgets('a disposed session cannot reclaim the window', (tester) async {
final first = NativeFullscreenSession(onExit: () {});
var exits = 0;
final second = NativeFullscreenSession(onExit: () => exits++);
first.attach();
first.dispose();
second.attach();
expect(first.attach, throwsStateError);
await first.setFullscreen(false);
await messenger.handlePlatformMessage(
channel.name,
const StandardMethodCodec().encodeMethodCall(const MethodCall('exited')),
(_) {},
);
expect(exits, 1);
expect(requests, isEmpty);
second.dispose();
});
testWidgets('a replacement takes ownership while an entry is pending', (
tester,
) async {
final entered = Completer<void>();
messenger.setMockMethodCallHandler(channel, (call) async {
requests.add(call.arguments as bool);
if (requests.length == 1) await entered.future;
return null;
});
final first = NativeFullscreenSession(onExit: () {});
final second = NativeFullscreenSession(onExit: () {});
first.attach();
final entering = first.setFullscreen(true);
await tester.pump();
second.attach();
final replacement = second.setFullscreen(true);
first.dispose(exitFullscreen: true);
await tester.pump();
expect(requests, [true]);
entered.complete();
await tester.pump();
await Future.wait([entering, replacement]);
expect(requests, [true, true]);
second.dispose(exitFullscreen: true);
await tester.pump();
expect(requests, [true, true, false]);
});
testWidgets('a failed transition does not block the next request', (
tester,
) async {
messenger.setMockMethodCallHandler(channel, (call) async {
requests.add(call.arguments as bool);
if (call.arguments == true) throw PlatformException(code: 'failed');
return null;
});
final session = NativeFullscreenSession(onExit: () {});
session.attach();
await expectLater(
session.setFullscreen(true),
throwsA(isA<PlatformException>()),
);
await session.setFullscreen(false);
expect(requests, [true, false]);
session.dispose();
});
}
@@ -0,0 +1,43 @@
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets(
'inactive routes unregister header hit regions and restore them on return',
(tester) async {
const channel = MethodChannel('cutdex_native/window_controls');
final calls = <MethodCall>[];
final messenger = tester.binding.defaultBinaryMessenger;
messenger.setMockMethodCallHandler(channel, (call) async {
calls.add(call);
return null;
});
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
Widget target(bool enabled) => MaterialApp(
home: TickerMode(
enabled: enabled,
child: const HeaderControlRegion(
child: SizedBox(width: 100, height: 40),
),
),
);
await tester.pumpWidget(target(true));
await tester.pumpAndSettle();
expect((calls.last.arguments as Map)['rect'], isNotNull);
final id = (calls.last.arguments as Map)['id'];
await tester.pumpWidget(target(false));
await tester.pumpAndSettle();
expect((calls.last.arguments as Map)['id'], id);
expect((calls.last.arguments as Map)['rect'], isNull);
await tester.pumpWidget(target(true));
await tester.pumpAndSettle();
expect((calls.last.arguments as Map)['rect'], isNotNull);
await tester.pumpWidget(const SizedBox());
await tester.pumpAndSettle();
expect((calls.last.arguments as Map)['rect'], isNull);
},
variant: TargetPlatformVariant.only(TargetPlatform.macOS),
);
}
@@ -0,0 +1,43 @@
import Cocoa
import FlutterMacOS
@main
struct FileDropPolicyTests {
static func main() throws {
let files = FileManager.default
let root = files.temporaryDirectory.appendingPathComponent(UUID().uuidString)
try files.createDirectory(at: root, withIntermediateDirectories: true)
defer { try? files.removeItem(at: root) }
let file = root.appendingPathComponent("input.WAV")
try Data([0]).write(to: file)
let directory = root.appendingPathComponent("directory.wav")
try files.createDirectory(at: directory, withIntermediateDirectories: true)
let missing = root.appendingPathComponent("missing.wav")
let unrestricted = NativeFileDropPolicy(arguments: [
"allowedExtensions": NSNull(), "maximumFileCount": NSNull()
])!
let audio = NativeFileDropPolicy(arguments: [
"allowedExtensions": ["wav"], "maximumFileCount": 1
])!
var failures = 0
func check(_ condition: Bool, _ label: String) {
if !condition {
failures += 1
fputs("FAIL: \(label)\n", stderr)
}
}
check(audio.accepts([file]), "existing file with uppercase extension")
check(unrestricted.accepts([file]), "existing file without extension restrictions")
check(!audio.accepts([directory]), "directory with a permitted extension")
check(!unrestricted.accepts([directory]), "directory without extension restrictions")
check(!audio.accepts([missing]), "missing file with a permitted extension")
check(!unrestricted.accepts([missing]), "missing file without extension restrictions")
check(!audio.accepts([file, file]), "file count limit")
check(!audio.accepts([]), "empty input")
check(!unrestricted.accepts([URL(string: "https://example.com/input.wav")!]), "non-file URL")
try files.removeItem(at: file)
check(!audio.accepts([file]), "file deleted after entering the drop destination")
if failures > 0 { exit(1) }
print("Native file drop policy passed")
}
}
@@ -0,0 +1,88 @@
import Cocoa
import FlutterMacOS
// The harness exercises a window without initializing plugins or showing it.
final class HiddenTestWindow: CutdexNativeWindow {
var emptyDrags = 0
override var isKeyWindow: Bool { true }
override func performDrag(with event: NSEvent) {
if isMovable {
emptyDrags += 1
return // Observe the explicit native drag entry without a blocking tracking loop.
}
super.performDrag(with: event)
}
override func makeKeyAndOrderFront(_ sender: Any?) {}
}
final class BubblingControlView: NSView {
var downs = 0
var drags = 0
var ups = 0
override func mouseDown(with event: NSEvent) {
downs += 1
precondition(window?.isMovable == false)
// Exercise responder fallback and direct native actions during the gesture.
window?.mouseDown(with: event)
window?.performZoom(nil)
window?.zoom(nil)
window?.performDrag(with: event)
}
override func mouseDragged(with event: NSEvent) {
drags += 1
precondition(window?.isMovable == false)
window?.mouseDragged(with: event)
window?.performDrag(with: event)
}
override func mouseUp(with event: NSEvent) {
ups += 1
precondition(window?.isMovable == false)
window?.mouseUp(with: event)
}
}
@main
struct HeaderGestureTest {
static func main() {
_ = NSApplication.shared
let window = HiddenTestWindow(contentRect: NSRect(x: 100, y: 100, width: 640, height: 480),
styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
let control = BubblingControlView(frame: NSRect(x: 0, y: 0, width: 640, height: 480))
let controller = NSViewController()
controller.view = control
window.contentViewController = controller
window.isMovable = true
window.isMovableByWindowBackground = true
window.configureChrome(true)
window.headerControlRegions["control"] = NSRect(x: 88, y: 0, width: 140, height: 40)
precondition(!window.isMovable && !window.isMovableByWindowBackground)
let original = window.frame
func event(_ type: NSEvent.EventType, x: CGFloat, top: CGFloat, clicks: Int = 1) -> NSEvent {
let view = window.contentView!
let p = NSPoint(x: x, y: view.isFlipped ? top : view.bounds.height - top)
return NSEvent.mouseEvent(with: type, location: view.convert(p, to: nil),
modifierFlags: [], timestamp: ProcessInfo.processInfo.systemUptime,
windowNumber: window.windowNumber, context: nil, eventNumber: 0,
clickCount: clicks, pressure: 1)!
}
window.sendEvent(event(.leftMouseDown, x: 110, top: 20))
// A route change caused by the press must not release native protection.
window.configureChrome(true)
window.sendEvent(event(.leftMouseDragged, x: 400, top: 150))
window.sendEvent(event(.leftMouseUp, x: 400, top: 150))
precondition(!window.isMovable)
precondition(window.frame == original)
window.sendEvent(event(.leftMouseDown, x: 110, top: 20, clicks: 2))
window.sendEvent(event(.leftMouseUp, x: 110, top: 20, clicks: 2))
precondition(!window.isMovable)
precondition(window.frame == original)
precondition(control.downs == 2 && control.drags == 1 && control.ups == 2)
precondition(window.emptyDrags == 0)
window.sendEvent(event(.leftMouseDown, x: 400, top: 20))
precondition(window.emptyDrags == 1)
precondition(!window.isMovable)
window.configureChrome(false)
precondition(window.isMovable && window.isMovableByWindowBackground)
print("Native header control gestures passed")
}
}
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 [flutter-framework-directory]"
exit 0
fi
if [ "$#" -gt 1 ]; then
echo "Usage: $0 [flutter-framework-directory]" >&2
exit 2
fi
task_root=$(cd "$(dirname "$0")/../.." && pwd)
task_workspace_root=$(cd "$task_root/../.." && pwd)
task_framework_dir=${1:-"$task_workspace_root/build/macos/Build/Products/Debug-development"}
task_test_dir=$(mktemp -d)
trap 'rm -rf "$task_test_dir"' EXIT HUP INT TERM
xcrun swiftc -F "$task_framework_dir" -framework FlutterMacOS -framework Cocoa \
-Xlinker -rpath -Xlinker "$task_framework_dir" \
"$task_root/macos/cutdex_native/Sources/cutdex_native/NativeBridges.swift" \
"$task_root/tool/macos/file_drop_policy_test.swift" \
-o "$task_test_dir/file-drop-policy"
"$task_test_dir/file-drop-policy"
@@ -0,0 +1,25 @@
#!/bin/sh
set -eu
if [ "$#" -eq 1 ] && { [ "$1" = "--help" ] || [ "$1" = "-h" ]; }; then
echo "Usage: $0 [flutter-framework-directory]"
exit 0
fi
if [ "$#" -gt 1 ]; then
echo "Usage: $0 [flutter-framework-directory]" >&2
exit 2
fi
task_root=$(cd "$(dirname "$0")/../.." && pwd)
task_workspace_root=$(cd "$task_root/../.." && pwd)
task_framework_dir=${1:-"$task_workspace_root/build/macos/Build/Products/Debug-development"}
task_test_dir=$(mktemp -d)
trap 'rm -rf "$task_test_dir"' EXIT HUP INT TERM
xcrun swiftc -F "$task_framework_dir" -framework FlutterMacOS -framework Cocoa \
-Xlinker -rpath -Xlinker "$task_framework_dir" \
"$task_root/macos/cutdex_native/Sources/cutdex_native/CutdexNativeWindow.swift" \
"$task_root/tool/macos/header_control_gestures_test.swift" \
-o "$task_test_dir/header-gestures"
"$task_test_dir/header-gestures"
@@ -0,0 +1,20 @@
cmake_minimum_required(VERSION 3.14)
project(window_chrome_tests LANGUAGES CXX)
set(PACKAGE_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../..")
set(NATIVE_SOURCES "${PACKAGE_ROOT}/windows")
set(WRAPPER "${PACKAGE_ROOT}/../../windows/flutter/ephemeral/cpp_client_wrapper")
if(NOT EXISTS "${WRAPPER}/standard_codec.cc")
message(FATAL_ERROR "Run flutter build windows once to prepare the Flutter wrapper")
endif()
add_executable(window_chrome_tests
"window_chrome_tests.cpp" "${NATIVE_SOURCES}/window_chrome.cpp" "${WRAPPER}/standard_codec.cc"
"${WRAPPER}/core_implementations.cc")
target_include_directories(window_chrome_tests PRIVATE "${NATIVE_SOURCES}" "${WRAPPER}/include" "${WRAPPER}/..")
target_compile_features(window_chrome_tests PRIVATE cxx_std_17)
target_compile_definitions(window_chrome_tests PRIVATE UNICODE _UNICODE NOMINMAX)
target_compile_options(window_chrome_tests PRIVATE /W4 /WX /wd4100 /EHsc)
target_link_libraries(window_chrome_tests PRIVATE dwmapi comctl32 "${WRAPPER}/../flutter_windows.dll.lib")
add_custom_command(TARGET window_chrome_tests POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different "${WRAPPER}/../flutter_windows.dll" "$<TARGET_FILE_DIR:window_chrome_tests>")
enable_testing()
add_test(NAME window_chrome COMMAND window_chrome_tests)
@@ -0,0 +1,227 @@
#include "window_chrome.h"
#include <flutter/standard_method_codec.h>
#include <windowsx.h>
#include <cstdlib>
#include <iostream>
#include <vector>
namespace {
using Value = flutter::EncodableValue;
using Map = flutter::EncodableMap;
int checks = 0;
void Check(bool condition, const char* message) {
++checks;
if (!condition) { std::cerr << "FAIL: " << message << '\n'; std::exit(1); }
}
class Messenger : public flutter::BinaryMessenger {
public:
std::map<std::string, flutter::BinaryMessageHandler> handlers;
mutable std::vector<std::string> notifications;
void Send(const std::string&, const uint8_t* bytes, size_t size,
flutter::BinaryReply reply) const override {
auto call = flutter::StandardMethodCodec::GetInstance().DecodeMethodCall(bytes, size);
notifications.push_back(call->method_name());
}
void SetMessageHandler(const std::string& channel,
flutter::BinaryMessageHandler handler) override {
handlers[channel] = std::move(handler);
}
void Call(const char* channel, const char* method, Value args) {
const auto bytes = flutter::StandardMethodCodec::GetInstance().EncodeMethodCall(
flutter::MethodCall<Value>(method, std::make_unique<Value>(std::move(args))));
bool success = false;
handlers.at(channel)(bytes->data(), bytes->size(),
[&](const uint8_t* data, size_t size) { success = size > 0 && data[0] == 0; });
Check(success, method);
}
};
WindowChrome* chrome = nullptr;
HWND view = nullptr;
LRESULT CALLBACK WindowProc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
if (chrome) {
auto result = chrome->HandleMessage(message, wparam, lparam);
if (result) return *result;
}
if (message == WM_GETMINMAXINFO) {
DefWindowProc(window, message, wparam, lparam);
const auto dpi = static_cast<int>(GetDpiForWindow(window));
auto limits = reinterpret_cast<MINMAXINFO*>(lparam);
limits->ptMinTrackSize.x = MulDiv(520, dpi, 96);
limits->ptMinTrackSize.y = MulDiv(360, dpi, 96);
return 0;
}
if (message == WM_SIZE && view) {
RECT rect{};
GetClientRect(window, &rect);
MoveWindow(view, 0, 0, rect.right, rect.bottom, FALSE);
return 0;
}
return DefWindowProc(window, message, wparam, lparam);
}
LPARAM Position(HWND window, double x, double y) {
const double scale = GetDpiForWindow(window) / 96.0;
POINT point{static_cast<LONG>(x * scale), static_cast<LONG>(y * scale)};
ClientToScreen(window, &point);
return MAKELPARAM(point.x, point.y);
}
void Configure(Messenger& messenger, bool enabled = true, bool intercept_close = false) {
messenger.Call("cutdex_native/window", "configureChrome", Value(Map{
{Value("enabled"), Value(enabled)}, {Value("headerHeight"), Value(46.0)},
{Value("interceptClose"), Value(intercept_close)}}));
}
void ReportControl(Messenger& messenger, const char* id, double x, double width,
const char* role = "control") {
messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{
{Value("id"), Value(id)}, {Value("role"), Value(role)},
{Value("rect"), Value(Map{
{Value("x"), Value(x)}, {Value("y"), Value(0.0)},
{Value("width"), Value(width)}, {Value("height"), Value(46.0)}})}}));
}
} // namespace
int main() {
SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
WNDCLASS window_class{};
window_class.lpfnWndProc = WindowProc;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.lpszClassName = L"CutdexChromeTest";
RegisterClass(&window_class);
const HWND window = CreateWindow(window_class.lpszClassName, L"Chrome test",
WS_OVERLAPPEDWINDOW, -350, -100, 900, 600, nullptr, nullptr,
window_class.hInstance, nullptr);
Check(window != nullptr, "create window at negative screen coordinates");
WNDCLASS view_class{};
view_class.lpfnWndProc = DefWindowProc;
view_class.hInstance = window_class.hInstance;
view_class.lpszClassName = L"CutdexChromeTestView";
RegisterClass(&view_class);
view = CreateWindow(view_class.lpszClassName, L"", WS_CHILD | WS_VISIBLE, 0, 0, 800, 500, window,
nullptr, window_class.hInstance, nullptr);
Messenger messenger;
auto owner = std::make_unique<WindowChrome>(window, view, &messenger);
chrome = owner.get();
Configure(messenger);
const LONG_PTR style = GetWindowLongPtr(window, GWL_STYLE);
Check((style & WS_THICKFRAME) != 0 && (style & WS_SYSMENU) != 0 &&
(style & WS_MAXIMIZEBOX) != 0, "retain Windows frame and commands");
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCAPTION,
"empty header drags");
Check(SendMessage(view, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTTRANSPARENT,
"Flutter child passes native header hits to parent");
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 100)) == HTCLIENT,
"body stays in Flutter");
messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{
{Value("id"), Value("button")}, {Value("rect"), Value(Map{
{Value("x"), Value(270.0)}, {Value("y"), Value(0.0)},
{Value("width"), Value(60.0)}, {Value("height"), Value(46.0)}})}}));
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCLIENT,
"buttons and inputs do not drag");
Check(SendMessage(view, WM_NCHITTEST, 0, Position(view, 300, 22)) != HTTRANSPARENT,
"Flutter child keeps control hits");
messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{
{Value("id"), Value("button")}, {Value("rect"), Value()}}));
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCAPTION,
"disposed control removes its exclusion");
RECT client{};
GetClientRect(view, &client);
const double width = client.right * 96.0 / GetDpiForWindow(window);
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 69, 22)) == HTCAPTION,
"no guessed caption hit targets before Flutter reports bounds");
// Deliberately differ from the current UI's 46-pixel buttons. Win32 must use
// the reported geometry, even if button widths or their positions change.
ReportControl(messenger, "minimize", width - 218, 68);
ReportControl(messenger, "maximize", width - 150, 74, "maximize");
ReportControl(messenger, "close", width - 76, 76);
LPARAM max_position = Position(view, width - 113, 22);
Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTMAXBUTTON,
"maximize advertises Snap Layouts hit target");
Check(SendMessage(view, WM_NCHITTEST, 0, max_position) == HTTRANSPARENT,
"maximize hit reaches native parent");
ReportControl(messenger, "a-clipped-control", width - 150, 74);
Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTMAXBUTTON,
"maximize takes precedence over overlapping workspace control bounds");
messenger.Call("cutdex_native/window_controls", "setHeaderControlRegion", Value(Map{
{Value("id"), Value("a-clipped-control")}, {Value("rect"), Value()}}));
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 23, 22)) == HTCLIENT,
"close button stays in Flutter");
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 184, 22)) == HTCLIENT,
"minimize button stays in Flutter");
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, width - 69, 22)) == HTCLIENT,
"old hardcoded maximize slot is a reported close control");
ReportControl(messenger, "maximize", width - 310, 74, "maximize");
Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTCAPTION,
"moving the maximize button removes its old hit target");
max_position = Position(view, width - 273, 22);
Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTMAXBUTTON,
"moving the maximize button updates its native hit target");
ReportControl(messenger, "maximize", width - 310, 74);
Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTCLIENT,
"a changed role updates hit behavior without moving the control");
ReportControl(messenger, "maximize", width - 310, 74, "maximize");
RECT bounds{};
GetWindowRect(window, &bounds);
Check(SendMessage(window, WM_NCHITTEST, 0, MAKELPARAM(bounds.left + 1, bounds.top + 1)) == HTTOPLEFT,
"top-left edge resizes");
Check(SendMessage(window, WM_NCHITTEST, 0, MAKELPARAM(bounds.right - 1, bounds.bottom - 1)) == HTBOTTOMRIGHT,
"bottom-right edge resizes");
Check(SendMessage(window, WM_NCHITTEST, 0, MAKELPARAM(bounds.left + 100, bounds.top + 1)) == HTTOP,
"top edge resizes");
messenger.Call("cutdex_native/window", "setHeaderInteractive", Value(false));
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 22)) == HTCLIENT,
"modal route blocks native header drag");
Check(SendMessage(window, WM_NCHITTEST, 0, max_position) == HTCLIENT,
"modal route blocks maximize hit target");
messenger.Call("cutdex_native/window", "setHeaderInteractive", Value(true));
SendMessage(window, WM_NCLBUTTONDOWN, HTMAXBUTTON, max_position);
Check(GetCapture() == window, "maximize captures the press");
SendMessage(window, WM_CANCELMODE, 0, 0);
ReleaseCapture();
Check(!IsZoomed(window), "cancelled maximize press leaves state unchanged");
POINT max_point{GET_X_LPARAM(max_position), GET_Y_LPARAM(max_position)};
ScreenToClient(window, &max_point);
SendMessage(window, WM_NCLBUTTONDOWN, HTMAXBUTTON, max_position);
SendMessage(window, WM_LBUTTONUP, 0, MAKELPARAM(max_point.x, max_point.y));
ShowWindow(window, SW_HIDE);
Check(IsZoomed(window) != FALSE, "native maximize mouse press and release");
SendMessage(window, WM_NCLBUTTONDBLCLK, HTCAPTION, Position(view, 300, 22));
ShowWindow(window, SW_HIDE);
Check(!IsZoomed(window), "double-click empty caption restores");
messenger.Call("cutdex_native/window", "toggleMaximize", Value());
ShowWindow(window, SW_HIDE);
Check(IsZoomed(window) != FALSE, "maximize command");
RECT max_bounds{}, max_client{};
GetWindowRect(window, &max_bounds);
GetClientRect(window, &max_client);
POINT origin{};
ClientToScreen(window, &origin);
Check(origin.y > max_bounds.top, "maximized client avoids invisible top frame");
Check(SendMessage(window, WM_NCHITTEST, 0, Position(view, 300, 1)) == HTCAPTION,
"maximized top is caption instead of resize");
messenger.Call("cutdex_native/window", "toggleMaximize", Value());
ShowWindow(window, SW_HIDE);
Check(!IsZoomed(window), "restore command");
MINMAXINFO limits{};
SendMessage(window, WM_GETMINMAXINFO, 0, reinterpret_cast<LPARAM>(&limits));
Check(limits.ptMinTrackSize.x == MulDiv(520, static_cast<int>(GetDpiForWindow(window)), 96) &&
limits.ptMinTrackSize.y == MulDiv(360, static_cast<int>(GetDpiForWindow(window)), 96),
"host minimum size survives native chrome and follows monitor DPI");
Configure(messenger, true, true);
const auto before = messenger.notifications.size();
SendMessage(window, WM_CLOSE, 0, 0);
Check(IsWindow(window) && messenger.notifications.size() == before + 1 &&
messenger.notifications.back() == "requestClose", "close callback is intercepted");
Configure(messenger, false);
POINT standard_origin{};
ClientToScreen(window, &standard_origin);
GetWindowRect(window, &bounds);
Check(standard_origin.y > bounds.top, "disable restores system titlebar");
chrome = nullptr;
owner.reset();
Check(!messenger.handlers["cutdex_native/window"] &&
!messenger.handlers["cutdex_native/window_controls"], "channel handlers unregister");
view = nullptr;
DestroyWindow(window);
std::cout << checks << " native window checks passed at " << GetDpiForSystem() << " DPI\n";
}
+17
View File
@@ -0,0 +1,17 @@
flutter/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
@@ -0,0 +1,64 @@
# The Flutter tooling requires that developers have a version of Visual Studio
# installed that includes CMake 3.14 or later. You should not increase this
# version, as doing so will cause the plugin to fail to compile for some
# customers of the plugin.
cmake_minimum_required(VERSION 3.14)
# Project-level configuration.
set(PROJECT_NAME "cutdex_native")
project(${PROJECT_NAME} LANGUAGES CXX)
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# This value is used when generating builds using this plugin, so it must
# not be changed
set(PLUGIN_NAME "cutdex_native_plugin")
# Any new source files that you add to the plugin should be added here.
list(APPEND PLUGIN_SOURCES
"cutdex_native_plugin.cpp"
"cutdex_native_plugin.h"
"window_chrome.cpp"
"native_file_drop.cpp"
)
# Define the plugin library target. Its name must not be changed (see comment
# on PLUGIN_NAME above).
add_library(${PLUGIN_NAME} SHARED
"include/cutdex_native/cutdex_native_plugin_c_api.h"
"cutdex_native_plugin_c_api.cpp"
${PLUGIN_SOURCES}
)
# Apply a standard set of build settings that are configured in the
# application-level CMakeLists.txt. This can be removed for plugins that want
# full control over build settings.
apply_standard_settings(${PLUGIN_NAME})
# Symbols are hidden by default to reduce the chance of accidental conflicts
# between plugins. This should not be removed; any symbols that should be
# exported should be explicitly exported with the FLUTTER_PLUGIN_EXPORT macro.
set_target_properties(${PLUGIN_NAME} PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_compile_definitions(${PLUGIN_NAME} PRIVATE FLUTTER_PLUGIN_IMPL)
# Source include directories and library dependencies. Add any plugin-specific
# dependencies here.
target_include_directories(${PLUGIN_NAME} INTERFACE
"${CMAKE_CURRENT_SOURCE_DIR}/include")
target_link_libraries(${PLUGIN_NAME} PRIVATE flutter flutter_wrapper_plugin dwmapi comctl32 ole32 shell32 uuid)
# List of absolute paths to libraries that should be bundled with the plugin.
# This list could contain prebuilt libraries, or libraries created by an
# external build triggered from this build file.
set(cutdex_native_bundled_libraries
""
PARENT_SCOPE
)
target_compile_definitions(${PLUGIN_NAME} PRIVATE NOMINMAX)
target_compile_definitions(${PLUGIN_NAME} PRIVATE
"CUTDEX_APP_VERSION=\"${FLUTTER_VERSION}\""
"CUTDEX_APP_BUILD=\"${FLUTTER_VERSION_BUILD}\"")
@@ -0,0 +1,40 @@
#include "cutdex_native_plugin.h"
#include <flutter/standard_method_codec.h>
namespace cutdex_native {
void CutdexNativePlugin::RegisterWithRegistrar(
flutter::PluginRegistrarWindows* registrar) {
registrar->AddPlugin(std::make_unique<CutdexNativePlugin>(registrar));
}
CutdexNativePlugin::CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar)
: registrar_(registrar) {
device_info_ = std::make_unique<flutter::MethodChannel<flutter::EncodableValue>>(
registrar->messenger(), "cutdex_native/device_info",
&flutter::StandardMethodCodec::GetInstance());
device_info_->SetMethodCallHandler([](const auto& call, auto result) {
if (call.method_name() != "getApplicationInfo") {
result->NotImplemented();
return;
}
result->Success(flutter::EncodableValue(flutter::EncodableMap{
{flutter::EncodableValue("appVersion"), flutter::EncodableValue(CUTDEX_APP_VERSION)},
{flutter::EncodableValue("appBuild"), flutter::EncodableValue(CUTDEX_APP_BUILD)}}));
});
const HWND view = registrar->GetView()->GetNativeWindow();
chrome_ = std::make_unique<WindowChrome>(
GetAncestor(view, GA_ROOT), view, registrar->messenger());
drop_ = std::make_unique<NativeFileDrop>(view, registrar->messenger());
delegate_id_ = registrar->RegisterTopLevelWindowProcDelegate(
[this](HWND, UINT message, WPARAM wparam, LPARAM lparam)
-> std::optional<LRESULT> {
return chrome_->HandleMessage(message, wparam, lparam);
});
}
CutdexNativePlugin::~CutdexNativePlugin() {
registrar_->UnregisterTopLevelWindowProcDelegate(delegate_id_);
drop_.reset();
chrome_.reset();
}
}
@@ -0,0 +1,25 @@
#ifndef FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_H_
#define FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_H_
#include <flutter/plugin_registrar_windows.h>
#include <flutter/method_channel.h>
#include "window_chrome.h"
#include "native_file_drop.h"
#include <memory>
namespace cutdex_native {
class CutdexNativePlugin : public flutter::Plugin {
public:
static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar);
explicit CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar);
~CutdexNativePlugin() override;
CutdexNativePlugin(const CutdexNativePlugin&) = delete;
CutdexNativePlugin& operator=(const CutdexNativePlugin&) = delete;
private:
flutter::PluginRegistrarWindows* registrar_;
int delegate_id_;
std::unique_ptr<WindowChrome> chrome_;
std::unique_ptr<NativeFileDrop> drop_;
std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> device_info_;
};
}
#endif
@@ -0,0 +1,12 @@
#include "include/cutdex_native/cutdex_native_plugin_c_api.h"
#include <flutter/plugin_registrar_windows.h>
#include "cutdex_native_plugin.h"
void CutdexNativePluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar) {
cutdex_native::CutdexNativePlugin::RegisterWithRegistrar(
flutter::PluginRegistrarManager::GetInstance()
->GetRegistrar<flutter::PluginRegistrarWindows>(registrar));
}
@@ -0,0 +1,23 @@
#ifndef FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_C_API_H_
#define FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_C_API_H_
#include <flutter_plugin_registrar.h>
#ifdef FLUTTER_PLUGIN_IMPL
#define FLUTTER_PLUGIN_EXPORT __declspec(dllexport)
#else
#define FLUTTER_PLUGIN_EXPORT __declspec(dllimport)
#endif
#if defined(__cplusplus)
extern "C" {
#endif
FLUTTER_PLUGIN_EXPORT void CutdexNativePluginCApiRegisterWithRegistrar(
FlutterDesktopPluginRegistrarRef registrar);
#if defined(__cplusplus)
} // extern "C"
#endif
#endif // FLUTTER_PLUGIN_CUTDEX_NATIVE_PLUGIN_C_API_H_
@@ -0,0 +1,367 @@
#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();
}
@@ -0,0 +1,25 @@
#ifndef FLUTTER_PLUGIN_CUTDEX_NATIVE_FILE_DROP_H_
#define FLUTTER_PLUGIN_CUTDEX_NATIVE_FILE_DROP_H_
#include <flutter/binary_messenger.h>
#include <windows.h>
// Receives Explorer file references and routes them to configured Flutter
// destinations. Must live on the window's STA thread.
class NativeFileDrop {
public:
NativeFileDrop(HWND view, flutter::BinaryMessenger* messenger);
~NativeFileDrop();
NativeFileDrop(const NativeFileDrop&) = delete;
NativeFileDrop& operator=(const NativeFileDrop&) = delete;
private:
class Target;
Target* target_ = nullptr;
HWND view_;
bool ole_initialized_ = false;
bool registered_ = false;
};
#endif // FLUTTER_PLUGIN_CUTDEX_NATIVE_FILE_DROP_H_
@@ -0,0 +1,265 @@
#include "window_chrome.h"
#include <flutter/standard_method_codec.h>
#include <dwmapi.h>
#include <windowsx.h>
#include <cmath>
namespace {
using Value = flutter::EncodableValue;
using Map = flutter::EncodableMap;
const Value* Find(const Map* map, const char* name) {
if (!map) return nullptr;
const auto it = map->find(Value(name));
return it == map->end() ? nullptr : &it->second;
}
bool Boolean(const Map* map, const char* name, bool fallback = false) {
const auto value = Find(map, name);
const auto boolean = value ? std::get_if<bool>(value) : nullptr;
return boolean ? *boolean : fallback;
}
double Number(const Map* map, const char* name, double fallback = 0) {
const auto value = Find(map, name);
if (value) {
if (const auto number = std::get_if<double>(value)) return *number;
if (const auto number = std::get_if<int32_t>(value)) return *number;
}
return fallback;
}
} // namespace
WindowChrome::WindowChrome(HWND window, HWND view,
flutter::BinaryMessenger* messenger)
: window_(window), view_(view) {
SetWindowSubclass(view_, ViewProc, reinterpret_cast<UINT_PTR>(this),
reinterpret_cast<DWORD_PTR>(this));
chrome_ = std::make_unique<flutter::MethodChannel<Value>>(
messenger, "cutdex_native/window", &flutter::StandardMethodCodec::GetInstance());
controls_channel_ = std::make_unique<flutter::MethodChannel<Value>>(
messenger, "cutdex_native/window_controls", &flutter::StandardMethodCodec::GetInstance());
chrome_->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() == "configureChrome") {
const double height = Number(map, "headerHeight", 46);
if (!map || !std::isfinite(height) || height <= 0) {
result->Error("invalid_arguments", "Expected a positive header height");
return;
}
Configure(Boolean(map, "enabled"), height,
Boolean(map, "interceptClose"), Boolean(map, "headerInteractive", true));
result->Success(Value(enabled_));
NotifyState();
} else if (call.method_name() == "setHeaderInteractive") {
const auto active = args ? std::get_if<bool>(args) : nullptr;
if (!active) { result->Error("invalid_arguments", "Expected a boolean"); return; }
interactive_ = *active;
SetMaximizeHovered(false);
result->Success();
} else if (call.method_name() == "minimize") {
ShowWindow(window_, SW_MINIMIZE);
result->Success();
} else if (call.method_name() == "toggleMaximize") {
ShowWindow(window_, IsZoomed(window_) ? SW_RESTORE : SW_MAXIMIZE);
result->Success();
} else if (call.method_name() == "close") {
// Defer destruction until the method reply has reached Flutter.
PostMessage(window_, WM_CLOSE, 0, 0);
result->Success();
} else {
result->NotImplemented();
}
});
controls_channel_->SetMethodCallHandler([this](const auto& call, auto result) {
if (call.method_name() != "setHeaderControlRegion") { result->NotImplemented(); return; }
const auto args = call.arguments();
const auto map = args ? std::get_if<Map>(args) : nullptr;
const auto id_value = Find(map, "id");
const auto id = id_value ? std::get_if<std::string>(id_value) : nullptr;
const auto rect_value = Find(map, "rect");
if (!id || !rect_value) { result->Error("invalid_arguments", "Expected id and rect"); return; }
if (std::holds_alternative<std::monostate>(*rect_value)) {
controls_.erase(*id);
} else if (const auto rect = std::get_if<Map>(rect_value)) {
Region region{Number(rect, "x"), Number(rect, "y"),
Number(rect, "width"), Number(rect, "height"), false};
const auto role_value = Find(map, "role");
const auto role = role_value ? std::get_if<std::string>(role_value) : nullptr;
region.maximize = role && *role == "maximize";
if (!std::isfinite(region.x) || !std::isfinite(region.y) ||
!std::isfinite(region.width) || !std::isfinite(region.height) ||
region.width < 0 || region.height < 0) {
result->Error("invalid_arguments", "Invalid control bounds"); return;
}
controls_[*id] = region;
} else { result->Error("invalid_arguments", "Invalid rect"); return; }
result->Success();
});
}
WindowChrome::~WindowChrome() {
chrome_->SetMethodCallHandler(nullptr);
controls_channel_->SetMethodCallHandler(nullptr);
if (IsWindow(view_)) RemoveWindowSubclass(view_, ViewProc, reinterpret_cast<UINT_PTR>(this));
}
void WindowChrome::Configure(bool enabled, double height, bool intercept_close,
bool interactive) {
// Plugin registration precedes the runner parenting the Flutter view.
window_ = GetAncestor(view_, GA_ROOT);
const bool changed = enabled_ != enabled;
enabled_ = enabled;
header_height_ = height;
intercept_close_ = intercept_close;
interactive_ = interactive;
if (!changed) return;
if (!enabled) {
maximize_pressed_ = false;
if (GetCapture() == window_) ReleaseCapture();
SetMaximizeHovered(false);
}
// Retain WS_THICKFRAME, WS_SYSMENU and the caption command styles so Windows
// still owns resizing, Alt+Space, double-click zoom and drag-to-snap.
const MARGINS margins{0, 0, enabled ? 1 : 0, 0};
DwmExtendFrameIntoClientArea(window_, &margins);
SetWindowPos(window_, nullptr, 0, 0, 0, 0,
SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
}
LRESULT WindowChrome::HitTest(LPARAM position) const {
POINT point{GET_X_LPARAM(position), GET_Y_LPARAM(position)};
RECT window_rect{};
GetWindowRect(window_, &window_rect);
const UINT dpi = GetDpiForWindow(window_);
const int frame = GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) +
GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi);
if (!IsZoomed(window_)) {
const bool left = point.x < window_rect.left + frame;
const bool right = point.x >= window_rect.right - frame;
const bool top = point.y < window_rect.top + frame;
const bool bottom = point.y >= window_rect.bottom - frame;
if (top) return left ? HTTOPLEFT : right ? HTTOPRIGHT : HTTOP;
if (bottom) return left ? HTBOTTOMLEFT : right ? HTBOTTOMRIGHT : HTBOTTOM;
if (left) return HTLEFT;
if (right) return HTRIGHT;
}
if (!interactive_) return HTCLIENT;
ScreenToClient(view_, &point);
const double scale = dpi / 96.0;
const double x = point.x / scale;
const double y = point.y / scale;
if (y < 0 || y >= header_height_) return HTCLIENT;
// Flutter owns button sizes and positions. Only the reported maximize region
// becomes a native hit target for Windows 11 Snap Layouts.
LRESULT hit = HTCAPTION;
for (const auto& entry : controls_) {
const auto& region = entry.second;
if (x >= region.x && x < region.x + region.width &&
y >= region.y && y < region.y + region.height) {
// The caption strip is above workspace controls, including controls
// whose layout bounds extend beyond a clipped scroll viewport.
if (region.maximize) return HTMAXBUTTON;
hit = HTCLIENT;
}
}
return hit;
}
void WindowChrome::NotifyState() {
chrome_->InvokeMethod("windowState", std::make_unique<Value>(Map{
{Value("maximized"), Value(IsZoomed(window_) != FALSE)},
{Value("maximizeHovered"), Value(maximize_hovered_)}}));
}
void WindowChrome::SetMaximizeHovered(bool hovered) {
if (maximize_hovered_ == hovered) return;
maximize_hovered_ = hovered;
NotifyState();
}
std::optional<LRESULT> WindowChrome::HandleMessage(UINT message, WPARAM wparam,
LPARAM lparam) {
if (!enabled_) return std::nullopt;
switch (message) {
case WM_NCCALCSIZE: {
// Let Windows keep the side/bottom resize borders, replacing only the top.
auto rect = wparam ? &reinterpret_cast<NCCALCSIZE_PARAMS*>(lparam)->rgrc[0]
: reinterpret_cast<RECT*>(lparam);
const LONG top = rect->top;
DefWindowProc(window_, message, wparam, lparam);
const UINT dpi = GetDpiForWindow(window_);
rect->top = top + (IsZoomed(window_) ?
GetSystemMetricsForDpi(SM_CYSIZEFRAME, dpi) +
GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) : 0);
return 0;
}
case WM_NCHITTEST:
return HitTest(lparam);
case WM_NCMOUSEMOVE: {
SetMaximizeHovered(wparam == HTMAXBUTTON);
TRACKMOUSEEVENT tracking{sizeof(TRACKMOUSEEVENT), TME_LEAVE | TME_NONCLIENT,
window_, 0};
TrackMouseEvent(&tracking);
// Continue through DWM/DefWindowProc so Snap Layouts can appear.
break;
}
case WM_NCMOUSELEAVE:
SetMaximizeHovered(false);
break;
case WM_NCLBUTTONDOWN:
case WM_NCLBUTTONDBLCLK:
if (wparam == HTMAXBUTTON) {
maximize_pressed_ = true;
SetCapture(window_);
return 0;
}
break;
case WM_LBUTTONUP:
if (maximize_pressed_) {
POINT point{GET_X_LPARAM(lparam), GET_Y_LPARAM(lparam)};
ClientToScreen(window_, &point);
const bool activate = HitTest(MAKELPARAM(point.x, point.y)) == HTMAXBUTTON;
maximize_pressed_ = false;
ReleaseCapture();
SetMaximizeHovered(false);
if (activate) ShowWindow(window_, IsZoomed(window_) ? SW_RESTORE : SW_MAXIMIZE);
return 0;
}
break;
case WM_CAPTURECHANGED:
case WM_CANCELMODE:
maximize_pressed_ = false;
break;
case WM_SIZE:
NotifyState();
break;
case WM_CLOSE:
if (intercept_close_) {
chrome_->InvokeMethod("requestClose", nullptr);
return 0;
}
break;
case WM_DWMCOMPOSITIONCHANGED: {
const MARGINS margins{0, 0, 1, 0};
DwmExtendFrameIntoClientArea(window_, &margins);
break;
}
}
LRESULT result = 0;
if (DwmDefWindowProc(window_, message, wparam, lparam, &result)) return result;
return std::nullopt;
}
LRESULT CALLBACK WindowChrome::ViewProc(HWND window, UINT message, WPARAM wparam,
LPARAM lparam, UINT_PTR id, DWORD_PTR data) {
const auto chrome = reinterpret_cast<WindowChrome*>(data);
if (message == WM_NCHITTEST && chrome->enabled_ &&
chrome->HitTest(lparam) != HTCLIENT) {
// Flutter is a child HWND covering the client area. Let native caption and
// resize hits pass through to its parent while keeping controls in Flutter.
return HTTRANSPARENT;
}
if (message == WM_NCDESTROY) RemoveWindowSubclass(window, ViewProc, id);
return DefSubclassProc(window, message, wparam, lparam);
}
@@ -0,0 +1,45 @@
#pragma once
#include <flutter/binary_messenger.h>
#include <flutter/encodable_value.h>
#include <flutter/method_channel.h>
#include <windows.h>
#include <commctrl.h>
#include <map>
#include <memory>
#include <optional>
#include <string>
// Keeps the system resize frame and window commands around a Flutter header.
class WindowChrome {
public:
WindowChrome(HWND window, HWND view, flutter::BinaryMessenger* messenger);
~WindowChrome();
std::optional<LRESULT> HandleMessage(UINT message, WPARAM wparam, LPARAM lparam);
private:
struct Region {
double x, y, width, height;
bool maximize;
};
void Configure(bool enabled, double height, bool intercept_close,
bool interactive);
LRESULT HitTest(LPARAM position) const;
void NotifyState();
void SetMaximizeHovered(bool hovered);
static LRESULT CALLBACK ViewProc(HWND window, UINT message, WPARAM wparam,
LPARAM lparam, UINT_PTR id, DWORD_PTR data);
HWND window_;
HWND view_;
bool enabled_ = false;
bool intercept_close_ = false;
bool interactive_ = true;
bool maximize_hovered_ = false;
bool maximize_pressed_ = false;
double header_height_ = 46;
std::map<std::string, Region> controls_;
std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> chrome_;
std::unique_ptr<flutter::MethodChannel<flutter::EncodableValue>> controls_channel_;
};