import 'dart:async'; import 'dart:io'; import 'package:cutdex/features/timeline/timeline_panel.dart'; import 'package:cutdex/features/editor/editor_page.dart'; import 'package:cutdex/app/editor_theme.dart'; import 'package:cutdex/integrations/platform/device_experience.dart'; import 'package:cutdex/l10n/app_localizations.dart'; import 'package:cutdex/persistence/app_settings_repositories.dart'; import 'package:cutdex/workspace/preview_target.dart'; import 'package:cutdex/workspace/project_state.dart'; import 'package:cutdex/workspace/projects.dart'; import 'package:cutdex/workspace/timeline_provider.dart'; import 'package:cutdex/workspace/persistence/recent_projects.dart'; import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:cutdex_sdk/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 '../support/memory_app_settings.dart'; void main() { TestWidgetsFlutterBinding.ensureInitialized(); late Directory root; late ProviderContainer container; late Projects projects; late String projectId; late _ViewSettings views; late _RecentProjects recent; final nativeCalls = []; const native = MethodChannel('timeline-navigation-test'); Future initialize() async { root = await Directory.systemTemp.createTemp('cutdex-navigation-'); views = _ViewSettings(); recent = _RecentProjects(); nativeCalls.clear(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(native, (call) async { nativeCalls.add(call.method); throw StateError('Preview must not be initialized by navigation'); }); final path = '${root.path}/Project.cutdex'; final file = await ProjectFile.create( Directory(path), name: 'Project', initialTimeline: _document('a'), ); projectId = file.info.id; await file.saveTimeline(_document('b', content: true)); await file.saveTimeline(_document('c')); await file.close(); container = ProviderContainer( overrides: [ deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), recentProjectsProvider.overrideWithValue(recent), resourceLocationSettingsRepositoryProvider.overrideWithValue( MemoryResourceLocationSettingsRepository(root.path), ), timelineViewSettingsRepositoryProvider.overrideWithValue(views), runtimeConnectionProvider.overrideWithValue( CutdexRuntime(channel: native), ), ], ); projects = container.read(projectsProvider.notifier); expect(await projects.open(path, timelineId: 'a'), isTrue); } Future dispose() async { for (final gate in views.gates.values) { if (!gate.isCompleted) gate.complete(const TimelineViewState()); } if (recent.writeGate case final gate?) { if (!gate.isCompleted) gate.complete(); } await projects.prepareToQuit(); container.dispose(); TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger .setMockMethodCallHandler(native, null); await root.delete(recursive: true); } group('navigation controller', () { setUp(initialize); tearDown(dispose); test( 'content selection completes without any native preview initialization', () async { expect(await projects.openTimeline(projectId, 'b'), isTrue); expect(container.read(projectsProvider).requireValue.timeline!.id, 'b'); expect(nativeCalls, isEmpty); }, ); test( 'latest cold navigation wins despite reverse completion order', () async { final bGate = views.block('b'); final b = projects.openTimeline(projectId, 'b'); expect( container.read(projectsProvider).requireValue.visibleTimelineId, 'b', ); await views.started('b'); expect(projects.openTimeline(projectId, 'b'), same(b)); final cGate = views.block('c'); final c = projects.openTimeline(projectId, 'c'); expect( container.read(projectsProvider).requireValue.visibleTimelineId, 'c', ); await views.started('c'); cGate.complete(const TimelineViewState()); expect(await c, isTrue); bGate.complete(const TimelineViewState()); expect(await b, isFalse); final state = container.read(projectsProvider).requireValue; expect(state.timeline!.id, 'c'); expect(state.openingTimelineId, isNull); expect(state.error, isNull); expect(recent.projects[projectId], 'c'); }, ); test( 'returning to a partially prepared cache waits for one restore', () async { final gate = views.block('b'); final old = projects.openTimeline(projectId, 'b'); await views.started('b'); expect(await projects.openTimeline(projectId, 'a'), isTrue); final latest = projects.openTimeline(projectId, 'b'); await Future.delayed(Duration.zero); expect( container.read(projectsProvider).requireValue.openingTimelineId, 'b', ); expect(container.read(projectsProvider).requireValue.timeline!.id, 'a'); gate.complete(const TimelineViewState()); expect(await old, isFalse); expect(await latest, isTrue); expect(views.loads.where((id) => id == 'b'), hasLength(1)); expect(container.read(projectsProvider).requireValue.timeline!.id, 'b'); }, ); test('project navigation supersedes a blocked timeline', () async { final gate = views.block('b'); final old = projects.openTimeline(projectId, 'b'); await views.started('b'); expect( await projects.open('${root.path}/Other.cutdex', name: 'Other'), isTrue, ); final other = container .read(projectsProvider) .requireValue .activeProject! .id; gate.complete(const TimelineViewState()); expect(await old, isFalse); expect( container.read(projectsProvider).requireValue.activeProject!.id, other, ); expect( container.read(projectsProvider).requireValue.openingTimelineId, isNull, ); }); test( 'slow failed preference write cannot overwrite latest selection or error', () async { recent.writeGate = Completer(); recent.blockId = 'b'; final b = projects.openTimeline(projectId, 'b'); await recent.writeStarted.future; final c = projects.openTimeline(projectId, 'c'); await views.started('c'); await Future.delayed(const Duration(milliseconds: 10)); expect(container.read(projectsProvider).requireValue.timeline!.id, 'c'); recent.writeGate!.completeError(StateError('old write failed')); expect(await b, isTrue); expect(await c, isTrue); expect(recent.projects[projectId], 'c'); expect(container.read(projectsProvider).requireValue.error, isNull); }, ); }); test( 'startup failure is returned once without an unhandled cleanup future', () async { final failedContainer = ProviderContainer( overrides: [projectsProvider.overrideWith(_FailingProjects.new)], ); addTearDown(failedContainer.dispose); final failed = failedContainer.read(projectsProvider.notifier); await expectLater(failed.openTimeline('project', 'a'), throwsA(anything)); await Future.delayed(Duration.zero); }, ); testWidgets('pending tabs accept a newer real click', (tester) async { final widgetContainer = ProviderContainer( overrides: [projectsProvider.overrideWith(_PendingProjects.new)], ); addTearDown(widgetContainer.dispose); await tester.pumpWidget( UncontrolledProviderScope( container: widgetContainer, child: MaterialApp( theme: EditorTheme.penDark, localizationsDelegates: AppLocalizations.localizationsDelegates, supportedLocales: AppLocalizations.supportedLocales, home: Scaffold( body: Consumer( builder: (context, ref, _) { final state = ref.watch(projectsProvider).value; if (state == null) return const SizedBox(); return EditorWorkspace( projectId: 'project', timelineId: state.visibleTimelineId!, projectName: 'Project', integratedTitlebar: false, headerLeading: const SizedBox(), timelineLoading: true, ); }, ), ), ), ), ); await tester.pump(); expect(find.byKey(const Key('timeline-pending')), findsOneWidget); expect( widgetContainer.exists(editorTimelineProvider('project', 'b')), isFalse, ); final panel = tester.widget( find.byType(EditorTimelinePanel), ); expect(panel.timelineId, 'b'); await tester.tap(find.byKey(const ValueKey('timeline-tab-c'))); await tester.pump(); expect( widgetContainer.read(projectsProvider).requireValue.visibleTimelineId, 'c', ); expect( tester .widget(find.byType(EditorTimelinePanel)) .timelineId, 'c', ); await tester.pumpWidget(const SizedBox()); }); } TimelineDocument _document(String id, {bool content = false}) => TimelineDocument( id: id, name: id, defaultSequenceId: SequenceId('sequence-$id'), sequences: [ TimelineDto( id: SequenceId('sequence-$id'), name: id, format: TimelineFormat.fps30, primaryStorylineId: StorylineId('primary-$id'), storylines: [ StorylineDto( id: StorylineId('primary-$id'), elementIds: [if (content) ElementId('clip')], ), ], elements: [ if (content) ElementDto( id: ElementId('clip'), name: 'Clip', structure: ElementStructure.content, payloadRef: PayloadRef('source'), duration: RationalTime.seconds(2), sourceRange: TimeRange( start: RationalTime.zero, duration: RationalTime.seconds(2), ), ), ], ), ], payloads: [ if (content) PayloadDocument(id: 'source', type: 'video', assetIds: [], data: {}), ], ); class _ViewSettings implements TimelineViewSettingsRepository { final gates = >{}; final signals = >{}; final loads = []; Completer block(String id) => gates[id] = Completer(); Future started(String id) => (signals[id] ??= Completer()).future; @override Future load(String projectId, String timelineId) async { loads.add(timelineId); (signals[timelineId] ??= Completer()).complete(); return gates[timelineId]?.future ?? const TimelineViewState(); } @override Future save( String projectId, String timelineId, SequenceId sequenceId, TimelineSequenceViewState state, ) async {} } class _RecentProjects extends MemoryRecentProjectsRepository { Completer? writeGate; final writeStarted = Completer(); String? blockId; @override Future rememberTimeline(String projectId, String timelineId) async { if (timelineId == blockId) { writeStarted.complete(); await writeGate!.future; } await super.rememberTimeline(projectId, timelineId); } } class _PendingProjects extends Projects { @override Future build() async => ProjectState( activeProject: const RecentProject( id: 'project', name: 'Project', path: '/Project.cutdex', ), timeline: _document('a'), openingTimelineId: 'b', timelines: const [ TimelineSummary(id: 'a', name: 'a', revision: 0), TimelineSummary(id: 'b', name: 'b', revision: 0), TimelineSummary(id: 'c', name: 'c', revision: 0), ], ); @override Future openTimeline(String projectId, String timelineId) async { state = AsyncData( state.requireValue.copyWith(openingTimelineId: timelineId), ); return true; } } class _FailingProjects extends Projects { @override Future build() async => throw StateError('startup failed'); }