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

@@ -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,
);
},
);
}
}