import 'dart:convert'; import 'dart:io'; import 'package:crypto/crypto.dart'; import 'package:cutdex/integrations/platform/file_picker.dart'; import 'package:cutdex/workspace/external_media_import.dart'; import 'package:cutdex/workspace/media_import.dart'; import 'package:cutdex/workspace/persistence/project_workspace.dart'; import 'package:cutdex/workspace/persistence/timeline_creation_names.dart'; import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import 'package:path/path.dart' as p; import 'support/android_preview_measurement.dart' show pumpUntil; // Opt-in: select only a generated video fixture in the real system picker. // Re-run without CUTDEX_DOCUMENT_SELECT after deleting the original fixture. void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); const rootPath = String.fromEnvironment('CUTDEX_DOCUMENT_ROOT'); const select = bool.fromEnvironment('CUTDEX_DOCUMENT_SELECT'); const expectedHash = String.fromEnvironment('CUTDEX_DOCUMENT_SHA256'); testWidgets( 'Android document import survives provider removal and app restart', (tester) async { expect(Platform.isAndroid, isTrue); expect(rootPath, isNotEmpty); final root = await Directory(rootPath).create(recursive: true); final projectPath = p.join(root.path, 'Document.cutdex'); final reportFile = File( p.join(root.path, select ? 'import.json' : 'reopen.json'), ); final report = {'select': select, 'complete': false}; void save() => reportFile.writeAsStringSync(jsonEncode(report)); final runtime = CutdexRuntime(); ProjectWorkspace createWorkspace() => ProjectWorkspace( creationNames: const TimelineCreationNames( timeline: 'Test', sequence: 'Test', storyline: 'Test', ), runtime: runtime, ); var workspace = createWorkspace(); RuntimeSession? preview; try { await tester.pumpWidget( const MaterialApp( home: Scaffold( body: Center(child: Text('Document import validation')), ), ), ); save(); if (select) { debugPrint('DOCUMENT_PICKER_READY'); final files = await tester.runAsync( () => const AppFilePicker().pickFiles(allowedExtensions: ['mp4']), ); expect(files, hasLength(1)); expect(files!.single, isA()); report['sourceUri'] = files.single.sourceUri.toString(); save(); await tester.runAsync(() async { final providerInfo = await runtime.probe( MediaReference( id: 'provider-original', uri: files.single.sourceUri, ), ); expect(providerInfo.videoTrackCount, greaterThan(0)); expect(providerInfo.audioTrackCount, greaterThan(0)); report['providerVideoTracks'] = providerInfo.videoTrackCount; report['providerAudioTracks'] = providerInfo.audioTrackCount; await workspace.open(projectPath, name: 'Document'); final projectId = workspace.project!.info.id; final result = await workspace.importExternalMedia(projectId, [ files.single, files.single, ]); expect(result.failures, isEmpty); expect(result.added, 1); expect(result.duplicates, 1); final asset = result.assets.single; expect(asset.storage, AssetStorage.managed); expect(asset.name, files.single.displayName); final locations = await const MediaFileResolver().resolve( files, result.assets, ); expect( locations[files.single], contains(mediaSourceLocation(asset)), ); report['assetId'] = asset.id; report['assetName'] = asset.name; report['managedLocation'] = asset.location; report['byteLength'] = asset.byteLength; report['duplicates'] = result.duplicates; await workspace.close(); workspace = createWorkspace(); }); } await tester.runAsync(() => workspace.open(projectPath)); final assets = await tester.runAsync( () => workspace.project!.listAssets(), ); expect(assets, hasLength(1)); final asset = assets!.single; expect(asset.storage, AssetStorage.managed); final uri = (await tester.runAsync( () => workspace.project!.resolveAsset(asset), ))!; expect(uri.scheme, 'file'); final hash = await tester.runAsync( () async => (await sha256.bind(File.fromUri(uri).openRead()).first) .toString(), ); if (expectedHash.isNotEmpty) expect(hash, expectedHash); report['sha256'] = hash; report['resolvedUri'] = uri.toString(); final media = MediaReference(id: asset.id, uri: uri); final info = (await tester.runAsync(() => runtime.probe(media)))!; expect(info.videoTrackCount, greaterThan(0)); expect(info.audioTrackCount, greaterThan(0)); final thumbnail = (await tester.runAsync( () => runtime.thumbnail( ThumbnailRequest( media: media, time: MediaTime(1, 1), maximumWidth: 320, maximumHeight: 180, ), ), ))!; expect(thumbnail.data, isNotEmpty); final duration = MediaTime(6, 1); final range = MediaRange(start: MediaTime(0, 1), duration: duration); final plan = ExecutionPlan( duration: duration, renderSize: RenderSize(320, 180), frameDuration: MediaTime(1, 30), media: [media], visualLayers: [ VisualLayer( id: 'video', mediaId: media.id, sourceRange: range, timelineRange: range, inputColorSpace: RenderColorSpace.rec709, ), ], audioLayers: [ AudioLayer( id: 'audio', mediaId: media.id, sourceRange: range, timelineRange: range, ), ], ); final session = (await tester.runAsync(runtime.createSession))!; preview = session; await tester.runAsync(() => session.load(plan)); await tester.pumpWidget( MaterialApp( home: Center( child: SizedBox( width: 320, height: 180, child: RuntimePreview(session: session), ), ), ), ); await pumpUntil( tester, () => (session.snapshot?.presentedVideoFrameCount ?? 0) > 0, 'document first frame', ); final before = (await tester.runAsync(session.refresh))!; await tester.runAsync(session.play); await tester.runAsync( () => Future.delayed(const Duration(seconds: 1)), ); await tester.pump(); final playing = (await tester.runAsync(session.refresh))!; expect(playing.message, isNull); expect(playing.position.seconds, greaterThan(before.position.seconds)); expect( playing.presentedVideoFrameCount, greaterThan(before.presentedVideoFrameCount ?? 0), ); await tester.runAsync(session.pause); await tester.runAsync(() => session.seek(MediaTime(3, 1))); final destination = File( p.join(root.path, select ? 'import-export.mp4' : 'reopen-export.mp4'), ); if (await destination.exists()) await destination.delete(); final exported = (await tester.runAsync( () => session.export(plan, destination.uri), ))!; final exportInfo = (await tester.runAsync( () => runtime.probe(MediaReference(id: 'export', uri: exported)), ))!; expect(exportInfo.videoTrackCount, greaterThan(0)); expect(exportInfo.audioTrackCount, greaterThan(0)); report.addAll({ 'complete': true, 'videoTracks': info.videoTrackCount, 'audioTracks': info.audioTrackCount, 'presentedFrames': playing.presentedVideoFrameCount, 'exportUri': exported.toString(), 'exportDuration': exportInfo.duration.seconds, }); save(); debugPrint('DOCUMENT_IMPORT_PASSED ${jsonEncode(report)}'); } catch (error, stack) { report.addAll({'error': error.toString(), 'stack': stack.toString()}); save(); rethrow; } finally { await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await preview?.close(); await workspace.close(); }); } }, timeout: const Timeout(Duration(minutes: 10)), ); }