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

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

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

822 lines
32 KiB
Dart

import 'package:cutdex/app/editor_theme.dart';
// Opt-in, real desktop runtime validation. Source files are referenced, never copied.
// CUTDEX_VALIDATION_KIND=audio also checks source-preview transport and mute controls.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math' as math;
import 'package:cutdex/features/media/media_asset_drag.dart';
import 'package:cutdex/features/media/media_panel.dart';
import 'package:cutdex/features/preview/preview_panel.dart';
import 'package:cutdex/features/properties/properties_panel.dart';
import 'package:cutdex/features/timeline/timeline_panel.dart';
import 'package:cutdex/features/timeline/timeline_external_drop_target.dart';
import 'package:cutdex/l10n/app_localizations.dart';
import 'package:cutdex/persistence/app_database.dart';
import 'package:cutdex/workspace/media_file_extensions.dart';
import 'package:cutdex/workspace/preview_target.dart';
import 'package:cutdex/workspace/projects.dart';
import 'package:cutdex/workspace/timeline_provider.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:drift/native.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:path/path.dart' as p;
void main() {
const root = String.fromEnvironment('CUTDEX_VALIDATION_ROOT');
const sourceDirectory = String.fromEnvironment('CUTDEX_VALIDATION_SOURCE');
const configured = root != '' && sourceDirectory != '';
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets(
'Downloads: native drop, timeline drag and editing with real playback',
(tester) async {
const filter = String.fromEnvironment('CUTDEX_VALIDATION_FILTER');
const directDrop = bool.fromEnvironment('CUTDEX_VALIDATION_DIRECT_DROP');
const dropOnly = bool.fromEnvironment('CUTDEX_VALIDATION_DROP_ONLY');
const kind = String.fromEnvironment(
'CUTDEX_VALIDATION_KIND',
defaultValue: 'video',
);
expect(kind, anyOf('video', 'audio'));
Directory(root).createSync(recursive: true);
final paths =
Directory(sourceDirectory)
.listSync()
.whereType<File>()
.map((file) => file.path)
.where(
(path) =>
mediaKindForPath(path) == kind &&
(filter.isEmpty ||
filter
.split(',')
.any((value) => p.basename(path).contains(value))),
)
.toList()
..sort();
expect(paths, isNotEmpty);
// AppKit menu tracking consumes physical input outside the test binding.
// Exercise the existing Flutter menu fallback; native playback stays real.
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('cutdex_native/context_menu'),
(_) async => throw MissingPluginException(),
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
const MethodChannel('cutdex_native/context_menu'),
null,
),
);
final results = <Map<String, Object?>>[];
final report = File(
p.join(
root,
kind == 'audio'
? 'audio-editor-results.json'
: 'downloads-editor-results.json',
),
);
final database = AppDatabase(NativeDatabase.memory());
final container = ProviderContainer(
overrides: [appDatabaseProvider.overrideWithValue(database)],
);
addTearDown(() async {
container.dispose();
await database.close();
});
final projects = container.read(projectsProvider.notifier);
final projectPath = p.join(
root,
'Downloads-${DateTime.now().millisecondsSinceEpoch}.cutdex',
);
void save() => report.writeAsStringSync(
const JsonEncoder.withIndent(' ').convert({
'validatedAt': DateTime.now().toIso8601String(),
'sourceDirectory': sourceDirectory,
'projectPath': projectPath,
'directDrop': directDrop,
'dropOnly': dropOnly,
'kind': kind,
'method':
'Real ${Platform.operatingSystem} application and native playback runtime; '
'${directDrop ? 'injected native file-drop events directly on the timeline' : 'injected native file-drop events into the library, pointer drag from media tiles'}, '
'toolbar and property slider. AppKit menu bridge disabled only in test '
'to exercise production Flutter context-menu fallback.',
'files': results,
}),
);
Future<void> until(
bool Function() predicate,
String stage, {
int seconds = 40,
}) async {
final deadline = DateTime.now().add(Duration(seconds: seconds));
while (!predicate()) {
if (DateTime.now().isAfter(deadline)) {
throw StateError('Timed out: $stage');
}
await tester.pump(const Duration(milliseconds: 100));
}
await tester.pump();
}
Future<void> nativeDrop(
String phase,
String path,
int session, {
bool timeline = false,
Offset position = Offset.zero,
}) async {
final done = Completer<void>();
// The same entry point receives Finder NSDraggingInfo events in production.
tester.binding.defaultBinaryMessenger.handlePlatformMessage(
timeline
? 'cutdex_native/file_drop/timeline'
: 'cutdex_native/file_drop/media-library',
const StandardMethodCodec().encodeMethodCall(
MethodCall('event', {
'phase': phase,
'session': session,
'x': position.dx,
'y': position.dy,
'files': [
{'path': path},
],
}),
),
(_) => done.complete(),
);
await done.future;
await tester.pump();
}
expect(
await projects.open(
projectPath,
name: 'Downloads 操作验证',
initialTimelineName: '01',
),
isTrue,
);
final projectId = container
.read(projectsProvider)
.requireValue
.activeProject!
.id;
for (var index = 0; index < paths.length; index++) {
final path = paths[index];
final before = File(path).statSync();
final checks = <Map<String, Object?>>[];
final result = <String, Object?>{
'path': path,
'checks': checks,
'passed': false,
};
results.add(result);
save();
String stage = 'setup';
Future<void> check(String name, Future<void> Function() action) async {
stage = name;
debugPrint(
'DOWNLOADS_WORKFLOW ${index + 1}/${paths.length} $name ${p.basename(path)}',
);
await action();
checks.add({'stage': name, 'passed': true});
save();
}
try {
if (index > 0) {
expect(
await projects.createTimeline(
name: '${index + 1}'.padLeft(2, '0'),
),
isTrue,
);
}
final timelineId = container
.read(projectsProvider)
.requireValue
.timeline!
.id;
final ids = (projectId, timelineId);
result['timelineId'] = timelineId;
await tester.pumpWidget(
UncontrolledProviderScope(
container: container,
child: MaterialApp(
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
locale: const Locale('zh'),
theme: EditorTheme.penLight,
home: Scaffold(
body: Column(
children: [
Expanded(
child: Row(
children: [
SizedBox(
width: 300,
child: MediaPanel(
projectId: projectId,
grid: true,
onGridChanged: (_) {},
),
),
Expanded(
child: EditorPreviewPanel(
projectId: projectId,
timelineId: timelineId,
),
),
SizedBox(
width: 320,
child: EditorPropertiesPanel(
projectId: projectId,
timelineId: timelineId,
),
),
],
),
),
SizedBox(
height: 330,
child: EditorTimelinePanel(
projectId: projectId,
timelineId: timelineId,
),
),
],
),
),
),
),
);
await tester.pump(const Duration(milliseconds: 400));
final session = await container.read(
editorTimelineProvider(ids.$1, ids.$2).future,
);
final sequence = session.activeSequenceId!;
final view = session.view(sequence);
if (directDrop) {
await check('nativeDropDirectlyIntoTimeline', () async {
final rect = tester.getRect(
find.byType(TimelineExternalDropTarget),
);
final position = Offset(
24,
view.camera.screenYForWorld(
view.geometry.primaryTop +
view.geometry.primaryHeight / 2 +
(kind == 'audio' ? 100 : 0),
TimelineViewportRect(width: rect.width, height: rect.height),
),
);
await nativeDrop(
'enter',
path,
index + 1,
timeline: true,
position: position,
);
await tester.pump(const Duration(milliseconds: 500));
await nativeDrop(
'drop',
path,
index + 1,
timeline: true,
position: position,
);
await until(
() => session.sequenceDurationTicks(sequence) > 0,
'direct timeline insert',
);
expect(
container
.read(projectsProvider)
.requireValue
.assets
.any((asset) => asset.name == p.basename(path)),
isTrue,
);
});
} else {
await check('nativeDropIntoMediaLibrary', () async {
await nativeDrop('enter', path, index + 1);
await nativeDrop('drop', path, index + 1);
await until(
() => container
.read(projectsProvider)
.requireValue
.assets
.any((a) => a.name == p.basename(path)),
'import',
);
});
final asset = container
.read(projectsProvider)
.requireValue
.assets
.firstWhere((a) => a.name == p.basename(path));
await check('sourcePreviewSeekPlayPause', () async {
final target = container.read(
previewTargetProvider(ids.$1, ids.$2),
);
try {
await target.openSource(asset);
final source = target.source!;
await until(() => source.canPlay, 'source ready');
expect(source.audioOnly, kind == 'audio');
for (final position in [0, source.durationTick ~/ 2]) {
await source.control(
SourcePreviewAction.seek,
at: CommandTime(position, TimelineClock.ticksPerSecond),
);
await until(
() => !source.busy && source.canPlay,
'source seek settled',
);
expect(source.error, isNull);
await tester.pump();
await tester.tap(find.byTooltip('播放'));
await until(
() =>
source.playing &&
source.positionTick >
position + TimelineClock.ticksPerSecond ~/ 5,
'source play advances',
);
expect(source.error, isNull);
await until(
() => find.byTooltip('暂停播放').evaluate().isNotEmpty,
'source pause button',
);
await tester.tap(find.byTooltip('暂停播放'));
await until(
() => !source.playing && !source.busy,
'source pause',
);
final paused = source.positionTick;
for (var i = 0; i < 4; i++) {
await tester.pump(const Duration(milliseconds: 100));
}
expect(
(source.positionTick - paused).abs(),
lessThan(TimelineClock.ticksPerSecond ~/ 10),
);
expect(source.error, isNull);
}
} finally {
await target.closeSource();
await tester.pump();
}
});
await check('pointerDragIntoTimeline', () async {
final tile = find.byWidgetPredicate(
(widget) =>
widget is Draggable<MediaAssetDrag> &&
widget.data?.assetId == asset.id,
);
// Scroll the media panel as needed without opening a source preview.
final scroll = tester.state<ScrollableState>(
find
.descendant(
of: find.byType(MediaPanel),
matching: find.byType(Scrollable),
)
.last,
);
scroll.position.jumpTo(0);
await tester.pump(const Duration(milliseconds: 200));
for (
var attempt = 0;
tile.evaluate().isEmpty && attempt < 20;
attempt++
) {
scroll.position.jumpTo(
math.min(
scroll.position.maxScrollExtent,
scroll.position.pixels + 180,
),
);
await tester.pump(const Duration(milliseconds: 150));
}
expect(tile, findsOneWidget);
await tester.ensureVisible(tile);
await tester.pump();
final surfaceRect = tester.getRect(
find.byKey(const Key('editor-timeline-surface')),
);
final viewport = TimelineViewportRect(
width: surfaceRect.width,
height: surfaceRect.height,
);
final destination =
surfaceRect.topLeft +
Offset(
24,
view.camera.screenYForWorld(
view.geometry.primaryTop +
view.geometry.primaryHeight / 2 +
(kind == 'audio' ? 100 : 0),
viewport,
),
);
final gesture = await tester.startGesture(
tester.getCenter(tile),
kind: PointerDeviceKind.mouse,
);
await gesture.moveBy(const Offset(24, 0));
await tester.pump();
await gesture.moveTo(destination);
await tester.pump(const Duration(seconds: 1));
final drop = tester.state<TimelineExternalDropTargetState>(
find.byType(TimelineExternalDropTarget),
);
debugPrint(
'DOWNLOADS_DRAG preview=${drop.hasPreview} enabled=${drop.enabled} error=${drop.error} placement=${drop.placementError} duration=${drop.preparedMedia?.metadata.duration}',
);
await gesture.up();
await until(
() => session.sequenceDurationTicks(sequence) > 0,
'timeline insert',
);
});
}
final query = session.persistence.timeline(sequence).current.query();
final original = session.persistence
.timeline(sequence)
.exportDto()
.elements
.map((dto) => query.elementById(dto.id)!)
.firstWhere((h) {
final record = query.element(h);
return record.payloadRef != null &&
session.payloadFor(record.payloadRef!)?.type == kind;
});
final clipId = query.element(original).id;
final originalDuration = query.element(original).duration;
result['originalDurationTicks'] = originalDuration;
await check('sourceDurationPreserved', () async {
final source = await container
.read(runtimeConnectionProvider)
.probe(
MediaReference(id: 'duration-check', uri: File(path).uri),
);
final numerator = BigInt.from(source.duration.numerator);
final denominator = BigInt.from(source.duration.denominator);
final expectedTicks =
numerator *
BigInt.from(TimelineClock.ticksPerSecond) ~/
denominator;
expect(BigInt.from(originalDuration), expectedTicks);
expect(query.element(original).sourceDuration, originalDuration);
expect(query.element(original).mediaDuration, originalDuration);
result['nativeSourceDuration'] = source.duration.toMap();
result['discardedTickFraction'] =
'${numerator * BigInt.from(TimelineClock.ticksPerSecond) % denominator}/$denominator';
});
final frameTicks = view.format.frameGrid.quantumTicks;
final splitTick = math.max(
frameTicks,
((math.min(4 * TimelineClock.ticksPerSecond, originalDuration / 2) /
frameTicks)
.floor()) *
frameTicks,
);
await until(
() =>
container
.read(editorPreviewProvider(ids.$1, ids.$2))
.asData
?.value
?.ready ==
true,
'preview ready',
);
var preview = container
.read(editorPreviewProvider(ids.$1, ids.$2))
.requireValue!;
container.read(previewTargetProvider(ids.$1, ids.$2)).showTimeline();
Future<void> seek(int tick) async {
var waits = 0;
debugPrint('DOWNLOADS_SEEK stage=$stage tick=$tick');
await until(() {
// Import/autosave can replace the preview binding. Follow the
// live provider rather than waiting on a disposed controller.
final active = container
.read(editorPreviewProvider(ids.$1, ids.$2))
.asData
?.value;
if (active != null && active.error != null) {
throw StateError('Native preview: ${active.error}');
}
if (active == null || !active.ready || active.busy) {
if (waits++ % 50 == 0) {
debugPrint(
'DOWNLOADS_WAIT ready=${active?.ready} busy=${active?.busy} '
'playing=${active?.playing} native=${active?.session?.snapshot?.state}',
);
}
return false;
}
preview = active;
return true;
}, 'timeline preview ready for seek');
expect(preview.error, isNull);
await preview.controlPreview(
sequence,
PreviewAction.seek,
at: CommandTime(tick, TimelineClock.ticksPerSecond),
);
await until(() => !preview.busy, 'seek');
expect(preview.error, isNull);
}
Future<void> playPause() async {
final start = preview.positionTick;
await tester.tap(find.byTooltip('播放'));
await until(
() =>
preview.playing &&
preview.positionTick >
start +
math.min(
TimelineClock.ticksPerSecond ~/ 4,
math.max(
frameTicks,
(session.sequenceDurationTicks(sequence) -
start) ~/
3,
),
),
'play advances',
);
expect(preview.error, isNull);
await until(
() => find.byTooltip('暂停播放').evaluate().isNotEmpty,
'pause button renders',
seconds: 5,
);
await tester.tap(find.byTooltip('暂停播放'));
await until(() => !preview.playing && !preview.busy, 'pause');
final paused = preview.positionTick;
await tester.pump(const Duration(milliseconds: 400));
expect(
(preview.positionTick - paused).abs(),
lessThan(TimelineClock.ticksPerSecond ~/ 10),
);
expect(preview.error, isNull);
final state = preview.queryPreview(sequence);
(result.putIfAbsent(
'playbackSamples',
() => <Map<String, Object?>>[],
) as List).add({
'startTick': start,
'pausedTick': paused,
'presentedVideoFrames': state.presentedVideoFrameCount,
'droppedVideoFrames': state.droppedVideoFrameCount,
'maximumVideoFrameGapMs': state.maximumVideoFrameGapMs,
});
}
await check('playAndPause', () async {
await seek(0);
await playPause();
});
if (dropOnly) {
await check('seekImportedClip', () async {
await seek(
math.min(
2 * TimelineClock.ticksPerSecond,
originalDuration ~/ 2,
),
);
await playPause();
});
await check('saveImportedClip', () async {
await session.flush();
expect(session.saveError, isNull);
final saved = session.persistence.timeline(sequence).exportDto();
final content = saved.elements
.where((element) => element.payloadRef != null)
.single;
expect(
TimelineClock.standard.toTicks(content.duration),
originalDuration,
);
expect(content.sourceRange.duration, content.duration);
expect(content.mediaRange!.duration, content.duration);
});
result['passed'] = true;
final after = File(path).statSync();
result['sourceUnchanged'] =
before.size == after.size && before.modified == after.modified;
if (result['sourceUnchanged'] != true) result['passed'] = false;
save();
continue;
}
await check('splitFromToolbar', () async {
preview.selectVisual(clipId);
await seek(splitTick);
await tester.pump();
await tester.tap(find.byTooltip('在播放头处分割'));
await tester.pump(const Duration(milliseconds: 500));
final q = session.persistence.timeline(sequence).current.query();
final clips = session.persistence
.timeline(sequence)
.exportDto()
.elements
.map((dto) => q.elementById(dto.id)!)
.where((h) {
final record = q.element(h);
return record.payloadRef != null &&
session.payloadFor(record.payloadRef!)?.type == kind;
})
.toList();
expect(clips.length, 2);
expect(q.element(q.elementById(clipId)!).duration, splitTick);
expect(
clips.map((h) => q.element(h).duration).reduce((a, b) => a + b),
originalDuration,
);
await seek(
math.max(0, splitTick - TimelineClock.ticksPerSecond ~/ 10),
);
await playPause();
});
await check('speedFromPropertySlider', () async {
preview.selectVisual(clipId);
await tester.pump();
await tester.tap(find.byKey(const ValueKey('property-tab-speed')));
await tester.pump();
final slider = find.descendant(
of: find.byKey(const Key('clip-speed-slider')),
matching: find.byType(Slider),
);
expect(slider, findsOneWidget);
// Drag the native editor's logarithmic slider, verify the actual retime map.
for (final requestedSpeed in [2.0, 0.5]) {
final rect = tester.getRect(slider);
final oldValue = tester.widget<Slider>(slider).value;
final pos = (math.log(requestedSpeed) / math.ln10 + 1) / 3;
final gesture = await tester.startGesture(
Offset(
rect.left + 12 + (rect.width - 24) * oldValue,
rect.center.dy,
),
);
await gesture.moveTo(
Offset(
rect.left + 12 + (rect.width - 24) * pos,
rect.center.dy,
),
);
await tester.pump();
await gesture.up();
await tester.pump(const Duration(milliseconds: 500));
final q = session.persistence.timeline(sequence).current.query();
final record = q.element(q.elementById(clipId)!);
final speed = session.clipSpeed(record)!;
expect(speed, closeTo(requestedSpeed, 0.05));
expect(
record.duration,
closeTo(
splitTick / requestedSpeed,
TimelineClock.ticksPerSecond / 4,
),
);
(result.putIfAbsent('testedSpeeds', () => <double>[]) as List)
.add(speed);
await seek(0);
await playPause();
}
});
if (kind == 'audio') {
await check('muteAndUnmuteFromProperties', () async {
preview.selectVisual(clipId);
await tester.pump();
await tester.tap(
find.byKey(const ValueKey('property-tab-audio')),
);
await tester.pump();
for (final muted in [true, false]) {
await tester.tap(find.byKey(const Key('audio-mute')));
await tester.pump(const Duration(milliseconds: 500));
final q = session.persistence
.timeline(sequence)
.current
.query();
expect(
ClipAudioGain.fromRecord(q.element(q.elementById(clipId)!))
.muted,
muted,
);
await seek(0);
await playPause();
}
});
} else if (session.hasAudio(query.element(original))) {
await check('detachAudioFromContextMenu', () async {
await seek(0);
preview.selectVisual(clipId);
await tester.pump();
final surface = find.byKey(const Key('editor-timeline-surface'));
final bounds = tester.getRect(surface);
final frame = view.project(
TimelineViewportRect(
width: bounds.width,
height: bounds.height,
),
);
// First primary video spans the first two seconds in the visible viewport.
final clipIndex = Iterable<int>.generate(frame.length)
.firstWhere((i) {
final handle = view.elementForIdentity(frame.identityAt(i));
return handle != null &&
view.version.kernelVersion.query().element(handle).id ==
clipId;
});
final clipBounds = view.presentationBoundsAt(frame, clipIndex);
final point =
bounds.topLeft +
Offset(
math.max(clipBounds.left + 15, 20),
clipBounds.center.dy,
);
final contextGesture = await tester.startGesture(
point,
kind: PointerDeviceKind.mouse,
buttons: kSecondaryMouseButton,
);
await contextGesture.up();
await until(
() => find.text('分离音频').evaluate().isNotEmpty,
'audio menu',
);
await tester.tap(find.text('分离音频'));
await tester.pump(const Duration(milliseconds: 500));
final q = session.persistence.timeline(sequence).current.query();
final video = q.element(q.elementById(clipId)!);
expect(ClipAudioGain.fromRecord(video).muted, isTrue);
expect(ClipAudioGain.isDetached(video), isTrue);
final audio = session.persistence
.timeline(sequence)
.exportDto()
.elements
.map((dto) => q.element(q.elementById(dto.id)!))
.where(
(r) =>
r.payloadRef != null &&
session.payloadFor(r.payloadRef!)?.type == 'audio',
)
.toList();
expect(audio.length, 1);
expect(audio.single.duration, video.duration);
expect(audio.single.sourceDuration, video.sourceDuration);
expect(
session.clipSpeed(audio.single),
closeTo(session.clipSpeed(video)!, 0.001),
);
result['detachedAudioId'] = audio.single.id.value;
await seek(0);
await playPause();
});
}
await check('save', () async {
await session.flush();
expect(session.saveError, isNull);
});
result['passed'] = true;
} catch (error, stack) {
checks.add({'stage': stage, 'passed': false, 'error': '$error'});
debugPrint('DOWNLOADS_WORKFLOW FAILED $stage $error\n$stack');
}
final after = File(path).statSync();
result['sourceUnchanged'] =
before.size == after.size && before.modified == after.modified;
if (result['sourceUnchanged'] != true) result['passed'] = false;
save();
}
await tester.pumpWidget(const SizedBox.shrink());
expect(
results.where((r) => r['passed'] != true).toList(),
isEmpty,
reason: 'See ${report.path}',
);
},
skip: !configured,
timeout: const Timeout(Duration(minutes: 30)),
);
}