import 'package:cutdex/app/editor_theme.dart'; import 'dart:math' as math; import 'dart:ui' as ui; import 'package:cutdex/features/properties/speed_properties.dart'; import 'package:cutdex/features/timeline/timeline_speed_editor.dart'; import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex_ui/widgets.dart'; import 'package:cutdex/workspace/timeline_session.dart'; import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/timeline/engine.dart'; import 'package:cutdex_sdk/timeline/layout.dart'; import 'package:cutdex_sdk/timeline/model.dart'; import 'package:cutdex_sdk/timeline_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_test/flutter_test.dart'; import 'support/preview_fixture.dart'; void main() { testWidgets('split speed then blade the clip at arbitrary playheads', ( tester, ) async { final f = (await tester.runAsync( () => createPreviewFixture( Uri.file('/test/video.mov'), clipDuration: RationalTime.seconds(600), ), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final controller = f.timeline.view(sequence); final kernel = f.timeline.persistence.timeline(sequence); f.timeline.setClipSpeed(sequence, id, 1.1); f.timeline.setCustomSpeedEnabled(sequence, id, true); final handle = kernel.current.query().elementById(id)!; controller.setSelection([handle]); controller.seekTo(666769090558); final before = kernel.current.query().element(handle); expect(() => before.retime!.sourceAt(666769090558), throwsArgumentError); final history = kernel.historyVersions.length; await tester.pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 300, height: 400, child: SpeedProperties( session: f.timeline, sequence: sequence, clip: id, ), ), ), ), ); await tester.tap(find.byKey(const Key('split-speed-segment'))); await tester.pump(); expect(find.byType(SnackBar), findsNothing); expect(find.text('2 个速度区间'), findsOneWidget); final split = kernel.current.query().element(handle); expect(split.retime!.segments, hasLength(2)); expect(split.retime!.segments.first.projectDuration, 666769090558); expect(split.duration, before.duration); expect(split.sourceStart, before.sourceStart); expect(split.sourceDuration, before.sourceDuration); expect(controller.playheadTick, 666769090558); expect(controller.selectedIdentities, contains(handle)); expect(kernel.historyVersions.length, history + 1); controller.seekTo(327469570558); expect( () => split.retime!.sourceAt(controller.playheadTick), throwsArgumentError, ); expect(controller.cutSelectionAtPlayhead(), isTrue); expect(controller.commandRejection, isNull); final cutVersion = kernel.current; final query = cutVersion.query(); final left = query.element(handle); final right = query.element(query.elementAt(query.primaryStoryline, 1)); expect(f.timeline.isCustomSpeedEnabled(sequence, left.id), isTrue); expect(f.timeline.isCustomSpeedEnabled(sequence, right.id), isTrue); expect(controller.geometry.primaryClipHeightFor(handle), 92); expect( controller.geometry.primaryClipHeightFor(query.elementById(right.id)!), 92, ); expect(left.duration, 327469570558); expect(left.duration + right.duration, split.duration); expect(left.retime!.segments, hasLength(1)); expect(right.retime!.segments, hasLength(2)); expect(left.retime!.sourceAt(left.duration), right.retime!.sourceAt(0)); expect(left.sourceStart, split.sourceStart); expect( right.sourceStart + right.sourceDuration, split.sourceStart + split.sourceDuration, ); expect(kernel.historyVersions.length, history + 2); f.timeline.undo(sequence); expect(kernel.current.query().element(handle).duration, split.duration); f.timeline.redo(sequence); expect(kernel.current, same(cutVersion)); expect(f.timeline.isCustomSpeedEnabled(sequence, right.id), isTrue); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); for (final connected in [false, true]) { for (final enabled in [false, true]) { testWidgets( 'blade inherits speed visibility: connected $connected, enabled $enabled', (tester) async { final duration = RationalTime.seconds(2); final f = (await tester.runAsync( () => createPreviewFixture( Uri.file('/test/video.mov'), timelineOverride: TimelineDto( id: SequenceId('one'), format: TimelineFormat.fps30, primaryStorylineId: StorylineId('primary'), storylines: [ StorylineDto( id: StorylineId('primary'), elementIds: [ if (!connected) ElementId('clip'), ElementId('normal'), ], ), ], elements: [ for (final id in ['clip', 'normal']) ElementDto( id: ElementId(id), structure: ElementStructure.content, payloadRef: PayloadRef('source'), duration: duration, sourceRange: TimeRange( start: RationalTime.zero, duration: duration, ), mediaRange: TimeRange( start: RationalTime.zero, duration: duration, ), ), ], connections: [ if (connected) ConnectionDto( id: ConnectionId('connection'), anchorId: ElementId('normal'), targetId: ElementId('clip'), anchorTime: RationalTime.zero, targetTime: RationalTime.zero, side: ConnectionSide.above, ), ], ), ), ))!; final sequence = SequenceId('one'); final session = f.timeline; final view = session.view(sequence); final kernel = session.persistence.timeline(sequence); session.setClipSpeed(sequence, ElementId('clip'), 1.1); session.setCustomSpeedEnabled(sequence, ElementId('clip'), enabled); final query = kernel.current.query(); final clip = query.elementById(ElementId('clip'))!; final normal = query.elementById(ElementId('normal'))!; view.setSelection([connected ? LayoutBodyId.element(clip) : clip]); view.setCamera(view.camera.panBy(verticalPixels: -100)); await tester.pumpWidget( MaterialApp( theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 800, height: 400, child: _speedSurface( session: session, sequence: sequence, controller: view, ), ), ), ), ); final before = kernel.current; view.seekTo(7 * TimelineClock.ticksPerSecond ~/ 10); expect(view.cutSelectionAtPlayhead(), isTrue); await tester.pump(); final cutVersion = kernel.current; final cutQuery = cutVersion.query(); final rightId = kernel .exportDto() .elements .singleWhere( (e) => e.id != ElementId('clip') && e.id != ElementId('normal'), ) .id; final right = cutQuery.elementById(rightId)!; void expectHeaders(int count) { expect( find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(count), ); expect( session.isCustomSpeedEnabled(sequence, ElementId('normal')), isFalse, ); expect(view.geometry.primaryClipHeightFor(normal), 76); } expect(session.isCustomSpeedEnabled(sequence, rightId), enabled); expect(view.geometry.primaryClipHeightFor(right), enabled ? 92 : 76); if (connected) { expect( view.version.scene.bodies[LayoutBodyId.element(right)]!.height, enabled ? 92 : 76, ); } expectHeaders(enabled ? 2 : 0); view.clearSelection(); await tester.pump(); expectHeaders(enabled ? 2 : 0); session.undo(sequence); await tester.pump(); expect(kernel.current, same(before)); expectHeaders(enabled ? 1 : 0); session.redo(sequence); await tester.pump(); expect(kernel.current, same(cutVersion)); expectHeaders(enabled ? 2 : 0); // Each fragment can be disabled independently; its next split inherits // that current choice rather than the original ancestor's choice. session.setCustomSpeedEnabled(sequence, rightId, false); await tester.pump(); expectHeaders(enabled ? 1 : 0); view.setSelection([connected ? LayoutBodyId.element(right) : right]); view.seekTo(TimelineClock.ticksPerSecond); expect(view.cutSelectionAtPlayhead(), isTrue); await tester.pump(); expectHeaders(enabled ? 1 : 0); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }, ); } } for (final start in ['top', 'bottom', 'diagonal']) { testWidgets('speed handle owns edge gestures: $start', (tester) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov')), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final controller = f.timeline.view(sequence); final kernel = f.timeline.persistence.timeline(sequence); final before = kernel.current; final handle = before.query().elementById(id)!; final original = before.query().element(handle); final history = kernel.historyVersions.length; f.timeline.setCustomSpeedEnabled(sequence, id, true); await tester.pumpWidget( MaterialApp( theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 800, height: 400, child: TimelineInteractionRegion( controller: controller, edgeScrollExtent: 0, child: _speedSurface( session: f.timeline, sequence: sequence, controller: controller, ), ), ), ), ), ); final bar = tester.getRect(find.byKey(const ValueKey('speed-segment-0'))); final viewport = TimelineViewportRect(width: 800, height: 400); final edge = Offset(bar.right - 2.5, bar.top + 16 + 38); expect( controller.beginDrag( viewport: viewport, position: edge, trimHitExtent: 6, ), isTrue, ); expect( controller.finishDrag(viewport: viewport, position: edge), isFalse, ); await tester.pump(); expect(controller.trimOutlineEdgeFor(handle), TimelineTrimEdge.trailing); // The bar stops 2 px before the clip edge; its pill is inset another 3 px. final position = switch (start) { 'top' => Offset(bar.right - 2.5, bar.top + 1), 'bottom' => Offset(bar.right - 2.5, bar.bottom - 1), _ => Offset(bar.right - 5.5, bar.center.dy), }; final gesture = await tester.startGesture( position, kind: ui.PointerDeviceKind.mouse, ); if (start == 'diagonal') { await gesture.moveBy(const Offset(1, 30)); await tester.pump(); expect(controller.isDragging, isFalse); expect(controller.trimOutlineEdgeFor(handle), isNull); } for (var i = 0; i < 2; i++) { await gesture.moveBy(const Offset(-30, 0)); await tester.pump(); expect(controller.isDragging, isFalse); expect(controller.trimOutlineEdgeFor(handle), isNull); expect(controller.selectedIdentities, contains(handle)); expect(kernel.current, same(before)); } final preview = controller .project(TimelineViewportRect(width: 800, height: 400)) .version .kernelVersion .query() .element(handle); expect(preview.duration, lessThan(original.duration)); expect(preview.sourceStart, original.sourceStart); expect(preview.sourceDuration, original.sourceDuration); await gesture.up(); await tester.pump(); final committed = kernel.current.query().element(handle); expect(committed.duration, preview.duration); expect(committed.sourceStart, original.sourceStart); expect(committed.sourceDuration, original.sourceDuration); expect(kernel.historyVersions.length, history + 1); expect(controller.trimOutlineEdgeFor(handle), isNull); final published = kernel.current; final updatedBar = tester.getRect( find.byKey(const ValueKey('speed-segment-0')), ); final trim = await tester.startGesture( Offset(updatedBar.right - 2.5, updatedBar.top + 16 + 38), kind: ui.PointerDeviceKind.mouse, ); await trim.moveBy(const Offset(-24, 0)); await tester.pump(); expect(controller.isTrimming, isTrue); expect(controller.dragRejection, isNull); await trim.cancel(); await tester.pump(); expect(kernel.current, same(published)); expect(kernel.historyVersions.length, history + 1); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); } testWidgets( 'speed handle keeps the background stable when crossing 100 percent', (tester) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov')), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final view = f.timeline.view(sequence); final kernel = f.timeline.persistence.timeline(sequence); final before = kernel.current; final history = kernel.historyVersions.length; f.timeline.setCustomSpeedEnabled(sequence, id, true); const boundaryKey = Key('speed-drag-background'); for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: RepaintBoundary( key: boundaryKey, child: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: view, ), ), ), ), ), ); await tester.pump(); final sample = tester.getTopLeft(find.byKey(ValueKey((sequence, id)))) + const Offset(12, 11); final color = await _surfacePixel(tester, boundaryKey, sample); final gesture = await tester.startGesture( tester.getCenter( find.byKey(const ValueKey('speed-segment-handle-0')), ), ); for (final delta in [30.0, 30.0, -60.0, -30.0, 30.0]) { await gesture.moveBy(Offset(delta, 0)); await tester.pump(); expect( await _surfacePixel(tester, boundaryKey, sample), color, reason: 'Changing speed through 100% must not toggle the background shade.', ); } await gesture.cancel(); await tester.pump(); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, history); expect(await _surfacePixel(tester, boundaryKey, sample), color); } await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }, ); testWidgets('speed sections share their clip stacking during overlaps', ( tester, ) async { final sequence = SequenceId('one'); final clipId = ElementId('clip'); final otherId = ElementId('other'); final f = (await tester.runAsync( () => createPreviewFixture( Uri.file('/test/video.mov'), timelineOverride: TimelineDto( id: sequence, format: TimelineFormat.fps30, primaryStorylineId: StorylineId('primary'), storylines: [ StorylineDto( id: StorylineId('primary'), elementIds: [clipId, otherId], ), ], elements: [ for (final id in [clipId, otherId]) ElementDto( id: id, structure: ElementStructure.content, payloadRef: PayloadRef('source'), duration: RationalTime.seconds(2), sourceRange: TimeRange( start: RationalTime.zero, duration: RationalTime.seconds(2), ), mediaRange: TimeRange( start: RationalTime.zero, duration: RationalTime.seconds(2), ), ), ], ), ), ))!; final view = f.timeline.view(sequence); final query = view.version.kernelVersion.query(); final clip = query.elementById(clipId)!; final other = query.elementById(otherId)!; f.timeline.setCustomSpeedEnabled(sequence, clipId, true); const boundaryKey = Key('speed-stacking-surface'); const mediaColor = Color(0xff2468ac); final viewport = TimelineViewportRect(width: 800, height: 400); await tester.pumpWidget( MaterialApp( theme: EditorTheme.penLight, home: Scaffold( body: RepaintBoundary( key: boundaryKey, child: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: view, theme: const TimelineThemeData.dark().copyWith( visualClipColor: mediaColor, playheadWidth: 0, ), ), ), ), ), ), ); await tester.pump(); final stationaryPoint = tester.getTopLeft(find.byKey(ValueKey((sequence, clipId)))) + const Offset(12, 11); final headerColor = await _surfacePixel( tester, boundaryKey, stationaryPoint, ); final frame = view.project(viewport); final otherIndex = List.generate( frame.length, (index) => index, ).singleWhere((index) => frame.identityAt(index) == other); final origin = view.presentationBoundsAt(frame, otherIndex).topLeft + const Offset(60, 40); view.setSelection([other]); expect(view.beginDrag(viewport: viewport, position: origin), isTrue); view.updateDrag( viewport: viewport, position: origin + const Offset(-120, -30), ); await tester.pump(); expect( await _surfacePixel(tester, boundaryKey, stationaryPoint), [36, 104, 172, 255], reason: 'A moving clip must cover the stationary clip and its speed header.', ); view.cancelDrag(); await tester.pump(); view.setSelection([clip]); final clipOrigin = tester.getTopLeft(find.byKey(ValueKey((sequence, clipId)))) + const Offset(60, 40); expect(view.beginDrag(viewport: viewport, position: clipOrigin), isTrue); view.updateDrag( viewport: viewport, position: clipOrigin + const Offset(120, 30), ); await tester.pump(); final movingPoint = tester.getTopLeft(find.byKey(ValueKey((sequence, clipId)))) + const Offset(12, 11); expect( await _surfacePixel(tester, boundaryKey, movingPoint), headerColor, reason: 'A moving speed header must stay above clips underneath its owner.', ); view.cancelDrag(); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); testWidgets( 'speed backgrounds preserve selection and drag outlines without hover frames', (tester) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov')), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final view = f.timeline.view(sequence); final handle = view.version.kernelVersion.query().elementById(id)!; f.timeline.setCustomSpeedEnabled(sequence, id, true); const boundaryKey = Key('speed-outline-surface'); const selectedColor = Color(0xffcc44aa); final outlineTheme = const TimelineThemeData.dark().copyWith( selectionOutlineColor: selectedColor, selectionOutlineWidth: 2, playheadWidth: 0, ); Future> borderPixel() async { await tester.pump(); final boundary = tester.renderObject( find.byKey(boundaryKey), ); final point = tester.getTopLeft(find.byKey(ValueKey((sequence, id)))) - tester.getTopLeft(find.byKey(boundaryKey)) + const Offset(12, 0); return (await tester.runAsync(() async { final image = await boundary.toImage(pixelRatio: 1); try { final pixels = (await image.toByteData( format: ui.ImageByteFormat.rawRgba, ))!; final offset = (point.dy.floor() * image.width + point.dx.floor()) * 4; return [for (var i = 0; i < 4; i++) pixels.getUint8(offset + i)]; } finally { image.dispose(); } }))!; } for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { view.setHoveredIdentity(null); view.setSelection([handle]); await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: RepaintBoundary( key: boundaryKey, child: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: view, theme: outlineTheme, ), ), ), ), ), ); expect(await borderPixel(), [204, 68, 170, 255]); view.clearSelection(); final idlePixel = await borderPixel(); expect(idlePixel, isNot([204, 68, 170, 255])); view.setHoveredIdentity(handle); expect(await borderPixel(), idlePixel); view.setSelection([handle]); expect(await borderPixel(), [204, 68, 170, 255]); view.setHoveredIdentity(null); final origin = tester.getTopLeft(find.byKey(ValueKey((sequence, id)))) + const Offset(60, 40); final viewport = TimelineViewportRect(width: 800, height: 400); expect(view.beginDrag(viewport: viewport, position: origin), isTrue); view.updateDrag( viewport: viewport, position: origin + const Offset(30, 20), ); expect(await borderPixel(), [204, 68, 170, 255]); view.cancelDrag(); } await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }, ); testWidgets('speed backgrounds retain their color over overlapping clips', ( tester, ) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov')), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final view = f.timeline.view(sequence); f.timeline.setCustomSpeedEnabled(sequence, id, true); const boundaryKey = Key('overlapping-speed-background'); Future> backgroundPixel(ThemeData theme, Color underneath) async { await tester.pumpWidget( MaterialApp( theme: theme, home: Scaffold( body: RepaintBoundary( key: boundaryKey, child: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: view, theme: theme.extension()!.copyWith( primaryLaneBackgroundColor: underneath, ), ), ), ), ), ), ); await tester.pump(); final boundary = tester.renderObject( find.byKey(boundaryKey), ); final point = tester.getTopLeft(find.byKey(const ValueKey('speed-segment-0'))) - tester.getTopLeft(find.byKey(boundaryKey)) + const Offset(10, 11); return (await tester.runAsync(() async { final image = await boundary.toImage(pixelRatio: 1); try { final pixels = (await image.toByteData( format: ui.ImageByteFormat.rawRgba, ))!; final offset = (point.dy.floor() * image.width + point.dx.floor()) * 4; return [for (var i = 0; i < 4; i++) pixels.getUint8(offset + i)]; } finally { image.dispose(); } }))!; } for (final theme in [EditorTheme.penLight, EditorTheme.penDark]) { for (final speed in [1.0, 2.0]) { f.timeline.setClipSpeed(sequence, id, speed); final overRed = await backgroundPixel(theme, Colors.red); final overBlue = await backgroundPixel(theme, Colors.blue); expect( overRed, overBlue, reason: 'Underlying clip colors must not bleed through speed sections.', ); } } await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); testWidgets( 'speed slider commits once, preserves source and supports undo and reset', (tester) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final kernel = f.timeline.persistence.timeline(sequence); final before = kernel.current; final history = kernel.historyVersions.length; final source = before.query().element(before.query().elementById(id)!); final view = f.timeline.view(sequence); view.setSelection([before.query().elementById(id)!]); final selection = view.selectedIdentities.toList(); // Preview and view-state consumers read the authoritative root inside // the notification, before widgets rebuild on the next frame. void observeLayout() { view.version; } view.editingChanges.addListener(observeLayout); await tester.pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 800, height: 400, child: Row( children: [ SizedBox( width: 225, child: SpeedProperties( session: f.timeline, sequence: sequence, clip: id, ), ), Expanded( child: _speedSurface( session: f.timeline, sequence: sequence, controller: view, ), ), ], ), ), ), ), ); expect(f.timeline.isCustomSpeedEnabled(sequence, id), isFalse); expect(view.geometry.primaryHeight, 88); expect( view.geometry.primaryClipHeightFor(before.query().elementById(id)!), 76, ); expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); expect( tester .widget( find.byKey(const Key('split-speed-segment')), ) .onPressed, isNull, ); await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); await tester.pumpAndSettle(); expect(f.timeline.isCustomSpeedEnabled(sequence, id), isTrue); expect(view.selectedIdentities, selection); expect(view.geometry.primaryHeight, 98); expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, history); AppSlider slider() => tester.widget(find.byKey(const Key('clip-speed-slider'))); final position = (math.log(2) / math.ln10 + 1) / 3; slider().onChangeStart!(position); slider().onChanged!(position); await tester.pump(); expect(find.text('2.00×'), findsOneWidget); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, history); final previewFrame = view.project( TimelineViewportRect(width: 800, height: 400), ); expect(previewFrame.version.kernelVersion, isNot(same(before))); final previewQuery = previewFrame.version.kernelVersion.query(); expect( previewQuery.element(previewQuery.elementById(id)!).duration, source.duration ~/ 2, ); expect( tester.getSize(find.byKey(const ValueKey('speed-segment-0'))).width, closeTo(60, 1e-6), ); expect( find.byWidgetPredicate( (widget) => widget is Semantics && widget.properties.label == '200%', ), findsOneWidget, ); await tester.runAsync(() async { slider().onChangeEnd!(position); await f.timeline.flush(); }); await tester.pumpAndSettle(); final q = kernel.current.query(); final changed = q.element(q.elementById(id)!); expect(changed.duration, source.duration ~/ 2); expect(changed.sourceStart, source.sourceStart); expect(changed.sourceDuration, source.sourceDuration); expect(view.selectedIdentities, selection); await tester.runAsync(() async { f.timeline.undo(sequence); await f.timeline.flush(); }); await tester.pumpAndSettle(); expect(kernel.current, same(before)); expect(find.text('1.00×'), findsOneWidget); await tester.runAsync(() async { for (final rate in [0.1, 100.0, 2.0]) { f.timeline.setClipSpeed(sequence, id, rate); final query = kernel.current.query(); expect( f.timeline.clipSpeed(query.element(query.elementById(id)!)), closeTo(rate, 0.001), ); } await f.timeline.flush(); }); await tester.pumpAndSettle(); await tester.runAsync(() async { await tester.tap(find.text('1×')); await tester.pump(); await f.timeline.flush(); }); await tester.pumpAndSettle(); expect(find.text('1.00×'), findsOneWidget); view.seekTo(source.duration ~/ 2); await tester.pump(); await tester.runAsync(() async { await tester.tap(find.byKey(const Key('split-speed-segment'))); await tester.pump(); await f.timeline.flush(); }); await tester.pumpAndSettle(); expect(find.text('2 个速度区间'), findsOneWidget); expect(find.byKey(const Key('clip-speed-slider')), findsNothing); final segmented = kernel.current; final segmentedHistory = kernel.historyVersions.length; await tester.tap(find.byKey(const Key('clip-custom-speed-toggle'))); await tester.pumpAndSettle(); expect(f.timeline.isCustomSpeedEnabled(sequence, id), isFalse); expect(view.selectedIdentities, selection); expect(view.geometry.primaryHeight, 88); expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); expect(kernel.current, same(segmented)); expect(kernel.historyVersions.length, segmentedHistory); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }, ); testWidgets('timeline speed handle expands the clip and commits once', ( tester, ) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final kernel = f.timeline.persistence.timeline(sequence); final controller = f.timeline.view(sequence); final handle = kernel.current.query().elementById(id)!; controller.setSelection([handle]); final before = kernel.current; final history = kernel.historyVersions.length; expect(controller.geometry.primaryHeight, 88); expect(controller.geometry.primaryLaneHeight, 88); expect(controller.geometry.primaryClipHeightFor(handle), 76); f.timeline.setCustomSpeedEnabled(sequence, id, true); expect(controller.geometry.primaryHeight, 98); expect(controller.geometry.primaryLaneHeight, 88); expect(controller.geometry.primaryLaneTop, 58); expect(controller.geometry.primaryClipTopFor(handle), 48); expect(controller.geometry.primaryClipHeightFor(handle), 92); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, history); await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: controller, ), ), ), ), ); await tester.pump(); expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); expect( tester.getSize(find.byKey(const ValueKey('speed-segment-0'))).height, 14, ); final frame = controller.project( TimelineViewportRect(width: 800, height: 400), ); final index = List.generate( frame.length, (index) => index, ).singleWhere((index) => frame.identityAt(index) == handle); final bounds = controller.presentationBoundsAt(frame, index); expect(bounds.height, 92); expect( tester.getTopLeft(find.byKey(const ValueKey('speed-segment-0'))).dy, bounds.top, ); final gesture = await tester.startGesture( tester.getCenter(find.byKey(const ValueKey('speed-segment-handle-0'))), ); await gesture.moveBy(const Offset(30, 0)); await tester.pump(); await gesture.moveBy(const Offset(30, 0)); await tester.pump(); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, history); final previewFrame = controller.project( TimelineViewportRect(width: 800, height: 400), ); expect(previewFrame.version.kernelVersion, isNot(same(before))); expect( previewFrame.version.kernelVersion.query().element(handle).duration, 3 * TimelineClock.ticksPerSecond, ); expect(controller.contentEndTick, 3 * TimelineClock.ticksPerSecond); await gesture.up(); await tester.pump(); expect(kernel.current, isNot(same(before))); expect(kernel.historyVersions.length, history + 1); expect( kernel.current.query().element(handle).duration, 3 * TimelineClock.ticksPerSecond, ); f.timeline.setCustomSpeedEnabled(sequence, id, false); await tester.pump(); expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); expect(controller.geometry.primaryHeight, 88); expect(controller.geometry.primaryLaneHeight, 88); expect(controller.geometry.primaryClipHeightFor(handle), 76); expect(controller.geometry.primaryClipTopFor(handle), 54); f.timeline.undo(sequence); await tester.pump(); expect(controller.geometry.primaryHeight, 88); expect(controller.geometry.primaryClipHeightFor(handle), 76); f.timeline.redo(sequence); await tester.pump(); expect(controller.geometry.primaryHeight, 88); expect(controller.geometry.primaryClipHeightFor(handle), 76); expect(kernel.historyVersions.length, history + 1); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); testWidgets('speed dimensions preserve other clips and connected spacing', ( tester, ) async { final duration = RationalTime.seconds(2); final fixture = TimelineDto( id: SequenceId('one'), name: 'one', format: TimelineFormat.fps30, primaryStorylineId: StorylineId('primary'), storylines: [ StorylineDto( id: StorylineId('primary'), elementIds: [ElementId('clip'), ElementId('normal')], ), ], elements: [ for (final id in ['clip', 'normal', 'above', 'below']) ElementDto( id: ElementId(id), structure: ElementStructure.content, payloadRef: PayloadRef('source'), duration: duration, sourceRange: TimeRange( start: RationalTime.zero, duration: duration, ), mediaRange: TimeRange(start: RationalTime.zero, duration: duration), ), ], connections: [ for (final side in ConnectionSide.values) ConnectionDto( id: ConnectionId(side.name), anchorId: ElementId('clip'), targetId: ElementId(side.name), anchorTime: RationalTime.zero, targetTime: RationalTime.zero, side: side, ), ], ); final f = (await tester.runAsync( () => createPreviewFixture( Uri.file('/test/video.mov'), timelineOverride: fixture, ), ))!; final sequence = SequenceId('one'); final kernel = f.timeline.persistence.timeline(sequence); final authored = kernel.current; final history = kernel.historyVersions.length; final query = authored.query(); final main = query.elementById(ElementId('clip'))!; final normal = query.elementById(ElementId('normal'))!; final above = query.elementById(ElementId('above'))!; final below = query.elementById(ElementId('below'))!; final view = f.timeline.view(sequence); final belowTop = view.version.placementOf(LayoutBodyId.element(below)).top; final aboveTop = view.version.placementOf(LayoutBodyId.element(above)).top; view.setSelection([main]); f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), true); expect(view.geometry.primaryHeight, 98); expect(view.geometry.primaryClipHeightFor(normal), 76); expect(view.geometry.primaryClipTopFor(normal), 64); expect( view.version.placementOf(LayoutBodyId.element(below)).top, belowTop + 10, ); expect(view.version.placementOf(LayoutBodyId.element(above)).top, aboveTop); await tester.pumpWidget( MaterialApp( theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: view, ), ), ), ), ); view.setCamera(view.camera.panBy(verticalPixels: -100)); view.clearSelection(); await tester.pump(); expect(view.geometry.primaryHeight, 98); expect(view.geometry.primaryClipHeightFor(main), 92); expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); // Every enabled clip retains its own header, independently of selection. view.setSelection([above]); f.timeline.setCustomSpeedEnabled(sequence, ElementId('above'), true); await tester.pump(); expect(view.geometry.primaryHeight, 98); expect( f.timeline.isCustomSpeedEnabled(sequence, ElementId('clip')), isTrue, ); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); final body = view.version.scene.bodies[LayoutBodyId.element(above)]!; expect(body.height, 92); expect(view.version.placementOf(body.id).top, aboveTop - 16); expect( view.version.placementOf(LayoutBodyId.element(below)).top, belowTop + 10, ); view.setSelection([normal]); await tester.pump(); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); f.timeline.setCustomSpeedEnabled(sequence, ElementId('normal'), true); await tester.pump(); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(3)); f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), false); await tester.pump(); expect(view.geometry.primaryHeight, 98); expect(view.geometry.primaryClipHeightFor(main), 76); expect(view.geometry.primaryClipHeightFor(normal), 92); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), true); f.timeline.setCustomSpeedEnabled(sequence, ElementId('normal'), false); await tester.pump(); expect(view.geometry.primaryClipHeightFor(normal), 76); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); f.timeline.selectSequence(SequenceId('empty')); f.timeline.selectSequence(sequence); await tester.pump(); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); final dragViewport = TimelineViewportRect(width: 800, height: 400); Future checkClipDrag(ElementHandle source) async { final frame = view.project(dragViewport); final index = List.generate(frame.length, (index) => index).singleWhere( (index) => view.elementForIdentity(frame.identityAt(index)) == source, ); final sourceBounds = view.presentationBoundsAt(frame, index); final origin = Offset(sourceBounds.left + 60, sourceBounds.top + 40); expect(view.beginDrag(viewport: dragViewport, position: origin), isTrue); for (final delta in [const Offset(30, 20), const Offset(120, -20)]) { view.updateDrag(viewport: dragViewport, position: origin + delta); await tester.pump(); expect(view.dragGhosts, isNotEmpty); for (final ghost in view.dragGhosts) { final record = query.element(ghost.body.id.owner); if (!f.timeline.isCustomSpeedEnabled(sequence, record.id)) continue; final expected = Offset( view.camera.screenXForTick(ghost.body.start, dragViewport), view.camera.screenYForWorld(ghost.top.toDouble(), dragViewport), ); expect( tester.getTopLeft(find.byKey(ValueKey((sequence, record.id)))), expected, reason: 'The speed header must follow its moving clip, including carried clips.', ); } } view.cancelDrag(); await tester.pump(); expect(kernel.current, same(authored)); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); } await checkClipDrag(main); await checkClipDrag(above); view.setSelection([normal]); await tester.pump(); // Unselected clips remain editable, and each bar edits its own clip. final aboveBar = find.descendant( of: find.byKey(ValueKey((sequence, ElementId('above')))), matching: find.byKey(const ValueKey('speed-segment-handle-0')), ); final drag = await tester.startGesture(tester.getCenter(aboveBar)); await drag.moveBy(const Offset(30, 0)); await tester.pump(); await drag.moveBy(const Offset(30, 0)); await tester.pump(); await drag.up(); await tester.pump(); expect( kernel.current.query().element(above).duration, greaterThan(query.element(above).duration), ); expect( kernel.current.query().element(main).duration, query.element(main).duration, ); expect( kernel.current.query().element(normal).duration, query.element(normal).duration, ); expect(view.selectedIdentities, [normal]); f.timeline.undo(sequence); await tester.pump(); expect(kernel.current, same(authored)); expect(find.byKey(const ValueKey('speed-segment-0')), findsNWidgets(2)); f.timeline.setCustomSpeedEnabled(sequence, ElementId('clip'), false); await tester.pump(); expect(view.geometry.primaryHeight, 88); expect(view.geometry.primaryClipHeightFor(main), 76); expect( f.timeline.isCustomSpeedEnabled(sequence, ElementId('above')), isTrue, ); expect(find.byKey(const ValueKey('speed-segment-0')), findsOneWidget); expect(view.version.scene.bodies[LayoutBodyId.element(above)]!.height, 92); expect(view.version.placementOf(LayoutBodyId.element(below)).top, belowTop); expect(kernel.current, same(authored)); expect(kernel.historyVersions.length, history + 1); f.timeline.setClipSpeed(sequence, ElementId('above'), 2); f.timeline.setClipSpeed(sequence, ElementId('above'), 1); f.timeline.setCustomSpeedEnabled(sequence, ElementId('above'), false); for (final move in [ f.timeline.undo, f.timeline.undo, f.timeline.redo, f.timeline.redo, ]) { move(sequence); expect(view.geometry.primaryHeight, 88); expect( view.version.scene.bodies[LayoutBodyId.element(above)]!.height, 76, ); } expect(kernel.historyVersions.length, history + 2); await tester.pump(); expect(find.byKey(const ValueKey('speed-segment-0')), findsNothing); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); testWidgets('speed handle cancels when the authored version changes', ( tester, ) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final kernel = f.timeline.persistence.timeline(sequence); final controller = f.timeline.view(sequence); final handle = kernel.current.query().elementById(id)!; controller.setSelection([handle]); f.timeline.setCustomSpeedEnabled(sequence, id, true); final history = kernel.historyVersions.length; await tester.pumpWidget( MaterialApp( home: Scaffold( body: SizedBox( width: 800, height: 400, child: _speedSurface( session: f.timeline, sequence: sequence, controller: controller, ), ), ), ), ); await tester.pump(); final gesture = await tester.startGesture( tester.getCenter(find.byKey(const ValueKey('speed-segment-handle-0'))), ); await gesture.moveBy(const Offset(30, 0)); await tester.pump(); expect( controller .project(TimelineViewportRect(width: 800, height: 400)) .version .kernelVersion, isNot(same(kernel.current)), ); f.timeline.setClipSpeed(sequence, id, 1.5); final externallyChanged = kernel.current; await tester.pump(); await gesture.moveBy(const Offset(30, 0)); await tester.pump(); expect( controller .project(TimelineViewportRect(width: 800, height: 400)) .version .kernelVersion, same(externallyChanged), ); await gesture.up(); await tester.pump(); expect(kernel.current, same(externallyChanged)); expect(kernel.historyVersions.length, history + 1); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); testWidgets('speed slider cancels when the authored version changes', ( tester, ) async { final f = (await tester.runAsync( () => createPreviewFixture(Uri.file('/test/video.mov'), hasAudio: true), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final kernel = f.timeline.persistence.timeline(sequence); final controller = f.timeline.view(sequence); final history = kernel.historyVersions.length; await tester.pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 225, child: SpeedProperties( session: f.timeline, sequence: sequence, clip: id, ), ), ), ), ); AppSlider slider() => tester.widget(find.byKey(const Key('clip-speed-slider'))); final speed2 = (math.log(2) / math.ln10 + 1) / 3; final speed3 = (math.log(3) / math.ln10 + 1) / 3; slider().onChangeStart!(speed2); slider().onChanged!(speed2); await tester.pump(); f.timeline.setClipSpeed(sequence, id, 1.5); final externallyChanged = kernel.current; await tester.pump(); slider().onChanged!(speed3); await tester.pump(); expect( controller .project(TimelineViewportRect(width: 800, height: 400)) .version .kernelVersion, same(externallyChanged), ); slider().onChangeEnd!(speed3); await tester.pump(); expect(kernel.current, same(externallyChanged)); expect(kernel.historyVersions.length, history + 1); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); testWidgets('audio speed previews and commits through the shared path', ( tester, ) async { final f = (await tester.runAsync( () => createPreviewFixture( Uri.file('/test/audio.wav'), mediaType: 'audio', hasAudio: true, ), ))!; final sequence = SequenceId('one'); final id = ElementId('clip'); final kernel = f.timeline.persistence.timeline(sequence); final before = kernel.current; final history = kernel.historyVersions.length; final controller = f.timeline.view(sequence); final handle = before.query().elementById(id)!; controller.setSelection([handle]); f.timeline.setCustomSpeedEnabled(sequence, id, true); await tester.pumpWidget( MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penLight, home: Scaffold( body: SizedBox( width: 800, height: 400, child: Row( children: [ SizedBox( width: 225, child: SpeedProperties( session: f.timeline, sequence: sequence, clip: id, ), ), Expanded( child: _speedSurface( session: f.timeline, sequence: sequence, controller: controller, ), ), ], ), ), ), ), ); final slider = tester.widget( find.byKey(const Key('clip-speed-slider')), ); final speed2 = (math.log(2) / math.ln10 + 1) / 3; slider.onChangeStart!(speed2); slider.onChanged!(speed2); await tester.pump(); expect(kernel.current, same(before)); expect(kernel.historyVersions.length, history); final preview = controller .project(TimelineViewportRect(width: 575, height: 400)) .version .kernelVersion .query(); final previewRecord = preview.element(preview.elementById(id)!); expect(previewRecord.duration, TimelineClock.ticksPerSecond); expect(previewRecord.sourceDuration, 2 * TimelineClock.ticksPerSecond); expect(f.timeline.payloadFor(previewRecord.payloadRef!)!.type, 'audio'); expect( find.byWidgetPredicate( (widget) => widget is Semantics && widget.properties.label == '200%', ), findsOneWidget, ); slider.onChangeEnd!(speed2); await tester.pump(); expect(kernel.historyVersions.length, history + 1); expect( kernel.current.query().element(handle).duration, TimelineClock.ticksPerSecond, ); await tester.pumpWidget(const SizedBox.shrink()); await tester.runAsync(() async { await f.workspace.close(); await f.directory.delete(recursive: true); }); }); } Widget _speedSurface({ required EditorTimelineSession session, required SequenceId sequence, required TimelineViewController controller, TimelineThemeData? theme, }) => Builder( builder: (context) => TimelineView( controller: controller, theme: theme, paintClipHeader: TimelineSpeedEditor.headerPainter( context, session: session, sequence: sequence, ), overlay: TimelineSpeedEditor( session: session, sequence: sequence, controller: controller, ), ), ); Future> _surfacePixel( WidgetTester tester, Key boundaryKey, Offset position, ) async { final boundary = tester.renderObject( find.byKey(boundaryKey), ); final point = position - tester.getTopLeft(find.byKey(boundaryKey)); return (await tester.runAsync(() async { final image = await boundary.toImage(pixelRatio: 1); try { final pixels = (await image.toByteData( format: ui.ImageByteFormat.rawRgba, ))!; final offset = (point.dy.floor() * image.width + point.dx.floor()) * 4; return [for (var i = 0; i < 4; i++) pixels.getUint8(offset + i)]; } finally { image.dispose(); } }))!; }