import 'package:cutdex/errors/app_failure.dart'; import 'dart:async'; import 'dart:io'; import 'dart:ui' show PlatformDispatcher; import '../diagnostics/app_diagnostics.dart'; import 'package:flutter/services.dart'; import 'package:path/path.dart' as p; import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:cutdex_sdk/timeline/model.dart'; import 'package:riverpod_annotation/riverpod_annotation.dart'; import '../features/settings/language_settings.dart'; import '../l10n/app_localizations.dart'; import '../integrations/app_failure_adapter.dart'; import 'project_state.dart'; import 'media_import.dart'; import 'timeline_session.dart'; import 'background_task_registry.dart'; import 'timeline_view_state.dart'; import 'preview_controller_registry.dart'; import 'package:cutdex_sdk/editor.dart'; import '../integrations/runtime/processing_configuration.dart'; import 'persistence/project_workspace.dart'; import 'persistence/timeline_creation_names.dart'; import 'persistence/project_locator.dart'; import 'persistence/recent_projects.dart'; import 'persistence/project_location_directory.dart'; import '../persistence/app_settings_repositories.dart'; part 'projects.g.dart'; @Riverpod(keepAlive: true) class Projects extends _$Projects { static const maxTimelineCount = 50; late ProjectWorkspace _workspace; bool _workspaceReady = false; AppLocalizations get _localizations { final configured = ref.read(languageSettingsProvider).asData?.value; final locale = configured?.locale ?? resolveAppLocale( PlatformDispatcher.instance.locales, AppLocalizations.supportedLocales, ); return lookupAppLocalizations(locale); } TimelineCreationNames _creationNames([String? timelineName]) { final l10n = _localizations; return TimelineCreationNames( timeline: timelineName ?? l10n.defaultTimelineName(1), sequence: l10n.primarySequence, storyline: l10n.primaryStoryline, ); } EditorTimelineSession? cachedTimelineSession( String projectId, String timelineId, ) { if (!_workspaceReady || state.value?.activeProject?.id != projectId) { return null; } return _workspace.cachedTimelineSession(projectId, timelineId); } Future withAssetMedia( String? projectId, AssetDocument asset, Future Function(MediaReference media) action, ) async { await future; if (projectId == null) throw AppException(AppErrorCode.openProjectFirst); return _workspace.withAssetMedia(projectId, asset, action); } @override Future build() async { try { await ref.read(languageSettingsProvider.future); } catch (error, stackTrace) { AppDiagnostics.failure('project', 'loadLanguage', error, stackTrace); } String? resources; try { resources = await ref .read(resourceLocationSettingsRepositoryProvider) .load(); } catch (error, stackTrace) { AppDiagnostics.failure( 'project', 'loadResourceLocation', error, stackTrace, ); } final workspace = ProjectWorkspace( creationNames: _creationNames(), processing: ProcessingConfiguration.configured( diagnostics: AppDiagnostics.report, resourcesRoot: resources, ), backgroundTasks: ref.read(backgroundTaskRegistryProvider), ); _workspace = workspace; _workspaceReady = true; ref.onDispose(() => unawaited(workspace.close())); final assetSubscription = workspace.assetChanges.listen((event) { final current = state.value; if (ref.mounted && current?.activeProject?.id == event.projectId) { state = AsyncData(current!.copyWith(assets: event.assets)); } }); ref.onDispose(() => unawaited(assetSubscription.cancel())); try { final repository = ref.read(recentProjectsProvider); final recent = await repository.load(); final locations = await Future.wait([ for (final project in recent) ref.read(projectLocatorProvider).locate(project), ]); final resolved = [for (final location in locations) location.project]; return ProjectState(recent: resolved); } catch (error, stackTrace) { AppDiagnostics.failure( 'project', 'loadRecentProjects', error, stackTrace, ); return const ProjectState( error: AppFailure(AppErrorCode.loadRecentProjectsFailed), ); } } /// Freeze workspace commands before closing; failed saves leave it recoverable. Future prepareToQuit() async { await future; final current = state.requireValue; if (current.projectBusy || current.creatingTimeline || current.openingTimelineId != null || _workspace.hasBackgroundTasks) { throw PlatformException(code: 'workspaceBusy'); } state = AsyncData(state.requireValue.copyWith(projectBusy: true)); try { await _workspace.close(); await AppDiagnostics.instance?.store.flush(); return true; } catch (error, stack) { AppDiagnostics.failure('project', 'close', error, stack); state = AsyncData(state.requireValue.copyWith(projectBusy: false)); throw PlatformException(code: 'saveFailed'); } } Future _perform(Future Function() action) async { await future; if (!ref.mounted || state.requireValue.projectBusy) return false; state = AsyncData( state.requireValue.copyWith(projectBusy: true, error: null), ); try { await action(); return true; } on ProjectOpenSuperseded { return false; } catch (error, stackTrace) { AppDiagnostics.failure('project', 'operation', error, stackTrace); if (ref.mounted) { final failure = projectFailureFromError(error); state = AsyncData(state.requireValue.copyWith(error: failure)); } return false; } finally { if (ref.mounted) { state = AsyncData(state.requireValue.copyWith(projectBusy: false)); } } } Future open( String path, { String? name, String? expectedId, String? timelineId, String? initialTimelineName, bool Function()? isCurrent, }) => _perform(() async { final previous = state.requireValue; var published = false; void checkCurrent() { if (!ref.mounted || isCurrent?.call() == false) { throw ProjectOpenSuperseded(); } } try { checkCurrent(); final timelines = await _workspace.open( path, name: name, expectedId: expectedId, creationNames: _creationNames(initialTimelineName), isCurrent: isCurrent, ); checkCurrent(); final file = _workspace.project!; final assets = await _workspace.listAssets(file.info.id); checkCurrent(); final active = RecentProject( id: file.info.id, name: file.info.name, path: file.directory.path, availability: ProjectAvailability.available, ); final previousRecent = state.requireValue.recent; final existingIndex = previousRecent.indexWhere( (item) => item.id == active.id || item.path == active.path, ); final recent = [ if (existingIndex == -1) active, for (final (index, item) in previousRecent.indexed) if (index == existingIndex) active else if (item.id != active.id && item.path != active.path) item, ].take(20).toList(); TimelineDocument? selectedDocument; if (timelines.isNotEmpty) { var selectedId = timelineId; if (selectedId == null) { try { selectedId = await ref .read(recentProjectsProvider) .lastTimeline(active.id); } catch (_) { // App settings storage must not block opening the project. } } final selected = timelines .where((timeline) => timeline.id == selectedId) .firstOrNull ?? (timelineId == null ? timelines.first : null); if (timelineId != null && selected == null) { throw AppException(AppErrorCode.timelineMissing); } if (selected != null) { selectedDocument = await _workspace.loadTimeline( active.id, selected.id, ); } } checkCurrent(); if (selectedDocument != null) { await _prepareTimeline( active.id, selectedDocument, preparePreview: false, ); } checkCurrent(); await ref .read(previewControllerRegistryProvider) .retainProject(active.id, keep: _workspace.cachedProjectIds); checkCurrent(); state = AsyncData( state.requireValue.copyWith( activeProject: active, recent: recent, timelines: timelines, assets: assets, timeline: selectedDocument, ), ); published = true; if (selectedDocument != null) { await _rememberTimeline(active.id, selectedDocument.id); } try { await ref.read(recentProjectsProvider).save(recent); } catch (_) { if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( error: const AppFailure(AppErrorCode.recentProjectSaveFailed), ), ); } } } catch (_) { checkCurrent(); rethrow; } finally { final old = previous.activeProject; if (!published && ref.mounted && old != null && _workspace.project?.info.id != old.id) { await _workspace.open(old.path, expectedId: old.id); if (previous.timeline != null) { await _prepareTimeline(old.id, previous.timeline!); } await ref .read(previewControllerRegistryProvider) .retainProject(old.id, keep: _workspace.cachedProjectIds); } } }); Future createProject( String name, { required String initialTimelineName, }) async { final value = name.trim(); if (value.isEmpty || RegExp(r'[/\\\x00-\x1F]').hasMatch(value) || const {'.', '..'}.contains(value)) { await future; if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( error: const AppFailure(AppErrorCode.projectNameInvalid), ), ); } return false; } String? root; try { root = await ref.read(projectLocationSettingsRepositoryProvider).load(); } on ProjectLocationUnavailableException { await future; if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( error: const AppFailure( AppErrorCode.projectLocationDefaultUnavailable, ), ), ); } return false; } if (root == null || root.trim().isEmpty) { await future; if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( error: const AppFailure(AppErrorCode.chooseProjectLocation), ), ); } return false; } try { await const ProjectLocationDirectory().prepare(root); } on StateError catch (error) { await future; if (ref.mounted) { state = AsyncData( state.requireValue.copyWith(error: projectFailureFromError(error)), ); } return false; } return open( p.join(root, '$value.cutdex'), name: value, initialTimelineName: initialTimelineName, ); } Future> listProjectTimelines( RecentProject project, ) async { await future; return _workspace.listProjectTimelines( project.path, expectedId: project.id, ); } Future removeRecentProject(String projectId) => _perform(() async { final recent = state.requireValue.recent .where((project) => project.id != projectId) .toList(); await ref.read(recentProjectsProvider).save(recent); if (!ref.mounted) return; state = AsyncData(state.requireValue.copyWith(recent: recent)); }); Future restoreRecentProject(RecentProject project, int index) => _perform(() async { final recent = [...state.requireValue.recent]; if (recent.any((item) => item.id == project.id)) return; recent.insert(index.clamp(0, recent.length), project); await ref.read(recentProjectsProvider).save(recent); if (!ref.mounted) return; state = AsyncData(state.requireValue.copyWith(recent: recent)); }); Future renameProject(RecentProject project, String name) => _perform(() async { final value = name.trim(); await _workspace.renameProject(project, value); if (!ref.mounted) return; final current = state.requireValue; final renamed = project.copyWith(name: value); final recent = [ for (final item in current.recent) if (item.id == project.id) renamed else item, ]; state = AsyncData( current.copyWith( recent: recent, activeProject: current.activeProject?.id == project.id ? current.activeProject!.copyWith(name: value) : current.activeProject, ), ); await ref.read(recentProjectsProvider).save(recent); }); Future renameTimeline( RecentProject project, String timelineId, String name, ) => _perform(() async { final value = name.trim(); await _workspace.renameTimeline(project, timelineId, value); if (!ref.mounted || state.requireValue.activeProject?.id != project.id) { return; } final current = state.requireValue; state = AsyncData( current.copyWith( timelines: [ for (final timeline in current.timelines) if (timeline.id == timelineId) TimelineSummary( id: timeline.id, name: value, revision: timeline.revision, pinned: timeline.pinned, ) else timeline, ], timeline: current.timeline?.id == timelineId ? TimelineDocument( id: current.timeline!.id, name: value, sequences: current.timeline!.sequences, defaultSequenceId: current.timeline!.defaultSequenceId, payloads: current.timeline!.payloads, settings: current.timeline!.settings, revision: current.timeline!.revision, ) : current.timeline, ), ); }); Future setTimelinePinned(String timelineId, bool pinned) => _perform(() async { final current = state.requireValue; final project = current.activeProject; if (project == null) throw AppException(AppErrorCode.openProjectFirst); final timelines = await _workspace.setTimelinePinned( project, timelineId, pinned, ); if (ref.mounted && state.requireValue.activeProject?.id == project.id) { state = AsyncData(state.requireValue.copyWith(timelines: timelines)); } }); Future deleteTimeline(String timelineId) => _perform(() async { final current = state.requireValue; final project = current.activeProject; if (project == null) throw AppException(AppErrorCode.openProjectFirst); if (current.timelines.length <= 1) { throw AppException(AppErrorCode.timelineRequired); } final deletedIndex = current.timelines.indexWhere( (timeline) => timeline.id == timelineId, ); if (deletedIndex < 0) throw AppException(AppErrorCode.timelineMissing); final replacementId = current.timelines[deletedIndex > 0 ? deletedIndex - 1 : 1].id; final timelines = await _workspace.deleteTimeline(project, timelineId); if (!ref.mounted || state.requireValue.activeProject?.id != project.id) { return; } TimelineDocument? selected = state.requireValue.timeline; if (selected?.id == timelineId) { selected = await _workspace.loadTimeline(project.id, replacementId); await _prepareTimeline(project.id, selected); } if (!ref.mounted || state.requireValue.activeProject?.id != project.id) { return; } state = AsyncData( state.requireValue.copyWith(timelines: timelines, timeline: selected), ); if (selected != null) await _rememberTimeline(project.id, selected.id); }); Future createTimeline({String? name}) async { await future; final current = state.requireValue; if (current.projectBusy || current.creatingTimeline || current.openingTimelineId != null || current.activeProject == null) { return false; } if (current.timelines.length >= maxTimelineCount) return false; state = AsyncData(current.copyWith(creatingTimeline: true, error: null)); try { final timelineName = name?.trim().isNotEmpty == true ? name!.trim() : _nextUntitledTimelineName(current.timelines); final created = await _workspace.createPreparedTimeline( timelineName, creationNames: _creationNames(timelineName), ); await _prepareTimeline(current.activeProject!.id, created.document); if (!ref.mounted) return true; state = AsyncData( state.requireValue.copyWith( timelines: created.timelines, timeline: created.document, creatingTimeline: false, ), ); await _rememberTimeline(current.activeProject!.id, created.document.id); return true; } catch (error) { if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( creatingTimeline: false, error: _failureFor(error), ), ); } return false; } } String _nextUntitledTimelineName(List timelines) { final names = timelines.map((timeline) => timeline.name).toSet(); final base = _localizations.untitledTimeline; if (!names.contains(base)) return base; for (var suffix = 2; ; suffix++) { final candidate = '$base ($suffix)'; if (!names.contains(candidate)) return candidate; } } Future importExternalMedia( String projectId, List files, { bool Function()? isCancelled, }) async { MediaImportResult? result; await _perform(() async { result = await _workspace.importExternalMedia( projectId, files, isCancelled: isCancelled, ); }); return result; } Future insertTimelineAsset({ required String projectId, required EditorTimelineSession session, required SequenceId sequenceId, required String assetId, required int position, }) => _perform(() async { final current = state.requireValue; if (current.activeProject?.id != projectId || current.timeline?.id != session.document.id) { throw AppException(AppErrorCode.projectSwitched); } await session.commands.insertMedia( sequence: sequenceId, assetId: assetId, position: position, ); }); Future editMediaAsset( String projectId, String assetId, { String? name, }) => _perform(() async { final assets = await _workspace.editAsset(projectId, assetId, name: name); if (ref.mounted && state.requireValue.activeProject?.id == projectId) { state = AsyncData(state.requireValue.copyWith(assets: assets)); } }); Future revealMediaAsset(String projectId, AssetDocument asset) => _perform(() async { await _workspace.withAssetMedia(projectId, asset, (media) async { if (media.uri.scheme != 'file') { throw AppException(AppErrorCode.notLocalMedia); } final path = media.uri.toFilePath(); final result = Platform.isMacOS ? await Process.run('/usr/bin/open', ['-R', path]) : Platform.isWindows ? await Process.run('explorer.exe', ['/select,', path]) : await Process.run('xdg-open', [File(path).parent.path]); if (result.exitCode != 0) { throw AppException(AppErrorCode.revealMediaFailed); } }); }); Future openTimelineSession( String projectId, String timelineId, ) async { final current = await future; if (current.activeProject?.id != projectId || current.timeline?.id != timelineId) { throw AppException( current.activeProject?.id != projectId ? AppErrorCode.openMatchingProject : AppErrorCode.openTimelineFailed, ); } return _workspace.openTimelineSession(projectId, current.timeline!); } Future _prepareTimeline( String projectId, TimelineDocument document, { bool preparePreview = true, }) async { final session = await _workspace.openTimelineSession(projectId, document); await TimelineViewStateBinding.prepare( projectId: projectId, timelineId: document.id, session: session, repository: ref.read(timelineViewSettingsRepositoryProvider), ); // The preview panel owns asynchronous startup after project publication. // Cached controllers still bind synchronously when revisiting a project. if (!preparePreview) return session; try { await ref.read(previewControllerRegistryProvider).prepare(( projectId, document.id, ), session); } catch (error, stackTrace) { AppDiagnostics.failure('preview', 'prepare', error, stackTrace); } return session; } Future leaseTimeline( String projectId, String timelineId, ) async { await future; return _workspace.leaseTimeline(projectId, timelineId); } Future openTimeline(String projectId, String timelineId) async { await future; final current = state.requireValue; if (current.projectBusy || current.creatingTimeline || current.openingTimelineId != null || current.activeProject?.id != projectId) { return false; } if (current.timeline?.id == timelineId) return true; final cachedTimeline = _workspace.cachedTimelineDocument( projectId, timelineId, ); final cachedSession = _workspace.cachedTimelineSession( projectId, timelineId, ); if (cachedTimeline != null && cachedSession != null) { state = AsyncData( current.copyWith(timeline: cachedTimeline, error: null), ); await _rememberTimeline(projectId, timelineId); return true; } state = AsyncData( current.copyWith(openingTimelineId: timelineId, error: null), ); try { final timeline = await _workspace.loadTimeline(projectId, timelineId); await _prepareTimeline(projectId, timeline); if (!ref.mounted) return true; state = AsyncData( state.requireValue.copyWith( timeline: timeline, openingTimelineId: null, ), ); await _rememberTimeline(projectId, timelineId); return true; } catch (error) { if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( openingTimelineId: null, error: _failureFor(error), ), ); } return false; } } Future _rememberTimeline(String projectId, String timelineId) async { try { await ref .read(recentProjectsProvider) .rememberTimeline(projectId, timelineId); } catch (_) { if (ref.mounted) { state = AsyncData( state.requireValue.copyWith( error: const AppFailure(AppErrorCode.lastProjectSaveFailed), ), ); } } } AppFailure _failureFor(Object error) => projectFailureFromError(error); }