import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/l10n/app_localizations.dart'; import 'dart:convert'; import 'dart:io'; import 'package:cutdex/workspace/timeline_provider.dart'; import 'dart:math' as math; import 'package:cutdex_preview/cutdex_preview.dart'; import 'package:cutdex/features/preview/preview_panel.dart'; import 'package:cutdex/features/properties/properties_panel.dart'; import 'package:cutdex_native_flutter/cutdex_native_flutter.dart'; import 'package:cutdex_core/timeline/model.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:integration_test/integration_test.dart'; import '../test/support/preview_fixture.dart'; import 'support/native_media_fixture.dart'; void main() { IntegrationTestWidgetsFlutterBinding.ensureInitialized(); testWidgets('measure repeated real-media canvas drags', (tester) async { final channel = _TimingChannel(); final mediaFile = await nativeMediaFixture(); final fixture = await createPreviewFixture( mediaFile.uri, renderSize: {'width': 1920, 'height': 1440}, ); final preview = PreviewController( timeline: fixture.timeline, activeSequence: () => fixture.timeline.activeSequenceId, viewForSequence: fixture.timeline.view, runtime: CutdexRuntime(channel: channel), ); addTearDown(() async { await preview.close(); await fixture.workspace.close(); await fixture.directory.delete(recursive: true); }); await preview.initialize(); expect(preview.error, isNull); final ids = (fixture.workspace.project!.info.id, 'project'); await tester.pumpWidget( ProviderScope( overrides: [ editorTimelineProvider( ids.$1, ids.$2, ).overrideWith((ref) async => fixture.timeline), editorPreviewProvider( ids.$1, ids.$2, ).overrideWith((ref) async => preview), ], child: MaterialApp( localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, locale: const Locale('zh'), theme: EditorTheme.penDark, home: Scaffold( body: Row( children: [ Expanded( child: EditorPreviewPanel( projectId: ids.$1, timelineId: ids.$2, ), ), SizedBox( width: 280, child: EditorPropertiesPanel( projectId: ids.$1, timelineId: ids.$2, ), ), ], ), ), ), ), ); await tester.pumpAndSettle(); await Future.delayed(const Duration(seconds: 1)); await tester.pump(); final canvas = tester.getRect(find.byKey(const Key('preview-canvas'))); final screenScale = canvas.width / preview.canvas.width; preview.selectVisual(ElementId('clip')); await tester.pump(); await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); final samples = []; final records = >[]; final clock = Stopwatch()..start(); // Identical inputs before/after. Option excludes snap acquisition/release. for (var run = 0; run < 3; run++) { final visual = preview.visuals.single; final origin = canvas.topLeft + visual.geometry.center * screenScale; final gesture = await tester.startGesture(origin); for (var i = 1; i <= 120; i++) { final dx = 100 * math.sin(i * 2 * math.pi / 120); final dy = 30 * math.sin(i * 4 * math.pi / 120); await gesture.moveTo(origin + Offset(dx, dy)); await tester.pump(); final paint = tester.widget( find.descendant( of: find.byType(PreviewInteractionOverlay), matching: find.byType(CustomPaint), ), ); final geometry = (paint.painter as dynamic).geometry as PreviewGeometry?; if (geometry != null) { final shownX = geometry.center.dx / preview.canvas.width - .5; final error = (shownX - channel.completedX).abs() * canvas.width; samples.add(error); records.add({ 'ms': clock.elapsedMicroseconds / 1000, 'boxX': shownX, 'nativeX': channel.completedX, 'gapPx': error, }); } await Future.delayed(const Duration(milliseconds: 8)); } await gesture.up(); await preview.transforms.settled; await Future.delayed(const Duration(milliseconds: 150)); await tester.pump(); expect(preview.error, isNull); } await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); samples.sort(); channel.latency.sort(); double percentile(List values, double p) => values[((values.length - 1) * p).round()]; final result = { 'samples': samples.length, 'updates': channel.latency.length, 'gapMeasurement': 'callbackGeometry', 'gapP50Px': percentile(samples, .5), 'gapP95Px': percentile(samples, .95), 'gapMaxPx': samples.last, 'nativeP50Ms': percentile(channel.latency, .5), 'nativeP95Ms': percentile(channel.latency, .95), 'nativeMaxMs': channel.latency.last, 'canvasWidth': canvas.width, 'records': records, }; debugPrint('DRAG_TIMING ${jsonEncode({...result}..remove('records'))}'); const report = String.fromEnvironment('CUTDEX_TEST_REPORT'); if (report.isNotEmpty) await File(report).writeAsString(jsonEncode(result)); expect(samples.length, 360); expect(channel.latency.length, greaterThan(0)); expect( samples.last, lessThan(1), reason: 'Selection must follow the acknowledged native snapshot', ); expect(tester.takeException(), isNull); await tester.pumpWidget(const SizedBox()); }, skip: !hasNativeMediaFixture); } class _TimingChannel extends MethodChannel { _TimingChannel() : super('cutdex_runtime'); double completedX = 0; final latency = []; @override Future invokeMethod(String method, [dynamic arguments]) async { final request = method == 'request' ? jsonDecode(arguments['request'] as String) as Map : arguments as Map; final update = method == 'updateInteractiveTransform' || request['method'] == 'updateInteractiveTransform'; final watch = Stopwatch()..start(); final response = await super.invokeMethod(method, arguments); if (update) { latency.add(watch.elapsedMicroseconds / 1000); final transforms = request['transforms'] as List; if (transforms.isNotEmpty) { completedX = (transforms.first['x'] as num).toDouble(); } } return response; } }