import 'support/creation_names.dart'; import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/integrations/runtime/timeline_thumbnails.dart'; import 'package:cutdex/features/media/transcription_dialog.dart'; import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex_native/cutdex_native.dart'; import 'package:cutdex/features/properties/canvas_presets.dart'; import 'package:cutdex_sdk/editor.dart'; import 'dart:async'; import 'dart:convert'; import 'package:cutdex/features/timeline/timeline_external_drop_target.dart'; import 'package:cutdex/features/timeline/timeline_asset_drop_target.dart'; import 'package:cutdex/features/media/media_asset_drag.dart'; import 'dart:io'; import 'dart:ui' as ui; import 'package:flutter/rendering.dart'; import 'package:cutdex/workspace/timeline_provider.dart'; import 'package:cutdex/features/timeline/timeline_panel.dart'; import 'package:cutdex/features/properties/properties_panel.dart'; import 'package:cutdex/features/properties/picture_properties.dart'; import 'package:cutdex_sdk/preview.dart'; import 'package:cutdex/features/preview/preview_panel.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:cutdex/features/media/media_panel.dart'; import 'package:cutdex/workspace/projects.dart'; import 'package:cutdex/workspace/project_state.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex/workspace/persistence/project_workspace.dart'; import 'package:cutdex/workspace/timeline_session.dart'; import 'package:cutdex/workspace/timeline_view_state.dart'; import 'package:cutdex/persistence/app_database.dart'; import 'package:cutdex/persistence/app_settings_repositories.dart'; import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/timeline/model.dart'; import 'package:cutdex_sdk/timeline/engine.dart'; import 'package:cutdex_sdk/timeline/layout.dart'; import 'package:cutdex_sdk/timeline_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:cutdex/workspace/media_import.dart'; import 'package:cutdex/workspace/media_availability.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:drift/native.dart'; TimelineDto sequence(String id) => TimelineDto( id: SequenceId(id), name: id, format: TimelineFormat.fps24, primaryStorylineId: StorylineId('primary'), storylines: [ StorylineDto(id: StorylineId('primary'), elementIds: [ElementId('clip')]), ], elements: [ ElementDto( id: ElementId('clip'), name: '真实工程片段', structure: ElementStructure.content, duration: RationalTime.seconds(10), sourceRange: TimeRange( start: RationalTime.zero, duration: RationalTime.seconds(10), ), mediaRange: TimeRange( start: RationalTime.zero, duration: RationalTime.seconds(20), ), ), ], ); void main() { TestWidgetsFlutterBinding.ensureInitialized(); late Directory root; late ProjectWorkspace workspace; late EditorTimelineSession session; late String projectId; setUp(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( const MethodChannel('cutdex_native/file_drop'), (_) async => null, ); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( const MethodChannel('cutdex_native/file_drop/timeline'), (_) async => null, ); root = await Directory.systemTemp.createTemp('cutdex-timeline-'); workspace = ProjectWorkspace(creationNames: testCreationNames); await workspace.open('${root.path}/Project.cutdex', name: 'Test'); projectId = workspace.project!.info.id; await workspace.project!.saveTimeline( TimelineDocument( id: 'project', name: 'Test project', sequences: [sequence('one'), sequence('two')], defaultSequenceId: SequenceId('two'), settings: const {'keep': true}, payloads: [ PayloadDocument( id: 'unused', type: 'custom', data: const {'keep': 42}, ), ], ), ); final project = await workspace.loadTimeline(projectId, 'project'); session = await workspace.openTimelineSession(projectId, project); }); tearDown(() async { TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( const MethodChannel('cutdex_native/file_drop'), null, ); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler( const MethodChannel('cutdex_native/file_drop/timeline'), null, ); await workspace.close(); await root.delete(recursive: true); }); for (final direction in [-1.0, 1.0]) { testWidgets('single primary clip stays painted off axis $direction', ( tester, ) async { await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _ViewProjects(session, projectId), ), editorTimelineProvider( projectId, 'project', ).overrideWith((ref) => session), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: EditorTimelinePanel( projectId: projectId, timelineId: 'project', ), ), ), ), ); await tester.pumpAndSettle(); final surface = find.byKey(const Key('editor-timeline-surface')); final origin = tester.getTopLeft(surface); final size = tester.getSize(surface); final viewport = TimelineViewportRect( width: size.width, height: size.height, ); final controller = session.view(session.activeSequenceId!); final base = controller.version; final frame = controller.project(viewport); final clipBounds = controller.presentationBoundsAt(frame, 0); final start = Offset(clipBounds.left + 30, clipBounds.center.dy); final gesture = await tester.startGesture( origin + start, kind: PointerDeviceKind.mouse, ); await gesture.moveTo(origin + start + Offset(0, 100 * direction)); await tester.pump(); expect(tester.takeException(), isNull); expect(controller.isDragging, isTrue); expect(controller.dragRejection, isNull); expect(controller.dragGhost, isNotNull); expect(controller.version, same(base)); final ghostBounds = controller.dragGhostBounds( controller.dragGhost!, viewport, ); final boundary = tester.renderObject( find.descendant(of: surface, matching: find.byType(RepaintBoundary)), ); await tester.runAsync(() async { final image = await boundary.toImage(pixelRatio: 1); try { final bytes = (await image.toByteData( format: ui.ImageByteFormat.rawRgba, ))!; final point = Offset(ghostBounds.left + 30, ghostBounds.bottom - 10); final color = TimelineThemeData.of(tester.element(surface)) .visualClipColor .toARGB32(); expect( bytes.getUint32( (point.dy.toInt() * image.width + point.dx.toInt()) * 4, ), ((color & 0xffffff) << 8) | (color >> 24), ); } finally { image.dispose(); } }); await gesture.cancel(); expect(controller.version, same(base)); expect(controller.canUndo, isFalse); await tester.pumpWidget(const SizedBox()); expect(tester.takeException(), isNull); }); } for (final connected in [false, true]) { test('detach audio is independent and atomic (connected=$connected)', () async { final id = SequenceId('two'); final videoId = ElementId('video-with-audio'); final uri = Uri.file('/original.mov'); await workspace.project!.saveAsset( AssetDocument( id: 'original', name: 'Original', storage: AssetStorage.external, location: uri.toString(), ), ); session.insertAsset( sequenceId: id, assetId: 'original', assetName: 'Original', uri: uri, duration: RationalTime.seconds(4), position: 0, kind: 'video', hasAudio: true, clipId: videoId, sourceStart: RationalTime.seconds(2), mediaDuration: RationalTime.seconds(20), ); final engine = session.layout(id); session.publishLayout( id, const LayoutIntervalEdit().preview( kernel: session.persistence.timeline(id), engine: engine, projection: engine.currentComponents!.semanticProjection, edit: (tx) { final query = session.persistence.timeline(id).current.query(); // The fixture's placeholder clip has no media binding. tx.setEnabled(query.elementById(ElementId('clip'))!, false); tx.retimePlayback( session.persistence .timeline(id) .current .query() .elementById(videoId)!, [ RetimeSegmentDto( projectDuration: RationalTime.seconds(2), sourceStart: RationalTime.zero, sourceDelta: RationalTime.seconds(4), ), ], ); }, ), ); if (connected) { await session.commands.executeEdit( id, PlaceClip( clipId: videoId.value, at: CommandTime( 6 * TimelineClock.ticksPerSecond, TimelineClock.ticksPerSecond, ), side: ClipPlacement.above, ), ); } session.commands.setAudio(sequence: id, clip: videoId, db: -6); final kernel = session.persistence.timeline(id); final before = kernel.current; final q = before.query(); final source = q.elementById(videoId)!; final view = session.view(id); view.setSelection([source]); final selection = view.selectedIdentities.toList(); expect(session.canDetachAudio(id, videoId), isTrue); final audioId = session.detachAudio(id, videoId); expect(view.selectedIdentities, selection); final after = kernel.current; final result = after.query(); final audio = result.elementById(audioId)!; final record = result.element(audio); final link = result.connectionForTarget(audio)!; expect(result.connectionOrderLocation(audio)!.side, ConnectionSide.below); if (connected) expect(link.anchor, isNot(source)); expect(result.absoluteStart(audio), q.absoluteStart(source)); expect(record.duration, q.element(source).duration); expect(record.sourceStart, q.element(source).sourceStart); expect(record.sourceDuration, q.element(source).sourceDuration); expect( kernel .exportElementDto(audio) .retimeSegments .map((s) => (s.projectDuration, s.sourceStart, s.sourceDelta)), kernel .exportElementDto(source) .retimeSegments .map((s) => (s.projectDuration, s.sourceStart, s.sourceDelta)), ); expect(ClipAudioGain.fromRecord(record).db, -6); expect(ClipAudioGain.fromRecord(record).muted, isFalse); expect(ClipAudioGain.fromRecord(result.element(source)).muted, isTrue); expect(session.canDetachAudio(id, videoId), isFalse); final binding = session.mediaBinding(record.payloadRef!)!; expect(binding.media.uri, uri); expect(binding.media.id, 'original'); expect(binding.videoTrackIndex, isNull); expect(binding.audioTrackIndex, 0); expect(session.payloadFor(record.payloadRef!)!.type, 'audio'); CompiledExecution compileAudioState() => const ExecutionCompiler().compile( editorExecutionInput( session, id, kernel.current, EditorExecutionMedia( bindings: { for (final ref in [ q.element(source).payloadRef!, record.payloadRef!, ]) ref: ExecutionMediaBinding( media: session.mediaBinding(ref)!.media, videoTrackSelection: session .mediaBinding(ref)! .videoSelection, audioTrackSelection: session .mediaBinding(ref)! .audioSelection, ), }, ), settings: session.settings, canvas: session.canvas, payloads: session.payloads.toList(), ), ); final detachedPlan = compileAudioState().plan; expect(detachedPlan.audioLayers.length, 2); expect( detachedPlan.audioLayers .expand((layer) => layer.automation) .any((curve) => curve.target == ClipAudioGain.detachedId), isFalse, ); session.setClipSpeed(id, audioId, 1); final speedChanged = kernel.current.query(); expect( speedChanged.element(audio).duration, 4 * TimelineClock.ticksPerSecond, ); expect( speedChanged.element(source).duration, 2 * TimelineClock.ticksPerSecond, ); final speedPlan = compileAudioState().plan; final spedLayer = speedPlan.audioLayers.singleWhere( (layer) => layer.id.contains(audioId.value), ); expect(spedLayer.timelineRange.duration.seconds, 4); expect(spedLayer.sampleStart?.seconds, 2); expect(spedLayer.sourceEnd?.seconds, 6); session.undo(id); expect(kernel.current, same(after)); session.undo(id); expect(kernel.current, same(before)); expect(session.canDetachAudio(id, videoId), isTrue); session.redo(id); expect(kernel.current, same(after)); // Restoring the video's audio does not remove or alter the detached copy. session.commands.setAudio(sequence: id, clip: videoId, muted: false); final restored = kernel.current.query(); expect(compileAudioState().plan.audioLayers.length, 2); expect(restored.element(audio), same(record)); expect(ClipAudioGain.fromRecord(restored.element(source)).muted, isFalse); session.commands.setAudio(sequence: id, clip: audioId, db: -12); expect( ClipAudioGain.fromRecord(kernel.current.query().element(source)).db, -6, ); await session.flush(); final reopened = await workspace.loadTimeline( projectId, session.document.id, ); final saved = await workspace.openTimelineSession(projectId, reopened); final savedQuery = saved.persistence.timeline(id).current.query(); expect(savedQuery.elementById(audioId), isNotNull); expect( saved .mediaBinding( savedQuery.element(savedQuery.elementById(audioId)!).payloadRef!, )! .media .uri, uri, ); if (!identical(saved, session)) await saved.close(); }); } test('incoming preview cancels without history and preserves redo', () async { final id = SequenceId('two'); final kernel = session.persistence.timeline(id); await workspace.project!.saveAsset( AssetDocument( id: 'saved', name: 'saved', storage: AssetStorage.external, location: 'file:///saved.png', ), ); session.insertAsset( sequenceId: id, assetId: 'saved', assetName: 'saved', uri: Uri.file('/saved.png'), duration: RationalTime.seconds(2), position: 0, kind: 'image', hasAudio: false, ); session.undo(id); await session.flush(); final before = kernel.current; final redo = kernel.redoVersion; final count = kernel.historyVersions.length; final clip = session.beginIncomingClip( media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), sequence: id, name: 'incoming', duration: RationalTime.seconds(3), kind: 'video', hasAudio: true, ); expect( clip.incoming.seed.query().positionOf(clip.incoming.source).position, 10 * TimelineClock.ticksPerSecond, ); for (final side in [ConnectionSide.above, null, ConnectionSide.below]) { clip.update( start: 2 * TimelineClock.ticksPerSecond, side: side, top: side == ConnectionSide.above ? -80 : 180, ); final query = clip.layout!.kernelVersion.query(); final handle = query.elementById(clip.clipId)!; expect(query.connectionOrderLocation(handle)?.side, side); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, count); } clip.cancel(); expect(kernel.current, same(before)); expect(kernel.redoVersion, same(redo)); expect(session.dirty, isFalse); expect(session.payloadFor(PayloadRef(clip.payloadId)), isNull); }); for (final side in [null, ConnectionSide.above, ConnectionSide.below]) { test( 'incoming $side commits once and undo removes payload reference', () async { final id = SequenceId('two'); final kernel = session.persistence.timeline(id); final before = kernel.current; final count = kernel.historyVersions.length; await workspace.project!.saveAsset( AssetDocument( id: 'incoming', name: 'incoming', storage: AssetStorage.external, location: 'file:///incoming.mov', ), ); final clip = session.beginIncomingClip( media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), sequence: id, name: 'incoming', duration: RationalTime.seconds(3), kind: 'video', hasAudio: true, ); clip.update( start: 2 * TimelineClock.ticksPerSecond, side: side, top: side == ConnectionSide.above ? -80 : 180, ); final preview = clip.layout!.kernelVersion; clip.commit(assetId: 'incoming', uri: Uri.file('/incoming.mov')); expect(kernel.current, same(preview)); expect(kernel.historyVersions.length, count + 1); final q = kernel.current.query(); final handle = q.elementById(clip.clipId)!; expect(q.connectionOrderLocation(handle)?.side, side); if (side != null) { expect(q.absoluteStart(handle), 2 * TimelineClock.ticksPerSecond); } session.undo(id); expect(kernel.current, same(before)); expect(session.canUndo(id), isFalse); session.redo(id); expect(kernel.current, same(preview)); await session.flush(); final saved = await workspace.project!.loadTimeline('project'); expect(saved.payloads.any((p) => p.id == clip.payloadId), isTrue); }, ); } test('incoming beyond tail creates and cancels its gap together', () { final id = SequenceId('two'); final kernel = session.persistence.timeline(id); final before = kernel.current; final clip = session.beginIncomingClip( media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), sequence: id, name: 'incoming', duration: RationalTime.seconds(3), kind: 'image', hasAudio: false, ); clip.update( start: 20 * TimelineClock.ticksPerSecond, side: ConnectionSide.above, top: -80, ); final q = clip.layout!.kernelVersion.query(); expect( q.absoluteStart(q.elementById(clip.clipId)!), 20 * TimelineClock.ticksPerSecond, ); expect( q.storylineSpan(q.primaryStoryline), 23 * TimelineClock.ticksPerSecond, ); clip.cancel(); expect(kernel.current, same(before)); expect(kernel.canUndo, isFalse); }); test( 'empty incoming stays on Primary at zero and stale previews cannot commit', () async { final timelines = await workspace.createTimeline('Empty incoming'); final document = await workspace.loadTimeline( projectId, timelines.singleWhere((d) => d.name == 'Empty incoming').id, ); session = await workspace.openTimelineSession(projectId, document); final id = session.activeSequenceId!; final kernel = session.persistence.timeline(id); final clip = session.beginIncomingClip( media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), sequence: id, name: 'audio', duration: RationalTime.seconds(3), kind: 'audio', hasAudio: true, ); clip.update( start: 4 * TimelineClock.ticksPerSecond, side: ConnectionSide.below, top: 180, ); final q = clip.layout!.kernelVersion.query(); expect(q.absoluteStart(q.elementById(clip.clipId)!), 0); expect(q.connectionForTarget(q.elementById(clip.clipId)!), isNull); expect(q.storylineLength(q.primaryStoryline), 1); expect( q.storylineSpan(q.primaryStoryline), 3 * TimelineClock.ticksPerSecond, ); expect(kernel.canUndo, isFalse); clip.cancel(); expect( kernel.current.query().storylineLength( kernel.current.query().primaryStoryline, ), 0, ); final pending = session.beginIncomingClip( media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), sequence: id, name: 'pending', duration: RationalTime.seconds(2), kind: 'image', hasAudio: false, ); pending.update(start: 0, top: 60); final other = session.beginIncomingClip( media: MediaReference(id: 'incoming', uri: Uri.file('/incoming.mov')), sequence: id, name: 'other', duration: RationalTime.seconds(2), kind: 'image', hasAudio: false, ); other.update(start: 0, top: 60); await workspace.project!.saveAsset( AssetDocument( id: 'other', name: 'other', storage: AssetStorage.external, location: 'file:///other.png', ), ); other.commit(assetId: 'other', uri: Uri.file('/other.png')); final before = kernel.current; expect( () => pending.commit(assetId: 'pending', uri: Uri.file('/pending.png')), throwsStateError, ); pending.cancel(); expect(kernel.current, same(before)); expect( session.payloads.where((p) => p.assetIds.contains('pending')), isEmpty, ); }, ); test( 'restores active sequence playhead and camera from local state', () async { final database = AppDatabase(NativeDatabase.memory()); addTearDown(database.close); final repository = DriftTimelineViewSettingsRepository(database); final binding = await TimelineViewStateBinding.attach( projectId: projectId, timelineId: 'project', session: session, repository: repository, ); final sequenceId = SequenceId('one'); session.selectSequence(sequenceId); final view = session.view(sequenceId); view.seekTo(720); view.setCamera( TimelineCamera( baseTick: 240, fractionalTick: .5, pixelsPerTick: .25, verticalOffset: 32, ), ); await binding.close(); final document = await workspace.loadTimeline(projectId, 'project'); session = await workspace.openTimelineSession(projectId, document); final restored = await TimelineViewStateBinding.attach( projectId: projectId, timelineId: 'project', session: session, repository: repository, ); addTearDown(restored.close); expect(session.activeSequenceId, sequenceId); final restoredView = session.view(sequenceId); expect(restoredView.playheadTick, 720); expect(restoredView.camera.baseTick, 240); expect(restoredView.camera.fractionalTick, .5); expect(restoredView.camera.pixelsPerTick, .25); expect(restoredView.camera.verticalOffset, 32); expect(restoredView.selectedIdentities, isEmpty); }, ); for (final mediaKind in ['audio', 'video']) { testWidgets( 'right-click caption menu targets $mediaKind and clears on empty space', (tester) async { final sequenceId = session.activeSequenceId!; final uri = Uri.file('${root.path}/speech.wav'); await tester.runAsync( () => workspace.project!.saveAsset( AssetDocument( id: 'speech', name: 'Speech', storage: AssetStorage.external, location: uri.toString(), ), ), ); session.insertAsset( sequenceId: sequenceId, assetId: 'speech', assetName: 'Speech', uri: uri, duration: RationalTime.seconds(5), position: 0, kind: mediaKind, hasAudio: true, clipId: ElementId('speech-clip'), ); await tester.runAsync(session.flush); final controller = session.view(sequenceId); controller.setSelection([ controller.version.kernelVersion.query().elementById( ElementId('clip'), )!, ]); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _ViewProjects(session, projectId), ), editorTimelineProvider( projectId, 'project', ).overrideWith((ref) async => session), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: EditorTimelinePanel( projectId: projectId, timelineId: 'project', ), ), ), ), ); await tester.pumpAndSettle(); final surface = tester.getRect( find.byKey(const Key('editor-timeline-surface')), ); Future rightClick(Offset point) async { final gesture = await tester.startGesture( point, kind: PointerDeviceKind.mouse, buttons: kSecondaryMouseButton, ); await gesture.up(); await tester.pumpAndSettle(); } final frame = controller.project( TimelineViewportRect(width: surface.width, height: surface.height), ); final speech = controller.version.kernelVersion.query().elementById( ElementId('speech-clip'), )!; final index = List.generate(frame.length, (i) => i).firstWhere( (i) => switch (frame.identityAt(i)) { ElementHandle h => h == speech, LayoutBodyId body => body.owner == speech, _ => false, }, ); await rightClick( surface.topLeft + Offset( frame.screenLeftAt(index) + 20, frame.screenTopAt(index) + 20, ), ); expect(find.text('生成字幕'), findsOneWidget); expect( tester .widget( find.byWidgetPredicate( (w) => w is AppMenuItem && w.label == '分离音频', ), ) .onPressed, mediaKind == 'audio' ? isNull : isNotNull, ); await tester.tap(find.text('生成字幕')); await tester.pumpAndSettle(); final dialog = tester.widget( find.byType(TranscriptionDialog), ); expect(dialog.target!.clipId, 'speech-clip'); expect(dialog.target!.sequence, sequenceId); expect(dialog.target!.mediaId, 'speech'); expect(dialog.target!.audioStream, 0); await tester.tap(find.byTooltip('关闭')); await tester.pumpAndSettle(); if (mediaKind == 'video') { await rightClick( surface.topLeft + Offset( frame.screenLeftAt(index) + 20, frame.screenTopAt(index) + 20, ), ); await tester.runAsync(() async { await tester.tap(find.text('分离音频')); await tester.pump(); await session.flush(); }); await tester.pumpAndSettle(); final q = controller.version.kernelVersion.query(); final source = q.elementById(ElementId('speech-clip'))!; expect(ClipAudioGain.fromRecord(q.element(source)).muted, isTrue); expect( controller.selectedIdentities.map(controller.elementForIdentity), [source], ); final detachedId = session.persistence .timeline(sequenceId) .exportDto() .elements .singleWhere( (element) => element.payloadRef != null && session.payloadFor(element.payloadRef!)?.type == 'audio', ) .id; final detached = q.elementById(detachedId)!; expect( q.connectionOrderLocation(detached)!.side, ConnectionSide.below, ); expect( session.payloadFor(q.element(detached).payloadRef!)!.type, 'audio', ); final detachedRecord = q.element(detached); final videoPoint = surface.topLeft + Offset( frame.screenLeftAt(index) + 20, frame.screenTopAt(index) + 20, ); session.setUnavailableAssets({'speech': 'missing'}); await tester.pumpAndSettle(); await rightClick(videoPoint); expect(find.text('恢复音频'), findsOneWidget); expect(find.text('分离音频'), findsNothing); final beforeRestore = controller.version.kernelVersion; await tester.runAsync(() async { await tester.tap(find.text('恢复音频')); await tester.pump(); await session.flush(); }); await tester.pumpAndSettle(); session.setUnavailableAssets({}); final restored = controller.version.kernelVersion.query(); expect( ClipAudioGain.fromRecord(restored.element(source)).muted, isFalse, ); expect(restored.element(detached), same(detachedRecord)); await rightClick(videoPoint); expect(find.text('分离音频'), findsOneWidget); expect(find.text('恢复音频'), findsNothing); await tester.tapAt(surface.topLeft + const Offset(2, 2)); await tester.pumpAndSettle(); await tester.runAsync(() async { session.undo(sequenceId); await session.flush(); }); expect(controller.version.kernelVersion, same(beforeRestore)); await tester.pumpAndSettle(); await tester.runAsync(() async { session.commands.setAudio( sequence: sequenceId, clip: ElementId('speech-clip'), muted: false, ); session.commands.setAudio( sequence: sequenceId, clip: ElementId('speech-clip'), muted: true, ); await session.flush(); }); await tester.pumpAndSettle(); await rightClick(videoPoint); expect(find.text('恢复音频'), findsOneWidget); await tester.tapAt(surface.topLeft + const Offset(2, 2)); await tester.pumpAndSettle(); } // The bottom edge now contains the floating scrollbar hit target. await rightClick(surface.topLeft + Offset(80, surface.height - 30)); expect(controller.selectedIdentities, isEmpty); final item = tester.widget( find.byWidgetPredicate((w) => w is AppMenuItem && w.label == '生成字幕'), ); expect(item.onPressed, isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(session.flush); }, ); } test( 'host layout configuration is shared by SDK commands and the viewport', () { final custom = EditorTimelineSession( document: session.document, persistence: session.persistence, layoutConfiguration: const EditorLayoutConfiguration( primaryTop: 90, primaryHeight: 110, clipHeight: 84, innerGap: 12, bodyGap: 7, ), ); final id = custom.document.sequences.first.id; final view = custom.view(id); final access = custom.timeline(id); expect(view.geometry.primaryTop, 90); expect(view.geometry.primaryHeight, 110); expect(access.primaryTop, view.geometry.primaryTop); expect(access.primaryHeight, view.geometry.primaryHeight); expect(access.engine, same(custom.layout(id))); final policies = access.engine.current!.policy.stacks.values; expect(policies.map((p) => p.primaryBoundary).toSet(), {90, 200}); expect(policies.every((p) => p.innerGap == 12 && p.bodyGap == 7), isTrue); custom.dispose(); }, ); testWidgets( 'pending timeline session keeps the editor area free of loading chrome', (tester) async { final pending = Completer(); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _ViewProjects(session, projectId), ), editorTimelineProvider( projectId, 'pending', ).overrideWith((ref) => pending.future), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: EditorTimelinePanel( projectId: projectId, timelineId: 'pending', ), ), ), ), ); await tester.pump(); expect(find.byType(CircularProgressIndicator), findsNothing); expect(find.byKey(const Key('timeline-pending')), findsOneWidget); pending.complete(session); await tester.pumpAndSettle(); }, ); testWidgets('prepared timeline stays visible while provider binds', ( tester, ) async { final pending = Completer(); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _CachedViewProjects(session, projectId), ), editorTimelineProvider( projectId, 'project', ).overrideWith((ref) => pending.future), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: EditorTimelinePanel( projectId: projectId, timelineId: 'project', ), ), ), ), ); await tester.pump(); expect(find.byKey(const Key('timeline-pending')), findsNothing); expect(find.byKey(const Key('editor-timeline-surface')), findsOneWidget); expect(tester.takeException(), isNull); pending.complete(session); await tester.pumpWidget(const SizedBox.shrink()); }); testWidgets('timeline switch keeps the toolbar element mounted', ( tester, ) async { final created = await tester.runAsync( () => workspace.createPreparedTimeline('Second'), ); final second = created!.session; Widget panel(String timelineId) => ProviderScope( overrides: [ // ignore: riverpod_lint/scoped_providers_should_specify_dependencies projectsProvider.overrideWith(() => _ViewProjects(session, projectId)), // ignore: riverpod_lint/scoped_providers_should_specify_dependencies editorTimelineProvider( projectId, 'project', ).overrideWith((ref) => session), // ignore: riverpod_lint/scoped_providers_should_specify_dependencies editorTimelineProvider( projectId, second.document.id, ).overrideWith((ref) => second), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: EditorTimelinePanel( key: const Key('timeline-panel'), projectId: projectId, timelineId: timelineId, ), ), ), ); await tester.pumpWidget(panel('project')); await tester.pumpAndSettle(); final toolbar = tester.element(find.byKey(const Key('timeline-toolbar'))); // Entering the clip enables cut/trim; subsequent motion keeps that state. session.view(session.activeSequenceId!).seekTo(100); await tester.pump(); final toolbarWidget = toolbar.widget; session.view(session.activeSequenceId!).seekTo(200); await tester.pump(); expect(toolbar.widget, same(toolbarWidget)); await tester.pumpWidget(panel(second.document.id)); await tester.pump(); expect( tester.element(find.byKey(const Key('timeline-toolbar'))), same(toolbar), ); expect(find.byKey(const Key('timeline-pending')), findsNothing); await tester.pumpWidget(const SizedBox.shrink()); }); testWidgets( 'closing a project keeps mounted timeline views alive until detached', (tester) async { final container = ProviderContainer( overrides: [ projectsProvider.overrideWith( () => _ViewProjects(session, projectId), ), ], ); await container.read(projectsProvider.future); await tester.pumpWidget( UncontrolledProviderScope( container: container, child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: EditorTimelinePanel( projectId: projectId, timelineId: 'project', ), ), ), ), ); await tester.pumpAndSettle(); final controller = session.view(session.activeSequenceId!); await tester.runAsync(session.close); expect(session.acceptsEdits, isFalse); // The old tree may rebuild while the next project loads from disk. tester.element(find.byType(TimelineView)).markNeedsBuild(); await tester.pump(); expect(tester.takeException(), isNull); void listener() {} controller.addListener(listener); controller.removeListener(listener); await tester.pumpWidget(const SizedBox()); await tester.pumpAndSettle(); container.dispose(); expect(() => controller.addListener(listener), throwsFlutterError); }, ); for (final (labelText, fieldKey) in const [ ('旋转', 'picture-rotation'), ('X', 'picture-x'), ('Y', 'picture-y'), ('W', 'picture-scale-x'), ('H', 'picture-scale-y'), ]) { for (final action in [ 'commit', 'fast', 'unlocked', if (labelText == 'W' || labelText == 'H') ...['lower', 'upper'], 'fallback', if (labelText == '旋转') ...[ 'wrap_positive', 'wrap_negative', 'wrap_boundary', 'wrap_multiple', 'wrap_reverse', ], 'escape', 'cancel', 'tap', 'return', 'stale', 'dispose', 'sequence', ]) { testWidgets('$labelText scrub $action preserves one edit boundary', ( tester, ) async { final id = SequenceId('two'); final view = session.view(id); final base = view.version.kernelVersion; var expectedVersion = base; final preview = _LivePropertyPreview(session); addTearDown(preview.close); await tester.pumpWidget( ProviderScope( overrides: [ editorPreviewProvider(projectId, 'project').overrideWith(( ref, ) async { if (action == 'fallback') throw StateError('No preview'); return preview; }), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 225, child: PictureProperties( projectId: projectId, timelineId: 'project', session: session, sequence: id, clip: base.query().element( base.query().elementById(ElementId('clip'))!, ), ), ), ), ), ), ); await tester.pumpAndSettle(); if (action == 'unlocked') { await tester.tap(find.byKey(const Key('picture-lock'))); await tester.pumpAndSettle(); } final label = find.text(labelText); final gesture = await tester.startGesture( tester.getCenter(label), kind: PointerDeviceKind.mouse, ); final distance = switch (action) { 'lower' => -20000.0, 'upper' => 20000.0, 'wrap_negative' => -190.0, 'wrap_boundary' => 180.0, 'wrap_multiple' => 750.0, 'wrap_positive' || 'wrap_reverse' => 190.0, 'fast' => 20.0, _ => 50.0, }; if (action != 'tap') { await gesture.moveBy(const Offset(20, 0)); await tester.pump(); if (action != 'fast') { await gesture.moveBy(Offset(distance - 20, 0)); await tester.pump(); } final field = tester.widget( find.descendant( of: find.byKey(ValueKey(fieldKey)), matching: find.byType(TextField), ), ); final expected = switch (action) { 'lower' => 1.0, 'upper' => 10000.0, 'wrap_negative' => 170.0, 'wrap_boundary' => -180.0, 'wrap_multiple' => 30.0, 'wrap_positive' || 'wrap_reverse' => -170.0, _ => (labelText == 'W' || labelText == 'H') ? 100 + distance : distance, }; expect(double.parse(field.controller!.text), closeTo(expected, .01)); if (action != 'fallback') { final timeline = preview.transforms.valueFor(ElementId('clip'))!; if (labelText == 'W' || labelText == 'H') { expect( labelText == 'W' ? timeline.scale : timeline.scaleY, closeTo(expected / 100, 1e-9), ); expect( labelText == 'W' ? timeline.scaleY : timeline.scale, closeTo(action == 'unlocked' ? 1 : expected / 100, 1e-9), ); } else if (labelText == 'X') { expect( timeline.x, closeTo(distance / session.canvas.width, 1e-9), ); expect(timeline.y, 0); } else if (labelText == 'Y') { expect( timeline.y, closeTo(distance / session.canvas.height, 1e-9), ); expect(timeline.x, 0); } else if (labelText == '旋转') { expect(timeline.rotation, closeTo(expected, 1e-9)); } } expect(view.version.kernelVersion, same(base)); expect(session.dirty, isFalse); if (action == 'wrap_reverse') { await gesture.moveBy(const Offset(-40, 0)); await tester.pump(); expect(double.parse(field.controller!.text), 150); expect( preview.transforms.valueFor(ElementId('clip'))!.rotation, 150, ); } if (action == 'escape') { await tester.sendKeyEvent(LogicalKeyboardKey.escape); } else if (action == 'cancel') { await gesture.cancel(); } else if (action == 'return') { await gesture.moveBy(Offset(-distance, 0)); } else if (action == 'dispose') { await tester.pumpWidget(const SizedBox()); } else if (action == 'sequence') { session.selectSequence(SequenceId('one')); } else if (action == 'stale') { final edit = session.previewParameters( id, ElementId('clip'), const ClipTransform(x: .2).parameters, ); session.commitParameters( id, edit, parameterTargets: ClipTransform.targets, ); expectedVersion = view.version.kernelVersion; } } if (action != 'cancel') await gesture.up(); // Flush real file IO before settle advances the autosave's fake clock. await tester.runAsync(session.flush); await tester.pumpAndSettle(); if (action.startsWith('wrap_') || [ 'commit', 'fast', 'fallback', 'unlocked', 'lower', 'upper', ].contains(action)) { expect(view.version.kernelVersion, isNot(same(base))); view.undo(); expect(view.version.kernelVersion, same(base)); } else { expect(view.version.kernelVersion, same(expectedVersion)); } expect(preview.transforms.hasPending, isFalse); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); await tester.runAsync(session.flush); }); } } testWidgets( 'picture values follow uncommitted gestures and restore on cancel', (tester) async { final id = SequenceId('two'); final clipId = ElementId('clip'); final view = session.view(id); final base = view.version.kernelVersion; final preview = _LivePropertyPreview(session); addTearDown(preview.close); var previewNotifications = 0; preview.busy = false; preview.addListener(() => previewNotifications++); await tester.pumpWidget( ProviderScope( overrides: [ editorPreviewProvider( projectId, 'project', ).overrideWith((ref) async => preview), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: AppTheme.propertiesPanelTheme(EditorTheme.penLight), home: Scaffold( body: SizedBox( width: 225, child: PictureProperties( projectId: projectId, timelineId: 'project', session: session, sequence: id, clip: base.query().element(base.query().elementById(clipId)!), ), ), ), ), ), ); await tester.pumpAndSettle(); String text(String key) => tester .widget( find.descendant( of: find.byKey(ValueKey(key)), matching: find.byType(TextField), ), ) .controller! .text; PreviewVisual visual(ClipTransform value) => PreviewVisual( layerId: 'video', elementId: clipId, lane: 0, transform: value, geometry: const PreviewGeometry( center: Offset(100, 100), size: Size(200, 200), ), ); expect(find.byType(Slider), findsNothing); expect(find.byKey(const ValueKey('picture-scale-y')), findsOneWidget); expect(text('picture-scale-x'), '100'); expect( tester.getSize(find.byKey(const Key('picture-lock'))), const Size.square(AppControlSize.propertyControl), ); expect( tester .getSize( find.descendant( of: find.byKey(const ValueKey('picture-scale-y')), matching: find.byType(TextField), ), ) .height, AppControlSize.propertyControl, ); expect( tester.getSize(find.byKey(const ValueKey('picture-align-left'))).height, AppControlSize.propertyControl, ); expect( tester.getSize(find.byKey(const Key('picture-lock'))), tester.getSize(find.byKey(const ValueKey('picture-key-scale'))), ); expect( tester.getRect(find.byKey(const ValueKey('picture-key-scale'))).left - tester.getRect(find.byKey(const ValueKey('picture-scale-y'))).right, AppSpacing.small, ); final canvasDrag = preview.transforms.begin( visual(const ClipTransform()), )!; canvasDrag.update(const ClipTransform(scale: 1.5)); await tester.pump(); final lockControl = tester.widget( find.byKey(const Key('picture-lock')), ); final alignControl = tester.widget( find.byKey(const ValueKey('picture-align-left')), ); expect(lockControl.onPressed, isNotNull); expect(alignControl.onPressed, isNotNull); lockControl.onPressed!(); alignControl.onPressed!(); await tester.pump(); expect(preview.aspectRatioLocked, isTrue); expect(find.byType(Slider), findsNothing); expect(text('picture-scale-x'), '150'); expect(preview.transforms.hasPending, isTrue); expect(view.version.kernelVersion, same(base)); canvasDrag.cancel(); await tester.pump(); preview.busy = true; await tester.pump(); final busyAlignControl = tester.widget( find.byKey(const ValueKey('picture-align-left')), ); expect(busyAlignControl.onPressed, isNotNull); busyAlignControl.onPressed!(); await tester.pump(); expect(view.version.kernelVersion, same(base)); preview.busy = false; await tester.tap(find.byKey(const Key('picture-lock'))); await tester.pumpAndSettle(); expect(preview.aspectRatioLocked, isFalse); expect(previewNotifications, 1); previewNotifications = 0; final edit = preview.transforms.begin(visual(const ClipTransform()))!; for (final (pixels, expected) in [ (-0.0, '0'), (-1e-12, '0'), (-0.004, '0'), (0.004, '0'), (-0.006, '-0.01'), (-10.5, '-10.5'), ]) { edit.update( ClipTransform( x: pixels / session.canvas.width, y: pixels / session.canvas.height, rotation: pixels, ), ); await tester.pump(); expect(text('picture-x'), expected); expect(text('picture-y'), expected); expect(text('picture-rotation'), expected); expect(edit.value.x, pixels / session.canvas.width); expect(view.version.kernelVersion, same(base)); } for (var i = 1; i <= 3; i++) { edit.update( ClipTransform( x: i * .1, y: i * -.1, scale: i.toDouble(), scaleY: i * .5, rotation: i * 10, ), ); await tester.pump(); for (final field in tester.widgetList( find.byType(TextField), )) { expect(field.enabled, isTrue); expect(field.readOnly, isTrue); expect(field.canRequestFocus, isFalse); } expect( double.parse(text('picture-x')), closeTo(i * .1 * session.canvas.width, .01), ); expect( double.parse(text('picture-y')), closeTo(i * -.1 * session.canvas.height, .01), ); expect(double.parse(text('picture-scale-x')), i * 100); expect(double.parse(text('picture-scale-y')), i * 50); expect(double.parse(text('picture-rotation')), i * 10); expect(view.version.kernelVersion, same(base)); expect(session.dirty, isFalse); expect(previewNotifications, 0); } await edit.end(); await tester.pump(); for (final field in tester.widgetList( find.byType(TextField), )) { expect(field.enabled, isTrue); expect(field.readOnly, isFalse); expect(field.canRequestFocus, isTrue); } await tester.runAsync(session.flush); expect(text('picture-rotation'), '30'); final committed = view.version.kernelVersion; final next = preview.transforms.begin(visual(edit.value))!; next.update(edit.value.copyWith(rotation: 80)); await tester.pump(); expect(text('picture-rotation'), '80'); next.cancel(); await tester.pump(); expect(text('picture-rotation'), '30'); expect(view.version.kernelVersion, same(committed)); expect(session.dirty, isFalse); view.undo(); expect(view.version.kernelVersion, same(base)); await tester.pumpWidget(const SizedBox()); await tester.runAsync(session.flush); }, ); testWidgets( 'property panel stays at both edges during repeated trackpad scrolling', (tester) async { final id = SequenceId('two'); final asset = AssetDocument( id: 'video', name: 'Video', storage: AssetStorage.external, location: 'file:///video.mov', ); await tester.runAsync(() => workspace.project!.saveAsset(asset)); session.insertAsset( sequenceId: id, assetId: asset.id, assetName: asset.name, uri: Uri.file('/video.mov'), duration: RationalTime.seconds(3), position: 0, kind: 'video', hasAudio: false, ); await tester.runAsync(session.flush); final view = session.view(id); final query = view.version.kernelVersion.query(); final clipId = session.persistence .timeline(id) .exportDto() .elements .singleWhere((element) => element.name == asset.name) .id; final clip = query.elementById(clipId)!; session.selectSequence(id); view.setSelection([clip]); view.seekTo(query.absoluteStart(clip)); await tester.pumpWidget( ProviderScope( overrides: [ editorTimelineProvider( projectId, 'project', ).overrideWith((ref) async => session), editorPreviewProvider(projectId, 'project').overrideWith( (ref) async => throw StateError('No native preview in scroll test'), ), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight.copyWith( platform: TargetPlatform.macOS, ), home: Scaffold( body: SizedBox( width: 225, height: 240, child: EditorPropertiesPanel( projectId: projectId, timelineId: 'project', ), ), ), ), ), ); await tester.pumpAndSettle(); final scroller = find .byWidgetPredicate( (widget) => widget is SingleChildScrollView && widget.scrollDirection == Axis.vertical, ) .first; final scrollable = find .descendant(of: scroller, matching: find.byType(Scrollable)) .first; final position = tester.state(scrollable).position; expect(position.maxScrollExtent, greaterThan(0)); final extent = position.maxScrollExtent; for (final bottom in [false, true]) { final edge = bottom ? extent : position.minScrollExtent; position.jumpTo(edge); await tester.pumpAndSettle(); for (var repeat = 0; repeat < 3; repeat++) { final gesture = await tester.createGesture( kind: PointerDeviceKind.trackpad, ); await gesture.panZoomStart( tester.getTopLeft(scroller) + const Offset(10, 20), ); for (var i = 1; i <= 8; i++) { await gesture.panZoomUpdate( tester.getTopLeft(scroller) + const Offset(10, 20), pan: Offset(0, (bottom ? -1 : 1) * i * 12.0), timeStamp: Duration(milliseconds: i * 16), ); await tester.pump(const Duration(milliseconds: 16)); expect(position.maxScrollExtent, extent); expect( position.pixels, closeTo(edge, .01), reason: 'bottom=$bottom repeat=$repeat step=$i', ); } await gesture.panZoomEnd( timeStamp: const Duration(milliseconds: 160), ); await tester.pumpAndSettle(); expect(position.pixels, closeTo(edge, .01)); await tester.sendEventToBinding( PointerScrollEvent( position: tester.getTopLeft(scroller) + const Offset(10, 20), scrollDelta: Offset(0, bottom ? 60 : -60), ), ); await tester.pumpAndSettle(); expect(position.pixels, closeTo(edge, .01)); } } position.jumpTo(extent / 2); await tester.pumpAndSettle(); await tester.sendEventToBinding( PointerScrollEvent( position: tester.getTopLeft(scroller) + const Offset(10, 20), scrollDelta: const Offset(0, 10), ), ); await tester.pumpAndSettle(); expect(position.pixels, closeTo(extent / 2 + 10, .01)); await tester.pumpWidget(const SizedBox()); }, ); testWidgets( 'property refresh preserves focused selection and scroll offset', (tester) async { final id = SequenceId('two'); final view = session.view(id); final scroll = ScrollController(); addTearDown(scroll.dispose); await tester.pumpWidget( ProviderScope( overrides: [ editorPreviewProvider(projectId, 'project').overrideWith( (ref) async => throw StateError('No native preview in input test'), ), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 225, height: 220, child: SingleChildScrollView( controller: scroll, child: ListenableBuilder( listenable: view, builder: (_, _) { final query = view.version.kernelVersion.query(); return PictureProperties( projectId: projectId, timelineId: 'project', session: session, sequence: id, clip: query.element( query.elementById(ElementId('clip'))!, ), ); }, ), ), ), ), ), ), ); await tester.pumpAndSettle(); final field = find.descendant( of: find.byKey(const ValueKey('picture-scale-x')), matching: find.byType(TextField), ); await tester.ensureVisible(field); await tester.pumpAndSettle(); await tester.tap(field); await tester.pumpAndSettle(); final controller = tester.widget(field).controller!; const selection = TextSelection(baseOffset: 0, extentOffset: 2); controller.selection = selection; await tester.pumpAndSettle(); scroll.jumpTo(120); await tester.pumpAndSettle(); final offset = scroll.offset; for (var i = 1; i <= 5; i++) { view.seekTo(i * TimelineClock.ticksPerSecond); await tester.pumpAndSettle(); expect(scroll.offset, closeTo(offset, .01)); expect(controller.selection, selection); } expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); }, ); testWidgets('picture inputs commit axes, preserve ratio, validate and undo', ( tester, ) async { final id = SequenceId('two'); final view = session.view(id); final clipId = ElementId('clip'); final base = view.version.kernelVersion; ClipTransform current() { final query = view.version.kernelVersion.query(); return ClipTransform.fromRecord( query.element(query.elementById(clipId)!), ); } await tester.pumpWidget( ProviderScope( overrides: [ editorPreviewProvider(projectId, 'project').overrideWith( (ref) async => throw StateError('No native preview in input test'), ), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 225, child: ListenableBuilder( listenable: view, builder: (_, _) { final query = view.version.kernelVersion.query(); return PictureProperties( projectId: projectId, timelineId: 'project', session: session, sequence: id, clip: query.element(query.elementById(clipId)!), ); }, ), ), ), ), ), ); await tester.pumpAndSettle(); Future input(String field, String text) async { final finder = find.descendant( of: find.byKey(ValueKey(field)), matching: find.byType(TextField), ); await tester.enterText(finder, text); await tester.testTextInput.receiveAction(TextInputAction.done); await tester.pump(); await tester.runAsync(session.flush); await tester.pumpAndSettle(); } await input('picture-scale-x', '150'); expect(current().scale, 1.5); expect(current().scaleY, 1.5); view.undo(); expect(view.version.kernelVersion, same(base)); view.redo(); await tester.runAsync(session.flush); await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key('picture-lock'))); await tester.pumpAndSettle(); await input('picture-scale-y', '50'); expect(current().scale, 1.5); expect(current().scaleY, .5); await tester.tap(find.byKey(const Key('picture-lock'))); await tester.pumpAndSettle(); await input('picture-scale-x', '300'); expect(current().scale, 3); expect(current().scaleY, 1); await input('picture-x', '192'); await input('picture-y', '-108'); expect(current().x, closeTo(192 / session.canvas.width, 1e-9)); expect(current().y, closeTo(-108 / session.canvas.height, 1e-9)); await input('picture-rotation', '37'); expect(current().rotation, 37); final valid = view.version.kernelVersion; await input('picture-scale-x', '0'); expect(view.version.kernelVersion, same(valid)); await input('picture-rotation', 'NaN'); expect(view.version.kernelVersion, same(valid)); await tester.sendKeyEvent(LogicalKeyboardKey.escape); await tester.pumpAndSettle(); expect(find.text('无效数值'), findsNothing); await tester.runAsync(session.flush); final saved = await tester.runAsync( () => workspace.project!.loadTimeline('project'), ); final clip = saved!.sequences .singleWhere((s) => s.id == id) .elements .single; expect( clip.parameters .singleWhere((p) => p.definition.id == 'canvas.scale.y') .definition .defaultValue, 1, ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); }); test('canvas settings save with edits and survive subsequent full saves and reopen', () async { final view = session.view(SequenceId('one')); final original = view.version.kernelVersion; session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); expect(identical(original, view.version.kernelVersion), isTrue); final saving = session.flush(); session.commands.setCanvas(ProjectCanvasPresets.values['9:16']!); await saving; expect(session.dirty, isFalse); var saved = await workspace.project!.loadTimeline('project'); expect(saved.settings['renderSize'], {'width': 1080.0, 'height': 1920.0}); expect(saved.settings['keep'], isTrue); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.seekTo(5 * TimelineClock.ticksPerSecond); view.cutSelectionAtPlayhead(); await session.flush(); saved = await workspace.project!.loadTimeline('project'); expect(saved.settings['renderSize'], {'width': 1080.0, 'height': 1920.0}); expect(saved.sequences.first.elements, hasLength(2)); await workspace.close(); workspace = ProjectWorkspace(creationNames: testCreationNames); await workspace.open('${root.path}/Project.cutdex'); final reopened = await workspace.openTimelineSession(projectId, saved); expect(reopened.canvas, ProjectCanvasPresets.values['9:16']); }); test('cut without selection keeps the resulting clips unselected', () async { final view = session.view(SequenceId('one')); view.seekTo(5 * TimelineClock.ticksPerSecond); expect(view.selectedIdentities, isEmpty); expect(view.canCutSelection, isTrue); expect(view.cutSelectionAtPlayhead(), isTrue); expect(view.selectedIdentities, isEmpty); await session.flush(); final saved = await workspace.project!.loadTimeline('project'); expect(saved.sequences.first.elements, hasLength(2)); }); test( 'cut, undo, redo and delete save the authoritative kernel across reopen', () async { final view = session.view(SequenceId('one')); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.seekTo(5 * TimelineClock.ticksPerSecond); view.cutSelectionAtPlayhead(); expect(view.selectedIdentities, hasLength(2)); expect(session.dirty, isTrue); await session.flush(); var saved = await workspace.project!.loadTimeline('project'); expect(saved.sequences.first.elements, hasLength(2)); view.undo(); await session.flush(); saved = await workspace.project!.loadTimeline('project'); expect(saved.sequences.first.elements, hasLength(1)); view.redo(); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.deleteSelection(); // Reopening the project verifies the persisted state, not the cached session. await workspace.close(); workspace = ProjectWorkspace(creationNames: testCreationNames); await workspace.open('${root.path}/Project.cutdex'); saved = await workspace.loadTimeline(projectId, 'project'); expect(saved.sequences.first.elements, hasLength(1)); expect( saved.sequences.first.elements.single.duration, RationalTime.seconds(5), ); expect( saved.sequences.last.elements.single.duration, RationalTime.seconds(10), ); expect(saved.settings['keep'], isTrue); expect(saved.payloads.single.data['keep'], 42); final reopened = await workspace.openTimelineSession(projectId, saved); expect(reopened.view(SequenceId('one')).canUndo, isFalse); }, ); test('repeated cuts and full saves keep the database usable', () async { final view = session.view(SequenceId('one')); for (var iteration = 0; iteration < 20; iteration++) { view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.seekTo(5 * TimelineClock.ticksPerSecond); view.cutSelectionAtPlayhead(); await session.flush(); expect( (await workspace.project!.loadTimeline('project')) .sequences .first .elements, hasLength(2), ); view.undo(); await session.flush(); expect( (await workspace.project!.loadTimeline('project')) .sequences .first .elements, hasLength(1), ); } }); test('concurrent session closes share disposal and preserve a cut', () async { final view = session.view(SequenceId('one')); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.seekTo(5 * TimelineClock.ticksPerSecond); view.cutSelectionAtPlayhead(); final closing = session.close(); expect(session.close(), same(closing)); await closing; await session.close(); expect( (await workspace.project!.loadTimeline('project')) .sequences .first .elements, hasLength(2), ); }); test( 'disposing during a cut save does not notify disposed listeners', () async { final view = session.view(SequenceId('one')); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.seekTo(5 * TimelineClock.ticksPerSecond); view.cutSelectionAtPlayhead(); final saving = session.flush(); expect(session.saving, isTrue); session.dispose(); await saving; expect( (await workspace.project!.loadTimeline('project')) .sequences .first .elements, hasLength(2), ); }, ); test('camera and selection do not save; committed edits autosave', () async { final view = session.view(SequenceId('two')); final initial = (await workspace.project!.loadTimeline('project')).revision; view.seekTo(3 * TimelineClock.ticksPerSecond); view.panBy(horizontalPixels: 20); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); await session.flush(); expect( (await workspace.project!.loadTimeline('project')).revision, initial, ); view.deleteSelection(); await Future.delayed(const Duration(milliseconds: 500)); await session.flush(); expect( (await workspace.project!.loadTimeline('project')) .sequences .last .elements, isEmpty, ); expect(session.dirty, isFalse); }); test('save conflict retains edits and prevents a project switch', () async { final view = session.view(SequenceId('one')); final current = await workspace.project!.loadTimeline('project'); await workspace.project!.saveTimeline(current); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.deleteSelection(); await expectLater(session.flush(), throwsA(isA())); expect(session.dirty, isTrue); expect(session.error, isNotNull); await expectLater( workspace.open('${root.path}/Other.cutdex', name: 'Other'), throwsA(isA()), ); expect(workspace.project!.info.id, projectId); expect(view.canUndo, isTrue); // Keep the persisted external revision; dispose this intentionally conflicted fixture. await expectLater(workspace.close(), throwsA(isA())); // A failed save must leave the workspace available to recover the edits. expect(await workspace.listAssets(projectId), isEmpty); await expectLater(workspace.close(), throwsA(isA())); session.dispose(); await workspace.project!.close(); workspace = ProjectWorkspace(creationNames: testCreationNames); }); test('imported video inserts at time, keeps source reference and survives undo/redo and reopen', () async { final file = await File('${root.path}/source.mp4').writeAsBytes([1, 2, 3]); final sourceUri = File(await file.resolveSymbolicLinks()).uri; final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler(const MethodChannel('cutdex_runtime'), ( call, ) async { expect(call.method, 'probe'); expect((call.arguments as Map)['media']['uri'], sourceUri.toString()); return { 'duration': {'numerator': '3', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 1, 'audioTrackIds': [1], 'audioTracks': [ { 'start': {'numerator': '0', 'denominator': 1}, 'duration': {'numerator': '2', 'denominator': 1}, }, ], 'isProtected': false, }; }); addTearDown( () => messenger.setMockMethodCallHandler( const MethodChannel('cutdex_runtime'), null, ), ); final imported = await workspace.importExternalMedia(projectId, [ ExternalMediaFile(path: file.path), ]); final asset = imported.assets.single; final view = session.view(SequenceId('one')); await session.commands.insertMedia( sequence: SequenceId('one'), assetId: asset.id, position: 5 * TimelineClock.ticksPerSecond, ); expect(view.canUndo, isTrue); expect(session.dirty, isTrue); expect(session.assetUris[asset.id], sourceUri); await session.flush(); var saved = await workspace.project!.loadTimeline('project'); expect(saved.sequences.first.elements.map((e) => e.duration.seconds), [ 5, 3, 5, ]); final payload = saved.payloads.singleWhere( (p) => p.assetIds.contains(asset.id), ); expect(payload.type, 'video'); expect(payload.data['audioTrackIndex'], 0); expect(saved.sequences.first.elements[1].payloadRef?.value, payload.id); view.undo(); await session.flush(); expect( (await workspace.project!.loadTimeline('project')) .sequences .first .elements, hasLength(1), ); view.redo(); await session.flush(); await workspace.close(); workspace = ProjectWorkspace(creationNames: testCreationNames); await workspace.open('${root.path}/Project.cutdex'); saved = await workspace.loadTimeline(projectId, 'project'); final reopened = await workspace.openTimelineSession(projectId, saved); expect(reopened.assetUris[asset.id], sourceUri); expect(saved.sequences.first.elements, hasLength(3)); expect(await file.readAsBytes(), [1, 2, 3]); expect( (await workspace.project!.listAssets()).single.storage, AssetStorage.external, ); }); test( 'shared insertion rejects a timeline change while media I/O is preparing', () async { final file = await File('${root.path}/slow.mp4').writeAsBytes([1]); final imported = await workspace.importExternalMedia(projectId, [ ExternalMediaFile(path: file.path), ]); final entered = Completer(); final release = Completer(); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler( const MethodChannel('cutdex_runtime'), (call) async { entered.complete(); await release.future; return { 'duration': {'numerator': '3', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 0, 'audioTrackIds': [], 'audioTracks': [], 'isProtected': false, }; }, ); addTearDown( () => messenger.setMockMethodCallHandler( const MethodChannel('cutdex_runtime'), null, ), ); final insertion = session.commands.insertMedia( sequence: SequenceId('one'), assetId: imported.assets.single.id, position: 0, ); final rejected = expectLater( insertion, throwsA( isA().having((e) => e.code, 'code', 'staleVersion'), ), ); await entered.future; session.commands.setCanvas(ProjectCanvasPresets.values['4:3']!); final before = session.view(SequenceId('one')).version; release.complete(); await rejected; expect(session.view(SequenceId('one')).version, same(before)); expect(session.assetUris.containsKey(imported.assets.single.id), isFalse); }, ); test('image inserts beyond tail with gap; rejected insert does not create history or metadata', () async { final file = await File('${root.path}/image.png').writeAsBytes([1]); final imported = await workspace.importExternalMedia(projectId, [ ExternalMediaFile(path: file.path), ]); final view = session.view(SequenceId('one')); await expectLater( session.commands.insertMedia( sequence: SequenceId('one'), assetId: imported.assets.single.id, position: -1, ), throwsA(anything), ); expect(view.canUndo, isFalse); expect(session.payloads, hasLength(1)); await session.commands.insertMedia( sequence: SequenceId('one'), assetId: imported.assets.single.id, position: 12 * TimelineClock.ticksPerSecond, ); await session.flush(); final saved = await workspace.project!.loadTimeline('project'); expect(saved.sequences.first.elements.map((e) => e.duration.seconds), [ 10, 2, 5, ]); expect(saved.sequences.first.elements[1].structure, ElementStructure.gap); expect(saved.payloads.last.type, 'image'); }); test( 'probe failure leaves active and retained project kernels untouched', () async { final file = await File('${root.path}/broken.mp4').writeAsBytes([1]); final imported = await workspace.importExternalMedia(projectId, [ ExternalMediaFile(path: file.path), ]); final view = session.view(SequenceId('one')); final before = view.version; await expectLater( session.commands.insertMedia( sequence: SequenceId('one'), assetId: imported.assets.single.id, position: 0, ), throwsStateError, ); expect(view.version, same(before)); expect(session.dirty, isFalse); await workspace.open('${root.path}/Other.cutdex', name: 'Other'); // Retained projects intentionally keep their sessions usable. expect(session.acceptsEdits, isTrue); await expectLater( session.commands.insertMedia( sequence: SequenceId('one'), assetId: imported.assets.single.id, position: 0, ), throwsStateError, ); expect(view.version, same(before)); expect(session.dirty, isFalse); }, ); test( 'audio inserts into an empty primary and persists its audio binding', () async { final projects = await workspace.createTimeline('Empty'); final project = projects.singleWhere((p) => p.name == 'Empty'); final document = await workspace.loadTimeline(projectId, project.id); session = await workspace.openTimelineSession(projectId, document); final file = await File('${root.path}/audio.wav').writeAsBytes([1]); final imported = await workspace.importExternalMedia(projectId, [ ExternalMediaFile(path: file.path), ]); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler( const MethodChannel('cutdex_runtime'), (_) async => { 'duration': {'numerator': '7', 'denominator': 2}, 'videoTrackCount': 0, 'videoTrackIds': [], 'audioTrackCount': 1, 'audioTrackIds': [1], 'audioTracks': [ { 'start': {'numerator': '0', 'denominator': 1}, 'duration': {'numerator': '2', 'denominator': 1}, }, ], 'isProtected': false, }, ); addTearDown( () => messenger.setMockMethodCallHandler( const MethodChannel('cutdex_runtime'), null, ), ); final id = session.activeSequenceId!; await session.commands.insertMedia( sequence: id, assetId: imported.assets.single.id, position: 0, ); final view = session.view(id); final query = view.version.kernelVersion.query(); final element = query.element( query.storylineElements(query.primaryStoryline).single, ); expect(session.classify(element).name, 'audioOnly'); await session.flush(); final saved = await workspace.project!.loadTimeline(project.id); expect( saved.sequences.single.elements.single.duration, RationalTime(7, 2), ); expect(saved.payloads.single.type, 'audio'); expect(saved.payloads.single.data, {'audioTrackIndex': 0}); view.undo(); await session.flush(); expect( (await workspace.project!.loadTimeline(project.id)) .sequences .single .elements, isEmpty, ); }, ); testWidgets( 'Finder drag remains active when the timeline target is replaced', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.macOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; final nativeCalls = []; messenger.setMockMethodCallHandler(dropChannel, (call) async { nativeCalls.add(call); return null; }); Widget editor(String id) => ProviderScope( overrides: [ // ignore: riverpod_lint/scoped_providers_should_specify_dependencies projectsProvider.overrideWith( () => _DropProjects(session, projectId), ), ], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( key: ValueKey(id), projectId: projectId, session: session, sequenceId: SequenceId('two'), child: const SizedBox.expand(), ), ), ), ); await tester.pumpWidget(editor('old')); await tester.pumpAndSettle(); await tester.pumpWidget(editor('new')); await tester.pumpAndSettle(); final target = tester.state( find.byType(TimelineExternalDropTarget), ); // A pending probe is enough to observe which widget receives the event. const runtimeChannel = MethodChannel('cutdex_runtime'); final probe = Completer(); messenger.setMockMethodCallHandler( runtimeChannel, (call) => probe.future, ); addTearDown( () => messenger.setMockMethodCallHandler(runtimeChannel, null), ); await messenger.handlePlatformMessage( dropChannel.name, const StandardMethodCodec().encodeMethodCall( const MethodCall('event', { 'phase': 'enter', 'session': 1, 'x': 125.0, 'y': 65.0, 'files': [ {'path': '/replacement.mov'}, ], }), ), (_) {}, ); await tester.pump(); expect(target.file?.localPath, '/replacement.mov'); expect( nativeCalls.lastWhere((call) => call.method == 'setRegion').arguments, isNotNull, ); await tester.pumpWidget(const SizedBox()); probe.complete(null); await tester.pumpAndSettle(); expect( nativeCalls.lastWhere((call) => call.method == 'setRegion').arguments, isNull, ); debugDefaultTargetPlatformOverride = null; }, ); testWidgets( 'inactive timeline routes release late drags without probing media', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.macOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); final messenger = tester.binding.defaultBinaryMessenger; const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); const runtimeChannel = MethodChannel('cutdex_runtime'); final nativeCalls = []; var probes = 0; messenger.setMockMethodCallHandler(dropChannel, (call) async { nativeCalls.add(call); return null; }); messenger.setMockMethodCallHandler(runtimeChannel, (_) async { probes++; return jsonEncode({'value': null}); }); addTearDown( () => messenger.setMockMethodCallHandler(runtimeChannel, null), ); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _DropProjects(session, projectId), ), ], child: MaterialApp( home: TickerMode( enabled: false, child: TimelineExternalDropTarget( projectId: projectId, session: session, sequenceId: SequenceId('two'), child: const SizedBox.expand(), ), ), ), ), ); await tester.pumpAndSettle(); final target = tester.state( find.byType(TimelineExternalDropTarget), ); await target.event( const NativeFileDropEvent( phase: NativeFileDropPhase.enter, session: 7, position: Offset(125, 65), paths: ['/late.mov'], ), ); await tester.pumpAndSettle(); expect(target.sessionId, isNull); expect(probes, 0); expect( nativeCalls .where((call) => call.method == 'release') .map((call) => call.arguments), [ {'session': 7}, ], ); await tester.pumpWidget(const SizedBox()); await tester.pumpAndSettle(); debugDefaultTargetPlatformOverride = null; }, ); testWidgets( 'hiding a timeline cancels hover but retains access until probing finishes', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.macOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); final messenger = tester.binding.defaultBinaryMessenger; const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); const runtimeChannel = MethodChannel('cutdex_runtime'); final nativeCalls = []; final probe = Completer(); final visible = ValueNotifier(true); addTearDown(visible.dispose); messenger.setMockMethodCallHandler(dropChannel, (call) async { nativeCalls.add(call); return null; }); messenger.setMockMethodCallHandler(runtimeChannel, (_) => probe.future); addTearDown( () => messenger.setMockMethodCallHandler(runtimeChannel, null), ); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _DropProjects(session, projectId), ), ], child: MaterialApp( home: ValueListenableBuilder( valueListenable: visible, builder: (_, enabled, child) => TickerMode(enabled: enabled, child: child!), child: TimelineExternalDropTarget( projectId: projectId, session: session, sequenceId: SequenceId('two'), child: const SizedBox.expand(), ), ), ), ), ); await tester.pumpAndSettle(); final target = tester.state( find.byType(TimelineExternalDropTarget), ); await target.event( const NativeFileDropEvent( phase: NativeFileDropPhase.enter, session: 7, position: Offset(125, 65), paths: ['/late.mov'], ), ); await tester.pump(); expect(target.sessionId, 7); visible.value = false; await tester.pumpAndSettle(); final hiddenSession = target.sessionId; expect(nativeCalls.where((call) => call.method == 'release'), isEmpty); probe.complete(jsonEncode({'value': null})); await tester.pumpAndSettle(); expect(hiddenSession, isNull); expect( nativeCalls .where((call) => call.method == 'release') .map((call) => call.arguments), [ {'session': 7}, ], ); expect(session.dirty, false); await tester.pumpWidget(const SizedBox()); await tester.pumpAndSettle(); debugDefaultTargetPlatformOverride = null; }, ); for (final fail in [false, true]) { testWidgets( 'closing a Finder drop waits for pending import before releasing access (fail=$fail)', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.macOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); const runtimeChannel = MethodChannel('cutdex_runtime'); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; final nativeCalls = []; messenger.setMockMethodCallHandler(dropChannel, (call) async { nativeCalls.add(call); return null; }); messenger.setMockMethodCallHandler(runtimeChannel, (call) async { if (call.method == 'probe') { return { 'duration': {'numerator': '20', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 0, 'audioTrackIds': [], 'isProtected': false, 'audioTracks': >[], 'videoDisplaySizes': [ {'width': 1920, 'height': 1080}, ], }; } return null; }); addTearDown(() { messenger.setMockMethodCallHandler(dropChannel, null); messenger.setMockMethodCallHandler(runtimeChannel, null); }); final projects = _ImportingDropProjects(session, projectId); final target = GlobalKey(); await tester.pumpWidget( ProviderScope( overrides: [projectsProvider.overrideWith(() => projects)], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( key: target, projectId: projectId, session: session, sequenceId: SequenceId('two'), child: const SizedBox.expand(), ), ), ), ), ); await tester.pumpAndSettle(); target.currentState!.enterExternal( 1, '/slow.mov', const Offset(125, 65), ); await tester.pumpAndSettle(); expect(target.currentState!.incomingClip, isNotNull); final dropping = target.currentState!.drop(); await tester.pump(); expect(projects._importStarted.isCompleted, isTrue); await tester.pumpWidget(const SizedBox.shrink()); await tester.pump(); expect(nativeCalls.where((call) => call.method == 'release'), isEmpty); if (fail) { projects._importResult.completeError(StateError('import failed')); } else { projects._importResult.complete( MediaImportResult( assets: [ AssetDocument( id: 'imported', name: 'slow.mov', storage: AssetStorage.external, location: Uri.file('/slow.mov').toString(), metadata: const {'kind': 'video'}, ), ], added: 1, duplicates: 0, failures: [], ), ); } await dropping; await tester.pumpAndSettle(); expect( nativeCalls .where((call) => call.method == 'release') .map((call) => call.arguments), [ {'session': 1}, ], ); expect(session.dirty, isFalse); expect( session.persistence.timeline(SequenceId('two')).canUndo, isFalse, ); expect(tester.takeException(), isNull); debugDefaultTargetPlatformOverride = null; }, ); } testWidgets( 'Finder hover uses the shared timeline renderer and temporary media binding', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.macOS; addTearDown(() => debugDefaultTargetPlatformOverride = null); const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); const runtimeChannel = MethodChannel('cutdex_runtime'); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; final thumbnails = RuntimeTimelineThumbnails( resolveMedia: (ref) => session.mediaBinding(ref)?.media, resolveTrackSelection: (ref) => session.mediaBinding(ref)?.videoSelection, ); addTearDown(thumbnails.dispose); final view = session.view(SequenceId('two')); final nativeCalls = []; final thumbnailTimes = []; Completer? probeGate; messenger.setMockMethodCallHandler(dropChannel, (call) async { nativeCalls.add(call); return null; }); messenger.setMockMethodCallHandler(runtimeChannel, (call) async { if (call.method == 'probe') { await probeGate?.future; return { 'duration': {'numerator': '20', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 1, 'audioTrackIds': [1], 'isProtected': false, 'audioTracks': [ { 'start': {'numerator': '0', 'denominator': 1}, 'duration': {'numerator': '20', 'denominator': 1}, }, ], 'videoDisplaySizes': [ {'width': 1920, 'height': 1080}, ], }; } if (call.method == 'thumbnails') { final times = (call.arguments as Map)['times'] as List; thumbnailTimes.addAll(times); return [ for (final time in times) { 'requestedTime': time, 'actualTime': time, 'width': 1, 'height': 1, 'format': 'jpeg', 'data': base64Decode( 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+a9uoAAAAASUVORK5CYII=', ), }, ]; } return null; }); addTearDown(() { messenger.setMockMethodCallHandler(dropChannel, null); messenger.setMockMethodCallHandler(runtimeChannel, null); }); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _DropProjects(session, projectId), ), ], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( projectId: projectId, session: session, sequenceId: SequenceId('two'), child: TimelineView( controller: view, thumbnails: thumbnails, classifyContent: session.classify, ), ), ), ), ), ); await tester.pumpAndSettle(); Future send(String phase, {int id = 1}) async { await messenger.handlePlatformMessage( dropChannel.name, const StandardMethodCodec().encodeMethodCall( MethodCall('event', { 'phase': phase, 'session': id, 'x': 125.0, 'y': 65.0, 'files': [ {'path': '/hover.mov'}, ], }), ), (_) {}, ); } await send('enter'); await tester.pumpAndSettle(); expect(view.dragGhost, isNotNull); expect(view.dragGhost!.top, 53); expect( view.dragGhost!.body.start, 50 * TimelineFormat.fps24.frameGrid.quantumTicks, ); final preview = view.project( TimelineViewportRect(width: 800, height: 600), ); final record = preview.version.kernelVersion.query().element( view.dragGhost!.source.owner, ); expect(record.name, 'hover.mov'); expect( session.mediaBinding(record.payloadRef!)!.media.uri, Uri.file('/hover.mov'), ); expect(thumbnailTimes, isNotEmpty); expect(find.byType(Image), findsNothing); final count = thumbnailTimes.length; await send('move'); await tester.pumpAndSettle(); expect(thumbnailTimes.length, count); expect(session.dirty, isFalse); await send('exit'); await tester.pumpAndSettle(); expect(view.dragGhost, isNull); expect(session.mediaBinding(record.payloadRef!), isNull); expect(nativeCalls.where((c) => c.method == 'release'), hasLength(1)); expect(session.dirty, isFalse); probeGate = Completer(); await send('enter'); await tester.pump(); await send('exit'); final previousProbe = probeGate; probeGate = null; try { await send('enter', id: 2); await tester.pump(); await tester.pump(); expect( view.dragGhost, isNotNull, reason: 'A cancelled probe must not block a new drag', ); await send('exit', id: 2); } finally { previousProbe.complete(); } await tester.pumpAndSettle(); expect(view.dragGhost, isNull); expect(session.dirty, isFalse); expect(session.persistence.timeline(SequenceId('two')).canUndo, isFalse); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); debugDefaultTargetPlatformOverride = null; }, ); testWidgets( 'Windows Explorer hover exposes files before drop and renders a clip', (tester) async { debugDefaultTargetPlatformOverride = TargetPlatform.windows; addTearDown(() => debugDefaultTargetPlatformOverride = null); const runtimeChannel = MethodChannel('cutdex_runtime'); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; const dropChannel = MethodChannel('cutdex_native/file_drop/timeline'); messenger.setMockMethodCallHandler(dropChannel, (_) async => null); addTearDown(() => messenger.setMockMethodCallHandler(dropChannel, null)); messenger.setMockMethodCallHandler(runtimeChannel, (call) async { final request = jsonDecode((call.arguments as Map)['request'] as String) as Map; return jsonEncode({ 'value': request['method'] == 'probe' ? { 'duration': {'numerator': '12', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 0, 'audioTrackIds': [], 'isProtected': false, 'audioTracks': [], } : null, }); }); addTearDown( () => messenger.setMockMethodCallHandler(runtimeChannel, null), ); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith( () => _DropProjects(session, projectId), ), ], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( projectId: projectId, session: session, sequenceId: SequenceId('two'), child: const SizedBox.expand(), ), ), ), ), ); await tester.pumpAndSettle(); await ProviderScope.containerOf( tester.element(find.byType(TimelineExternalDropTarget)), ).read(projectsProvider.future); await tester.pumpAndSettle(); Future send(String phase, double x) async { final done = Completer(); messenger.handlePlatformMessage( 'cutdex_native/file_drop/timeline', const StandardMethodCodec().encodeMethodCall( MethodCall('event', { 'phase': phase, 'session': 1, 'x': x, 'y': 65.0, 'files': phase == 'enter' ? [ {'path': r'C:\media\hover.mov'}, ] : [], }), ), (_) => done.complete(), ); await done.future; await tester.pumpAndSettle(); } await send('enter', 125.0); expect(session.view(SequenceId('two')).dragGhost, isNotNull); expect(session.dirty, isFalse); await send('move', 126.0); expect(session.view(SequenceId('two')).dragGhost, isNotNull); await send('exit', 126.0); expect(session.view(SequenceId('two')).dragGhost, isNull); expect(session.dirty, isFalse); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); debugDefaultTargetPlatformOverride = null; }, ); testWidgets( 'project video hover reuses drag geometry; cancel restores feedback', (tester) async { final asset = AssetDocument( id: 'video', name: 'project.mov', storage: AssetStorage.external, location: 'file:///project.mov', metadata: const {'kind': 'video'}, ); final projects = _DropProjects(session, projectId, mediaAsset: asset); final drag = MediaAssetDrag(projectId: projectId, assetId: asset.id); const runtimeChannel = MethodChannel('cutdex_runtime'); final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; messenger.setMockMethodCallHandler(runtimeChannel, (call) async { if (call.method == 'probe') { return { 'duration': {'numerator': '20', 'denominator': 1}, 'videoTrackCount': 1, 'videoTrackIds': [1], 'audioTrackCount': 0, 'audioTrackIds': [], 'audioTracks': [], 'isProtected': false, }; } return null; }); addTearDown( () => messenger.setMockMethodCallHandler(runtimeChannel, null), ); await tester.pumpWidget( ProviderScope( overrides: [projectsProvider.overrideWith(() => projects)], child: MaterialApp( home: Scaffold( body: Row( children: [ SizedBox( width: 180, child: Draggable( data: drag, dragAnchorStrategy: pointerDragAnchorStrategy, feedback: ValueListenableBuilder( valueListenable: drag.feedbackVisible, builder: (_, visible, _) => visible ? const Text('source feedback') : const SizedBox.shrink(), ), child: const Text('drag source'), ), ), Expanded( child: TimelineAssetDropTarget( projectId: projectId, session: session, sequenceId: SequenceId('two'), child: const SizedBox.expand(), ), ), ], ), ), ), ), ); await tester.pumpAndSettle(); await ProviderScope.containerOf( tester.element(find.byType(TimelineAssetDropTarget)), ).read(projectsProvider.future); await tester.pumpAndSettle(); final gesture = await tester.startGesture( tester.getCenter(find.text('drag source')), ); await gesture.moveBy(const Offset(20, 0)); await tester.pump(); await gesture.moveTo(const Offset(305, 65)); await tester.pumpAndSettle(); final view = session.view(SequenceId('two')); expect(view.dragGhost, isNotNull); expect( view.dragGhost!.body.end - view.dragGhost!.body.start, 20 * TimelineClock.ticksPerSecond, ); expect(find.text('source feedback'), findsNothing); expect(drag.feedbackVisible.value, isFalse); expect(session.dirty, isFalse); await gesture.moveTo(const Offset(365, 210)); await tester.pumpAndSettle(); expect(view.dragGhost!.top, 198); final ghost = view.dragGhost!; final preview = view.project( TimelineViewportRect(width: 620, height: 600), ); expect( preview.version.kernelVersion .query() .connectionOrderLocation(ghost.source.owner) ?.side, ConnectionSide.below, ); expect( view.dragGhost!.body.start, 74 * TimelineFormat.fps24.frameGrid.quantumTicks, ); await gesture.moveTo(const Offset(50, 500)); await tester.pumpAndSettle(); expect(view.dragGhost, isNull); expect(drag.feedbackVisible.value, isTrue); expect(find.text('source feedback'), findsOneWidget); await gesture.up(); await tester.pumpAndSettle(); expect(session.persistence.timeline(SequenceId('two')).canUndo, isFalse); expect(session.dirty, isFalse); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); }, ); testWidgets( 'empty timeline ghost moves freely but drops on Primary at zero', (tester) async { await tester.runAsync(() async { final timelines = await workspace.createTimeline('Empty drop'); final document = await workspace.loadTimeline( projectId, timelines.singleWhere((d) => d.name == 'Empty drop').id, ); session = await workspace.openTimelineSession(projectId, document); }); final projects = _DropProjects(session, projectId); await tester.runAsync(() => workspace.project!.saveAsset(projects.asset)); final id = session.activeSequenceId!; final view = session.view(id); final kernel = session.persistence.timeline(id); final before = kernel.current; final incoming = ValueNotifier(null); final target = GlobalKey(); addTearDown(incoming.dispose); await tester.pumpWidget( ProviderScope( overrides: [projectsProvider.overrideWith(() => projects)], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( key: target, projectId: projectId, session: session, sequenceId: id, incoming: incoming, child: TimelineView(controller: view), ), ), ), ), ); await tester.pumpAndSettle(); for (final point in [ const Offset(180, 10), const Offset(240, 65), const Offset(300, 210), ]) { incoming.value = (asset: projects.asset, globalPosition: point); await tester.pumpAndSettle(); final ghost = view.dragGhost!; expect(ghost.top, point.dy.round() - 12); expect( ghost.body.start, (point.dx / 60 * TimelineClock.ticksPerSecond).round(), ); expect(kernel.current, same(before)); final q = view .project(TimelineViewportRect(width: 800, height: 600)) .version .kernelVersion .query(); expect(q.absoluteStart(ghost.source.owner), 0); expect(q.connectionForTarget(ghost.source.owner), isNull); expect(q.storylineLength(q.primaryStoryline), 1); } final clipId = target.currentState!.incomingClip!.clipId; await tester.runAsync(() async { await target.currentState!.drop(); await session.flush(); }); await tester.pumpAndSettle(); final q = kernel.current.query(); final clip = q.elementById(clipId)!; expect(q.absoluteStart(clip), 0); expect(q.connectionForTarget(clip), isNull); expect(q.storylineLength(q.primaryStoryline), 1); expect(view.dragGhost, isNull); session.undo(id); expect(kernel.current, same(before)); expect(session.canUndo(id), isFalse); await tester.runAsync(session.flush); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); }, ); for (final pending in [false, true]) { testWidgets( 'replacing incoming source clears preview and pending media ($pending)', (tester) async { final projects = _DropProjects(session, projectId); final ready = Completer(); if (pending) projects.mediaReady = ready.future; final oldSource = ValueNotifier(null); final newSource = ValueNotifier(null); addTearDown(oldSource.dispose); addTearDown(newSource.dispose); final id = SequenceId('two'); final view = session.view(id); final before = session.persistence.timeline(id).current; final target = GlobalKey(); Widget surface( ValueNotifier source, ) => ProviderScope( // ignore: riverpod_lint/scoped_providers_should_specify_dependencies overrides: [projectsProvider.overrideWith(() => projects)], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( key: target, projectId: projectId, session: session, sequenceId: id, incoming: source, child: TimelineView(controller: view), ), ), ), ); await tester.pumpWidget(surface(oldSource)); oldSource.value = ( asset: projects.asset, globalPosition: const Offset(180, 210), ); await tester.pump(); final payload = target.currentState!.incomingClip?.payloadId; if (!pending) expect(view.dragGhost, isNotNull); await tester.pumpWidget(surface(newSource)); ready.complete(); await tester.pumpAndSettle(); expect(view.dragGhost, isNull); expect(target.currentState!.incomingClip, isNull); expect(target.currentState!.hasPreview, isFalse); if (payload != null) { expect(session.mediaBinding(PayloadRef(payload)), isNull); } expect(session.persistence.timeline(id).current, same(before)); expect(session.canUndo(id), isFalse); expect(session.dirty, isFalse); oldSource.value = ( asset: projects.asset, globalPosition: const Offset(240, 210), ); await tester.pumpAndSettle(); expect(view.dragGhost, isNull); newSource.value = oldSource.value; await tester.pumpAndSettle(); expect(view.dragGhost, isNotNull); newSource.value = null; await tester.pumpAndSettle(); expect(view.dragGhost, isNull); await tester.pumpWidget(const SizedBox()); }, ); } testWidgets( 'image movement waits for media resolution before creating a clip', (tester) async { final projects = _DropProjects(session, projectId); final ready = Completer(); projects.mediaReady = ready.future; final incoming = ValueNotifier(null); addTearDown(incoming.dispose); final view = session.view(SequenceId('two')); await tester.pumpWidget( ProviderScope( overrides: [projectsProvider.overrideWith(() => projects)], child: MaterialApp( home: Scaffold( body: TimelineExternalDropTarget( projectId: projectId, session: session, sequenceId: SequenceId('two'), incoming: incoming, child: TimelineView(controller: view), ), ), ), ), ); await tester.pumpAndSettle(); incoming.value = ( asset: projects.asset, globalPosition: const Offset(125, 65), ); await tester.pump(); incoming.value = ( asset: projects.asset, globalPosition: const Offset(126, 65), ); await tester.pump(); try { expect( view.dragGhost, isNull, reason: 'Do not create an unbound placeholder clip', ); } finally { ready.complete(); } await tester.pumpAndSettle(); final frame = view.project(TimelineViewportRect(width: 800, height: 600)); final clip = frame.version.kernelVersion.query().element( view.dragSource!.owner, ); expect( session.mediaBinding(clip.payloadRef!)?.media.id, projects.asset.id, ); incoming.value = null; await tester.pumpAndSettle(); expect(view.dragGhost, isNull); expect(session.dirty, isFalse); await tester.pumpWidget(const SizedBox()); }, ); testWidgets( 'media card drag uses frame-aligned viewport position; cancelled drag does not insert', (tester) async { final controller = _DropProjects(session, projectId); final fixture = await controller.build(); await tester.runAsync( () => workspace.project!.saveAsset(fixture.assets.single), ); await tester.pumpWidget( ProviderScope( overrides: [ projectsProvider.overrideWith(() => controller), mediaAvailabilityProvider( projectId, fixture.assets.single, ).overrideWith((ref) async => MediaAvailability.available), editorTimelineProvider( projectId, 'project', ).overrideWith((ref) async => session), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: Row( children: [ SizedBox(width: 260, child: MediaPanel(projectId: projectId)), Expanded( child: EditorTimelinePanel( projectId: projectId, timelineId: 'project', ), ), ], ), ), ), ), ); await tester.pumpAndSettle(); final source = find.text('image.png'); final surface = tester.getRect( find.byKey(const Key('editor-timeline-surface')), ); final gesture = await tester.startGesture(tester.getCenter(source)); await gesture.moveBy(const Offset(20, 0)); await tester.pump(); await gesture.moveTo(Offset(surface.left + 125, surface.top + 65)); await tester.pump(); expect(session.view(SequenceId('two')).dragGhost, isNotNull); expect(session.dirty, isFalse); final incomingId = tester .state( find.byType(TimelineExternalDropTarget), ) .incomingClip! .clipId; await gesture.up(); await tester.pump(); await tester.runAsync(session.flush); await tester.pumpAndSettle(); final kernel = session.persistence.timeline(SequenceId('two')); final query = kernel.current.query(); final inserted = query.elementById(incomingId)!; expect( session.payloadFor(query.element(inserted).payloadRef!)!.assetIds, ['asset'], ); expect( query.absoluteStart(inserted), 50 * TimelineFormat.fps24.frameGrid.quantumTicks, ); final committed = kernel.current; await tester.runAsync(session.flush); final cancelled = await tester.startGesture(tester.getCenter(source)); await cancelled.moveBy(const Offset(20, 0)); await tester.pump(); await cancelled.moveTo(const Offset(10, 550)); await cancelled.up(); await tester.pumpAndSettle(); expect(kernel.current, same(committed)); expect(session.dirty, isFalse); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); }, ); testWidgets( 'properties follow clip type, sequence and selection without editing history', (tester) async { final sequenceId = SequenceId('two'); for (final kind in ['video', 'audio', 'image']) { final asset = AssetDocument( id: kind, name: '$kind asset', storage: AssetStorage.external, location: 'file:///$kind', ); await tester.runAsync(() => workspace.project!.saveAsset(asset)); session.insertAsset( sequenceId: sequenceId, assetId: asset.id, assetName: asset.name, uri: Uri.file('/$kind'), duration: RationalTime.seconds(3), position: 10 * TimelineClock.ticksPerSecond, kind: kind, hasAudio: kind != 'image', ); } await tester.runAsync(session.flush); final view = session.view(sequenceId); final kernel = session.persistence.timeline(sequenceId); final savedVersion = kernel.current; ElementHandle handle(String kind) { final id = kernel .exportDto() .elements .singleWhere((e) => e.name == '$kind asset') .id; return view.version.kernelVersion.query().elementById(id)!; } Future select(String kind, {bool body = false}) async { view.setSelection([ body ? LayoutBodyId.element(handle(kind)) : handle(kind), ]); await tester.pumpAndSettle(); } void tabs(List expected) { for (final name in [ 'picture', 'mask', 'audio', 'speed', 'animation', 'basic', ]) { expect( find.byKey(ValueKey('property-tab-$name')), expected.contains(name) ? findsOneWidget : findsNothing, ); } } view.clearSelection(); await tester.pumpWidget( ProviderScope( overrides: [ editorTimelineProvider( projectId, 'project', ).overrideWith((ref) async => session), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 225, child: EditorPropertiesPanel( projectId: projectId, timelineId: 'project', ), ), ), ), ), ); await tester.pumpAndSettle(); expect(find.text('项目属性'), findsOneWidget); tabs([]); await select('video'); tabs(['picture', 'mask', 'audio', 'speed', 'animation']); expect(find.text('属性'), findsNothing); expect( find.ancestor(of: find.text('对齐'), matching: find.byType(ShaderMask)), findsOneWidget, ); final panelTop = tester.getTopLeft(find.byType(EditorPropertiesPanel)).dy; final tabBounds = tester.getRect( find.byKey(const ValueKey('property-tab-picture')), ); expect(tabBounds.height, AppControlSize.headerButton); expect( tabBounds.left - tester.getRect(find.byType(EditorPropertiesPanel)).left, 6, ); expect(tabBounds.top - panelTop, 6); final pictureLabel = find.descendant( of: find.byKey(const ValueKey('property-tab-picture')), matching: find.text('画面'), ); expect(pictureLabel, findsOneWidget); expect( tester.getTopLeft(find.text('对齐')).dx, tester.getTopLeft(pictureLabel).dx, ); final propertyContentLeft = tester.getTopLeft(find.text('对齐')).dx; final sectionTitle = tester.widget(find.text('对齐')).style!; expect(sectionTitle.fontSize, 13); expect(sectionTitle.height, 1.4); expect(sectionTitle.fontWeight, FontWeight.w500); expect(sectionTitle.color, EditorTheme.penLight.colorScheme.onSurface); expect(tabBounds.top, greaterThanOrEqualTo(panelTop)); expect( tabBounds.bottom, lessThanOrEqualTo(panelTop + AppControlSize.panelToolbar), ); expect(find.byKey(const Key('property-clip-name')), findsNothing); expect(find.text('video asset'), findsNothing); await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); await tester.pumpAndSettle(); expect(find.text('1.00×'), findsOneWidget); expect( session.isCustomSpeedEnabled( sequenceId, view.version.kernelVersion.query().element(handle('video')).id, ), isFalse, ); expect(view.geometry.primaryHeight, 88); await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); await tester.pumpAndSettle(); expect( session.isCustomSpeedEnabled( sequenceId, view.version.kernelVersion.query().element(handle('video')).id, ), isTrue, ); expect(view.geometry.primaryHeight, 98); await tester.tap(find.byKey(const ValueKey('property-tab-picture'))); await tester.pumpAndSettle(); expect(view.geometry.primaryHeight, 98); await tester.tap(find.byKey(const ValueKey('property-tab-speed'))); await tester.pumpAndSettle(); await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); await tester.pumpAndSettle(); expect( session.isCustomSpeedEnabled( sequenceId, view.version.kernelVersion.query().element(handle('video')).id, ), isFalse, ); expect(view.geometry.primaryHeight, 88); expect(kernel.current, same(savedVersion)); expect(tester.getTopLeft(find.text('速度')).dx, propertyContentLeft); expect( tester.getSize(find.byKey(const Key('split-speed-segment'))).height, AppControlSize.propertyControl, ); view.seekTo( view.version.kernelVersion.query().absoluteStart(handle('video')) + TimelineClock.ticksPerSecond, ); await tester.pumpAndSettle(); expect( find.text('1.00×'), findsOneWidget, ); // Playhead does not reset tabs. view.seekTo( view.version.kernelVersion.query().absoluteEnd(handle('video')), ); await tester.pumpAndSettle(); tabs(['picture', 'mask', 'audio', 'speed', 'animation']); expect(find.text('项目属性'), findsNothing); expect(find.text('1.00×'), findsOneWidget); expect(view.selectedIdentities, isNotEmpty); view.seekTo( view.version.kernelVersion.query().absoluteEnd(handle('video')) + 1, ); await tester.pumpAndSettle(); tabs(['picture', 'mask', 'audio', 'speed', 'animation']); expect(find.text('项目属性'), findsNothing); await select('audio', body: true); tabs(['audio', 'speed']); expect(find.byKey(const Key('audio-db')), findsOneWidget); expect(tester.getTopLeft(find.text('音量')).dx, propertyContentLeft); expect( tester.getSize(find.byKey(const Key('audio-key'))), const Size.square(AppControlSize.propertyControl), ); expect( tester.getSize(find.byKey(const Key('audio-db'))).height, AppControlSize.propertyControl, ); expect( tester .widget( find.descendant( of: find.byKey(const Key('audio-db')), matching: find.byType(TextField), ), ) .controller! .text, '0.0', ); await select('image'); tabs(['picture', 'mask', 'animation']); expect(find.byType(PictureProperties), findsOneWidget); view.setSelection([handle('image'), handle('video')]); await tester.pumpAndSettle(); tabs([]); expect(find.textContaining('已选择 2 个片段'), findsOneWidget); view.setSelection([const ElementHandle(99999, 1)]); await tester.pumpAndSettle(); tabs([]); await select('video'); session.selectSequence(SequenceId('one')); await tester.pumpAndSettle(); tabs([]); final otherView = session.view(SequenceId('one')); otherView.setSelection([ otherView.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); await tester.pumpAndSettle(); tabs(['basic']); session.selectSequence(sequenceId); await tester.pumpAndSettle(); tabs(['picture', 'mask', 'audio', 'speed', 'animation']); expect(kernel.current, same(savedVersion)); expect(session.dirty, isFalse); view.deleteSelection(); await tester.pumpAndSettle(); tabs([]); expect(find.text('video asset'), findsNothing); view.undo(); await select('video'); tabs(['picture', 'mask', 'audio', 'speed', 'animation']); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); await tester.runAsync(session.flush); }, ); for (final locale in const [Locale('zh')]) { testWidgets('renders and edits the timeline in $locale', (tester) async { await tester.pumpWidget( ProviderScope( overrides: [ editorTimelineProvider( projectId, 'project', ).overrideWith((ref) async => session), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: locale, theme: EditorTheme.penLight, home: Scaffold( body: EditorTimelinePanel( projectId: projectId, timelineId: 'project', ), ), ), ), ); await tester.pumpAndSettle(); expect(find.byType(TimelineRuler), findsOneWidget); expect(find.byType(TimelineView), findsOneWidget); final localized = AppLocalizations.of( tester.element(find.byType(EditorTimelinePanel)), )!; expect( Directionality.of(tester.element(find.byType(EditorTimelinePanel))), TextDirection.ltr, ); expect( Directionality.of(tester.element(find.byType(TimelineView))), TextDirection.ltr, ); expect( tester.widget(find.byType(TimelineView)).controller, same(session.view(SequenceId('two'))), ); final view = session.view(SequenceId('two')); final beforeEmptyDelete = view.version.kernelVersion; view.clearSelection(); await tester.pump(); expect(view.canDeleteSelection, isFalse); final deleteButton = find.byKey( const ValueKey('timeline-delete-selection'), ); expect(tester.widget(deleteButton).onPressed, isNotNull); await tester.tap(deleteButton); await tester.pump(); expect(view.version.kernelVersion, same(beforeEmptyDelete)); view.setSelection([ view.version.kernelVersion.query().elementById(ElementId('clip'))!, ]); view.seekTo(5 * TimelineClock.ticksPerSecond); await tester.pump(); final toolbarButtons = find.descendant( of: find.byKey(const Key('timeline-toolbar')), matching: find.byType(IconButton), ); expect(toolbarButtons, findsNWidgets(7)); final fitButton = find.byKey(const ValueKey('timeline-fit')); expect( tester.widget(fitButton).tooltip, localized.fitTimeline, ); final toolbarBounds = tester.getRect( find.byKey(const Key('timeline-toolbar')), ); final panelBounds = tester.getRect(find.byType(EditorTimelinePanel)); expect(toolbarBounds.left, panelBounds.left); expect(toolbarBounds.right, panelBounds.right); final buttonBounds = []; for (final button in toolbarButtons.evaluate()) { final bounds = tester.getRect( find.byElementPredicate((e) => e == button), ); if (button.widget.key != const ValueKey('timeline-fit')) { buttonBounds.add(bounds); } expect( bounds.size, const Size(AppControlSize.headerButton, AppControlSize.headerButton), ); expect((button.widget as IconButton).iconSize, AppIconSize.header); } expect(buttonBounds.first.left - panelBounds.left, AppSpacing.gap); expect( panelBounds.right - tester.getRect(fitButton).right, AppSpacing.gap, ); for (var i = 1; i < buttonBounds.length; i++) { expect( buttonBounds[i].left - buttonBounds[i - 1].right, AppSpacing.tiny, ); } for (final (tooltip, sourceStart) in [ (localized.trimLeftTooltip, 5 * TimelineClock.ticksPerSecond), (localized.trimRightTooltip, 0), ]) { final before = view.version.kernelVersion; await tester.tap(find.byTooltip(tooltip)); await tester.pump(); final q = view.version.kernelVersion.query(); final clip = q.element(q.elementById(ElementId('clip'))!); expect(clip.duration, 5 * TimelineClock.ticksPerSecond); expect(clip.sourceStart, sourceStart); await tester.tap(find.byTooltip(localized.undo)); await tester.pump(); expect(view.version.kernelVersion, same(before)); expect(view.canUndo, isFalse); } view.seekTo(0); await tester.pump(); expect( tester .widget( find.byKey(const ValueKey('timeline-trim-left')), ) .onPressed, isNull, ); expect( tester .widget( find.byKey(const ValueKey('timeline-trim-right')), ) .onPressed, isNull, ); view.seekTo(5 * TimelineClock.ticksPerSecond); await tester.pump(); await tester.tap(find.byTooltip(localized.splitAtPlayhead)); await tester.pump(); expect(view.canUndo, isTrue); await tester.tap(find.byTooltip(localized.undo)); await tester.pump(); expect(view.canRedo, isTrue); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); await tester.runAsync(() => session.flush()); }); } } class _LivePropertyPreview extends PreviewController { @override bool busy = true; _LivePropertyPreview(EditorTimelineSession timeline) : super( timeline: timeline, runtime: CutdexRuntime(), activeSequence: () => timeline.activeSequenceId, viewForSequence: timeline.view, ); @override PreviewVisual? visualForProperties(ElementId element) => visuals.where((visual) => visual.elementId == element).firstOrNull; @override List get visuals { final query = viewForSequence(activeSequence()!).version.kernelVersion .query(); final id = ElementId('clip'); return transforms.project([ PreviewVisual( layerId: 'video', elementId: id, lane: 0, transform: ClipTransform.fromRecord( query.element(query.elementById(id)!), ), geometry: const PreviewGeometry( center: Offset(100, 100), size: Size(200, 200), ), ), ], Size(canvas.width, canvas.height)); } @override PreviewTransformSession get transforms => _transforms; late final _transforms = PreviewTransformSession( canBegin: () => true, select: (_) {}, prepareNative: () async => true, updateNative: (_, _, rendered) => rendered(), commit: (id, value) { final sequence = activeSequence()!; final edit = timeline.previewParameters(sequence, id, value.parameters); timeline.commitParameters( sequence, edit, parameterTargets: ClipTransform.targets, ); }, cancelNative: () {}, failed: (error) => throw error, changed: () {}, ); } class _ViewProjects extends _DropProjects { _ViewProjects(super.session, super.projectId); @override Future openTimelineSession( String projectId, String timelineId, ) async => session; } class _DropProjects extends Projects { _DropProjects(this.session, this.projectId, {AssetDocument? mediaAsset}) : asset = mediaAsset ?? AssetDocument( id: 'asset', name: 'image.png', storage: AssetStorage.external, location: 'file:///image.png', metadata: const {'kind': 'image'}, ); final EditorTimelineSession session; final String projectId; final AssetDocument asset; @visibleForTesting Future? mediaReady; @override Future withAssetMedia( String? projectId, AssetDocument asset, Future Function(MediaReference) action, ) async { await mediaReady; return action( MediaReference( id: asset.id, uri: Uri.parse(asset.location), isImage: asset.metadata['kind'] == 'image', ), ); } @override Future build() async => ProjectState( activeProject: RecentProject( id: projectId, name: 'Project', path: '/Project.cutdex', ), timeline: session.document, assets: [asset], ); } class _ImportingDropProjects extends _DropProjects { _ImportingDropProjects(super.session, super.projectId); final _importStarted = Completer(); final _importResult = Completer(); @override Future importExternalMedia( String projectId, List files, { bool Function()? isCancelled, }) { _importStarted.complete(); return _importResult.future; } } class _CachedViewProjects extends _ViewProjects { _CachedViewProjects(super.session, super.projectId); @override EditorTimelineSession? cachedTimelineSession( String projectId, String timelineId, ) => projectId == this.projectId && timelineId == session.document.id ? session : null; }