import 'package:cutdex/errors/app_failure.dart'; import 'dart:async'; import 'dart:convert'; import 'dart:io'; import '../../diagnostics/app_diagnostics.dart'; import 'timeline_creation_names.dart'; import 'package:cutdex_sdk/project.dart'; import 'package:cutdex_sdk/runtime.dart'; import 'package:cutdex_sdk/timeline/model.dart'; import 'package:path/path.dart' as p; import 'package:uuid/uuid.dart'; import 'package:cutdex_sdk/editor.dart'; import '../project_assets_changed.dart'; import '../project_state.dart'; import '../media_file_extensions.dart'; import '../media_import.dart'; import '../prepared_media_metadata.dart'; import '../timeline_session.dart'; import '../background_task_registry.dart'; import '../../integrations/runtime/editor_export.dart'; import '../../integrations/runtime/processing_configuration.dart'; import '../../integrations/platform/media_source_reader.dart'; class ProjectOpenSuperseded implements Exception {} class WorkspaceTimelineLease { const WorkspaceTimelineLease(this.session, this.release, this.validate); final EditorTimelineSession session; final Future Function() release; final Future Function() validate; } typedef CreatedTimeline = ({ List timelines, TimelineDocument document, EditorTimelineSession session, }); /// Owns the active file and serializes operations, including close. class ProjectWorkspace { ProjectWorkspace({ required this._creationNames, CutdexRuntime? runtime, ProcessingConfiguration? processing, BackgroundTaskRegistry? backgroundTasks, this.mediaSourceReader = const MediaSourceReader(), }) : _runtime = runtime ?? CutdexRuntime(diagnostics: AppDiagnostics.report), _processingOverride = processing, backgroundTasks = backgroundTasks ?? BackgroundTaskRegistry(), _ownsBackgroundTasks = backgroundTasks == null; final _assetChanges = StreamController.broadcast(); Stream get assetChanges => _assetChanges.stream; final TimelineCreationNames _creationNames; final CutdexRuntime _runtime; final MediaSourceReader mediaSourceReader; final ProcessingConfiguration? _processingOverride; final BackgroundTaskRegistry backgroundTasks; final bool _ownsBackgroundTasks; ProcessingConfiguration? get _processing => _processingOverride ?? ProcessingConfiguration.configured(diagnostics: AppDiagnostics.report); ProjectFile? _project; final _documents = {}; final _documentVersions = {}; final _sessions = {}; final _retainedProjects = {}; final _warmProjects = []; Set get cachedProjectIds => { if (_project != null) _project!.info.id, for (final file in _warmProjects) file.info.id, }; final _retainedTimelines = {}; final _timelineLeases = {}; Future _tail = Future.value(); bool _closed = false; Future? _closing; static const _uuid = Uuid(); ProjectFile? get project => _project; EditorTimelineSession? cachedTimelineSession( String projectId, String timelineId, ) { if (_project?.info.id != projectId) return null; final session = _sessions[timelineId]; return session?.acceptsEdits == true ? session : null; } TimelineDocument? cachedTimelineDocument( String projectId, String timelineId, ) => _project?.info.id == projectId ? _documents[timelineId] : null; ProjectFile? _fileFor(String projectId) { final active = _project; if (active?.info.id == projectId) return active; for (final file in _retainedProjects) { if (file.info.id == projectId) return file; } return null; } Future _retireProject() async { final file = _project; if (file == null) return; for (final timeline in _sessions.values) { await timeline.flush(); } for (final timeline in _sessions.values) { _retainedTimelines[timeline] = file; } _retainedProjects.add(file); _warmProjects.remove(file); _warmProjects.add(file); _sessions.clear(); _documents.clear(); _documentVersions.clear(); _project = null; } Future deactivateProject() => _run(() async { await _retireProject(); await _trimWarmProjects(); }); Future _trimWarmProjects() async { while (_warmProjects.length > 2) { final file = _warmProjects.removeAt(0); final sessions = _retainedTimelines.entries .where((entry) => entry.value == file) .map((entry) => entry.key) .toList(); for (final session in sessions) { final hasTasks = session.subtitleWorkflows.tasks.isNotEmpty || (session.transcriptions?.tasks.isNotEmpty ?? false) || session.backgroundRemovals.tasks.isNotEmpty; if ((_timelineLeases[session] ?? 0) > 0 || hasTasks) continue; await session.flush(); backgroundTasks.unregister(session); await session.close(); _retainedTimelines.remove(session); } if (!_retainedTimelines.containsValue(file)) { _retainedProjects.remove(file); await file.close(); } } } Future leaseTimeline( String projectId, String timelineId, ) => _run(() async { final session = _sessions[timelineId]; if (_project?.info.id != projectId || session == null) { throw AppException(AppErrorCode.openTimelineFailed); } _timelineLeases[session] = (_timelineLeases[session] ?? 0) + 1; final file = _project!; var released = false; Future validate() async { if (!session.acceptsEdits) { throw AppException(AppErrorCode.timelineSessionClosed); } final manifest = File(p.join(file.directory.path, 'manifest.json')); final value = jsonDecode(await manifest.readAsString()); if (value is! Map || value['projectId'] != projectId) { throw AppException(AppErrorCode.projectMismatch); } } return WorkspaceTimelineLease( session, () => _run(() async { if (released) return; released = true; final remaining = (_timelineLeases[session] ?? 1) - 1; if (remaining > 0) { _timelineLeases[session] = remaining; return; } _timelineLeases.remove(session); final retainedFile = _retainedTimelines[session]; if (retainedFile == null || _warmProjects.contains(retainedFile)) { return; } final file = _retainedTimelines.remove(session)!; backgroundTasks.unregister(session); await session.close(); if (file != _project && !_retainedTimelines.containsValue(file)) { _retainedProjects.remove(file); await file.close(); } }), validate, ); }); bool get hasBackgroundTasks => {..._sessions.values, ..._retainedTimelines.keys}.any( (timeline) => timeline.subtitleWorkflows.runningCount > 0 || (timeline.transcriptions?.translationTasks.any( (task) => !task.terminal, ) ?? false) || (timeline.vocalSeparations?.tasks.any((task) => !task.terminal) ?? false), ); Future _run(Future Function() action) { if (_closed) { return Future.error(AppException(AppErrorCode.projectSessionClosed)); } final result = _tail.then((_) => action()); _tail = result.then((_) {}, onError: (Object _, StackTrace _) {}); return result; } Future> open( String path, { String? name, String? expectedId, TimelineCreationNames? creationNames, bool Function()? isCurrent, }) => _run(() async { void checkCurrent() { if (isCurrent?.call() == false) throw ProjectOpenSuperseded(); } checkCurrent(); final directory = Directory(path); ProjectFile? candidate; var installed = false; try { if (_project != null && name == null && await directory.resolveSymbolicLinks() == _project!.directory.path) { if (expectedId != null && expectedId != _project!.info.id) { throw AppException(AppErrorCode.projectMismatch); } return await _project!.listTimelines(); } final canonicalPath = name == null ? await directory.resolveSymbolicLinks() : null; final retained = name == null ? _retainedProjects .where((file) => file.directory.path == canonicalPath) .firstOrNull : null; candidate = retained ?? (name == null ? await ProjectFile.open(directory) : await _createProjectFile( directory, name: name, initialTimeline: _newTimelineDocument( (creationNames ?? _creationNames).timeline, creationNames ?? _creationNames, ), )); if (expectedId != null && candidate.info.id != expectedId) { throw AppException(AppErrorCode.projectMismatch); } var timelines = await candidate.listTimelines(); if (timelines.isEmpty) { final initial = _newTimelineDocument( (creationNames ?? _creationNames).timeline, creationNames ?? _creationNames, ); await candidate.saveTimeline(initial); await candidate.setTimelinePinned(initial.id, true); timelines = await candidate.listTimelines(); } checkCurrent(); final documents = {}; for (final timeline in timelines) { checkCurrent(); documents[timeline.id] = await candidate.loadTimeline(timeline.id); } checkCurrent(); // Saving the previous project is deliberately not cancellable. await _retireProject(); _retainedProjects.remove(candidate); _warmProjects.remove(candidate); _project = candidate; _documents.addAll(documents); installed = true; await _trimWarmProjects(); return timelines; } finally { if (!installed) { if (candidate != null && !_retainedProjects.contains(candidate)) { await candidate.close(); } } } }); Future _createProjectFile( Directory directory, { required String name, required TimelineDocument initialTimeline, }) async { try { return await ProjectFile.create( directory, name: name, initialTimeline: initialTimeline, ); } on ProjectFileException catch (error) { if (error.code != ProjectFileError.conflict) rethrow; throw AppException( AppErrorCode.projectAlreadyExists, diagnostic: error.toString(), ); } } /// Reads timelines from any project without installing it as the active one. /// /// This intentionally shares the workspace queue with [open] and all active /// project operations. A restored expansion and a restored active project /// can otherwise try to open the same SQLite files at the same time. Future> listProjectTimelines( String path, { required String expectedId, }) => _run(() async { final available = _fileFor(expectedId); if (available != null) { return available.listTimelines(); } final candidate = await ProjectFile.open(Directory(path)); try { if (candidate.info.id != expectedId) { throw AppException(AppErrorCode.projectMismatch); } return await candidate.listTimelines(); } finally { await candidate.close(); } }); Future renameProject(RecentProject project, String name) => _withProject(project, (file) => file.rename(name)); Future renameTimeline( RecentProject project, String timelineId, String name, ) => _withProject(project, (file) async { await file.renameTimeline(timelineId, name); if (file != _project) return; final document = _documents[timelineId]; if (document == null) return; _documents[timelineId] = TimelineDocument( id: document.id, name: name, sequences: document.sequences, defaultSequenceId: document.defaultSequenceId, payloads: document.payloads, settings: document.settings, revision: document.revision, ); }); Future> setTimelinePinned( RecentProject project, String timelineId, bool pinned, ) => _withProject(project, (file) async { await file.setTimelinePinned(timelineId, pinned); return file.listTimelines(); }); Future> deleteTimeline( RecentProject project, String timelineId, ) => _withProject(project, (file) async { final session = file == _project ? _sessions[timelineId] : null; if (session != null) { if ((_timelineLeases[session] ?? 0) > 0) { throw AppException(AppErrorCode.timelineInUse); } if (session.subtitleWorkflows.runningCount > 0 || session.backgroundRemovals.runningCount > 0 || (session.vocalSeparations?.tasks.any((task) => !task.terminal) ?? false)) { throw AppException(AppErrorCode.timelineHasBackgroundTasks); } await session.flush(); } final summaries = await file.listTimelines(); final target = summaries.where((item) => item.id == timelineId).firstOrNull; if (target == null) throw AppException(AppErrorCode.timelineMissing); await file.deleteTimeline(timelineId, expectedRevision: target.revision); if (session != null) { backgroundTasks.unregister(session); await session.close(); } if (file == _project) { _sessions.remove(timelineId); _documents.remove(timelineId); _documentVersions.remove(timelineId); } return file.listTimelines(); }); Future _withProject( RecentProject project, Future Function(ProjectFile file) action, ) => _run(() async { final available = _fileFor(project.id); if (available != null) return action(available); final candidate = await ProjectFile.open(Directory(project.path)); try { if (candidate.info.id != project.id) { throw AppException(AppErrorCode.projectMismatch); } return await action(candidate); } finally { await candidate.close(); } }); Future> createTimeline( String name, { TimelineCreationNames? creationNames, }) => _run(() async { await _createTimelineDocument(name, creationNames ?? _creationNames); return _project!.listTimelines(); }); Future createPreparedTimeline( String name, { TimelineCreationNames? creationNames, }) => _run(() async { final saved = await _createTimelineDocument( name, creationNames ?? _creationNames, ); final project = _project!; final session = await _openTimelineSession(project.info.id, saved); return ( timelines: await project.listTimelines(), document: saved, session: session, ); }); Future _createTimelineDocument( String name, TimelineCreationNames creationNames, ) async { final project = _project; if (project == null) throw AppException(AppErrorCode.openProjectFirst); final document = _newTimelineDocument(name, creationNames); await project.saveTimeline(document); final saved = await project.loadTimeline(document.id); _documents[document.id] = saved; return saved; } TimelineDocument _newTimelineDocument( String name, TimelineCreationNames creationNames, ) { final sequence = TimelineDto( id: SequenceId(_uuid.v4()), name: creationNames.sequence, format: TimelineFormat(frameDuration: RationalTime(1, 30)), primaryStorylineId: StorylineId('primary'), storylines: [ StorylineDto( id: StorylineId('primary'), elementIds: [], name: creationNames.storyline, ), ], elements: [], ); return TimelineDocument( id: _uuid.v4(), name: name, sequences: [sequence], defaultSequenceId: sequence.id, ); } Future loadTimeline(String projectId, String timelineId) => _run(() async { if (_project?.info.id != projectId) { throw AppException(AppErrorCode.openMatchingProject); } for (final session in _retainedTimelines.keys) { if (session.document.id == timelineId && _retainedTimelines[session] == _project) { return _documents[timelineId] ?? session.document; } } final session = _sessions[timelineId]; if (session != null && _documentVersions[timelineId] != session.version) { await session.flush(); _documents[timelineId] = await _project!.loadTimeline(timelineId); _documentVersions[timelineId] = session.version; } final document = _documents[timelineId] ?? await _project!.loadTimeline(timelineId); _documents[timelineId] = document; return document; }); Future> listAssets(String projectId) => _run(() async { final project = _fileFor(projectId); if (project == null) throw AppException(AppErrorCode.openMatchingProject); return _visibleAssets(await project.listAssets()); }); static const _hiddenAssetKey = 'cutdex.catalogHidden'; static List _visibleAssets(List assets) => [ for (final asset in assets) if (asset.metadata[_hiddenAssetKey] != true) asset, ]; static AssetDocument _catalogAsset( AssetDocument asset, { String? name, bool? hidden, }) => AssetDocument( id: asset.id, name: name ?? asset.name, storage: asset.storage, location: asset.location, byteLength: asset.byteLength, contentHash: asset.contentHash, metadata: { for (final entry in asset.metadata.entries) if (entry.key != _hiddenAssetKey || hidden == null) entry.key: entry.value, if (hidden == true) _hiddenAssetKey: true, }, accessData: asset.accessData, ); Future> editAsset( String projectId, String assetId, { String? name, }) => _run( () async => (await _editCatalog(projectId, assetId, name: name)).assets, ); Future editCatalog(String projectId, String assetId, {String? name}) => _run( () async => (await _editCatalog(projectId, assetId, name: name)).changed, ); Future<({List assets, bool changed})> _editCatalog( String projectId, String assetId, { String? name, }) async { final project = _fileFor(projectId); if (project == null) { throw const CommandRejected('closed', 'Media project has changed'); } final all = await project.listAssets(); final asset = all.where((a) => a.id == assetId).firstOrNull; if (asset == null) { throw const CommandRejected('missingMedia', 'Media does not exist'); } if (name != null && name.trim().isEmpty) { throw const CommandRejected('invalidArguments', 'Name is empty'); } final changed = name == null ? asset.metadata[_hiddenAssetKey] != true : asset.name != name.trim(); if (changed) { await project.saveAsset( name == null ? _catalogAsset(asset, hidden: true) : _catalogAsset(asset, name: name.trim()), ); } final visible = _visibleAssets(await project.listAssets()); if (changed) _assetChanges.add(ProjectAssetsChanged(projectId, visible)); return (assets: visible, changed: changed); } Future withAssetMedia( String projectId, AssetDocument asset, Future Function(MediaReference media) action, ) async { final media = await _run(() async { final project = _fileFor(projectId); if (project == null) { throw AppException(AppErrorCode.projectSwitched); } final uri = await project.resolveAsset(asset); return MediaReference( id: asset.id, uri: uri, isImage: asset.metadata['kind'] == 'image', ); }); return action(media); } /// Registers local references and imports provider documents into the project. Future importExternalMedia( String projectId, Iterable files, { bool Function()? isCancelled, }) { final batch = files.toList(growable: false); return _run(() async { final project = _fileFor(projectId); if (project == null) { throw AppException(AppErrorCode.openMatchingProject); } final assets = await project.listAssets(); final locations = { for (final asset in assets) if (asset.metadata[_hiddenAssetKey] != true) ?mediaSourceLocation(asset), }; final hiddenByLocation = { for (final asset in assets) if (asset.metadata[_hiddenAssetKey] == true) ?mediaSourceLocation(asset): asset, }; final failures = []; var added = 0; var duplicates = 0; for (final source in batch) { try { if (source case ContentMediaFile()) { final location = source.sourceUri.toString(); if (locations.contains(location)) { duplicates++; continue; } final hidden = hiddenByLocation[location]; if (hidden != null) { if (isCancelled?.call() == true) { throw AppException(AppErrorCode.mediaImportCancelled); } await project.saveAsset(_catalogAsset(hidden, hidden: false)); } else { await _importProviderMedia(project, source, isCancelled); } locations.add(location); added++; continue; } final sourcePath = source.localPath!; if (!p.isAbsolute(sourcePath)) { throw AppException(AppErrorCode.localFilesOnly); } // The native runtime verifies the selected file's actual media tracks. final kind = mediaKindForPath(sourcePath); if (kind == null) { throw AppException(AppErrorCode.unsupportedMediaType); } final file = File(await File(sourcePath).resolveSymbolicLinks()); final stat = await file.stat(); if (stat.type != FileSystemEntityType.file) { throw AppException(AppErrorCode.foldersUnsupported); } // Check read access without reading the file into memory. final handle = await file.open(); await handle.close(); final location = file.uri.toString(); if (locations.contains(location)) { duplicates++; continue; } if (p.extension(file.path).toLowerCase() == '.iso') { final metadata = PreparedMediaMetadata.fromInfo( await _runtime.probe(MediaReference(id: location, uri: file.uri)), ); if (metadata.kind != EditorMediaKind.video) { throw AppException(AppErrorCode.mediaNoVideoTracks); } } final hidden = hiddenByLocation[location]; if (hidden != null) { if (isCancelled?.call() == true) { throw AppException(AppErrorCode.mediaImportCancelled); } await project.saveAsset(_catalogAsset(hidden, hidden: false)); locations.add(location); added++; continue; } final asset = AssetDocument( id: _uuid.v4(), name: source.displayName, storage: AssetStorage.external, location: location, byteLength: stat.size, metadata: {'kind': kind}, ); if (isCancelled?.call() == true) { throw AppException(AppErrorCode.mediaImportCancelled); } await project.saveAsset(asset); locations.add(location); added++; } catch (error) { failures.add( MediaImportFailure( name: source.displayName, failure: switch (error) { AppException(:final failure) => failure, FileSystemException() => AppFailure( AppErrorCode.fileAccessFailed, diagnostic: error.toString(), ), _ => AppFailure( AppErrorCode.registerMediaFailed, diagnostic: error.toString(), ), }, ), ); } } final visible = _visibleAssets(await project.listAssets()); _assetChanges.add(ProjectAssetsChanged(projectId, visible)); return MediaImportResult( assets: visible, added: added, duplicates: duplicates, failures: failures, ); }); } Future _importProviderMedia( ProjectFile project, ContentMediaFile source, bool Function()? isCancelled, ) async { final kind = mediaKindForPath(source.name); if (source.uri.scheme != 'content' || source.uri.host.isEmpty) { throw AppException( AppErrorCode.fileAccessFailed, diagnostic: 'Invalid provider URI', ); } if (kind == null) throw AppException(AppErrorCode.unsupportedMediaType); if (isCancelled?.call() == true) { throw AppException(AppErrorCode.mediaImportCancelled); } final staging = await Directory.systemTemp.createTemp( 'cutdex-media-import-', ); try { final file = File( p.join(staging.path, 'source${p.extension(source.name)}'), ); final handle = await file.open(mode: FileMode.write); var bytes = 0; try { await for (final chunk in mediaSourceReader.openRead(source.uri)) { if (isCancelled?.call() == true) { throw AppException(AppErrorCode.mediaImportCancelled); } await handle.writeFrom(chunk); bytes += chunk.length; } await handle.flush(); } finally { await handle.close(); } if (source.byteLength != null && source.byteLength != bytes) { throw AppException( AppErrorCode.mediaReadFailed, diagnostic: 'Expected ${source.byteLength} bytes, received $bytes', ); } if (isCancelled?.call() == true) { throw AppException(AppErrorCode.mediaImportCancelled); } await project.importFile( file, name: source.name, metadata: {'kind': kind, mediaSourceUriKey: source.uri.toString()}, ); } finally { await staging.delete(recursive: true); } } Future openTimelineSession( String projectId, TimelineDocument document, ) => _run(() => _openTimelineSession(projectId, document)); Future _openTimelineSession( String projectId, TimelineDocument document, ) async { if (_project?.info.id != projectId) { throw AppException(AppErrorCode.openMatchingProject); } final existing = _sessions[document.id]; if (existing != null) return existing; for (final session in _retainedTimelines.keys.toList()) { if (session.document.id == document.id && _retainedTimelines[session] == _project) { _retainedTimelines.remove(session); _sessions[document.id] = session; _documentVersions[document.id] = session.version; return session; } } final persistence = await _project!.openTimelineSaveSession(document.id); EditorSession.validateCheckpoint(document, persistence); final referencedAssets = document.payloads .expand((payload) => payload.assetIds) .toSet(); final assetUris = {}; for (final asset in await _project!.listAssets()) { if (referencedAssets.contains(asset.id)) { assetUris[asset.id] = await _project!.resolveAsset(asset); } } final processing = _processing; final session = EditorTimelineSession( diagnostics: (event) => withDiagnosticContext({ 'projectId': projectId, }, () => reportDiagnostic(AppDiagnostics.report, event)), document: document, persistence: persistence, assetUris: Map.unmodifiable(assetUris), media: _WorkspaceEditorMedia(this, projectId), exportService: RuntimeEditorExport(_runtime), captionFiles: Platform.isMacOS || Platform.isIOS || Platform.isWindows ? _runtime : null, transcriptionBackend: processing?.transcriptionModel == null ? null : processing!.backend, transcriptionModel: processing?.transcriptionModel, translationBackend: processing?.translationModel == null ? null : processing!.backend, translationModel: processing?.translationModel, vocalSeparationBackend: processing?.vocalSeparationModel == null ? null : processing!.backend, vocalSeparationModel: processing?.vocalSeparationModel, ); if (processing?.backgroundRemovalModel case final model?) { session.backgroundRemovals.configure( backend: processing!.backend.execute, model: model, ); } await session.restoreProcessingTasks(); _sessions[document.id] = session; backgroundTasks.register( projectId: projectId, projectName: _project!.info.name, session: session, ); _documents[document.id] = document; _documentVersions[document.id] = session.version; return session; } Future prepareMedia( String projectId, String assetId, ) => _run(() async { final project = _fileFor(projectId); if (project == null) throw AppException(AppErrorCode.openMatchingProject); final asset = (await project.listAssets()) .where((asset) => asset.id == assetId) .firstOrNull; if (asset == null) throw AppException(AppErrorCode.mediaNoLongerExists); final uri = await project.resolveAsset(asset); final PreparedMediaMetadata metadata; if (asset.metadata['kind'] == 'image') { metadata = PreparedMediaMetadata.image(); } else { try { final source = MediaReference(id: asset.id, uri: uri); metadata = PreparedMediaMetadata.fromInfo(await _runtime.probe(source)); } on RuntimeException catch (e) { throw AppException( e.code == 'unsupported' ? AppErrorCode.mediaInfoUnsupported : AppErrorCode.mediaInfoFailed, diagnostic: e.toString(), ); } } return PreparedEditorMedia( asset: _editorAsset(asset), uri: uri, duration: metadata.duration, kind: metadata.kind, hasAudio: metadata.hasAudio, audioTracks: metadata.audioTracks, ); }); Future importGeneratedMedia( String projectId, String path, { required String name, }) async { final asset = await _run(() async { final project = _fileFor(projectId); if (project == null) { throw const CommandRejected('closed', 'Media project has changed'); } final imported = await project.importFile( File(path), name: name, recoveryKey: 'generated:${File(path).absolute.path}', ); final visible = _visibleAssets(await project.listAssets()); _assetChanges.add(ProjectAssetsChanged(projectId, visible)); return imported; }); return prepareMedia(projectId, asset.id); } Future close() { if (_closing case final pending?) return pending; _closed = true; final operation = _tail.then((_) async { try { for (final session in _sessions.values) { await session.flush(); } for (final session in _retainedTimelines.keys) { await session.flush(); } for (final session in _sessions.values) { backgroundTasks.unregister(session); await session.close(); } for (final session in _retainedTimelines.keys) { backgroundTasks.unregister(session); await session.close(); } } catch (_) { // Nothing has been released yet. Keep the workspace usable so the // caller can recover an unsuccessful save without losing the edits. _closed = false; rethrow; } _sessions.clear(); _documents.clear(); _documentVersions.clear(); _retainedTimelines.clear(); _timelineLeases.clear(); await _project?.close(); for (final file in _retainedProjects) { await file.close(); } _project = null; _retainedProjects.clear(); _warmProjects.clear(); await _assetChanges.close(); if (_ownsBackgroundTasks) backgroundTasks.dispose(); }); final closing = operation.onError((Object error, StackTrace stack) { _closing = null; Error.throwWithStackTrace(error, stack); }); _closing = closing; // A failed close must not poison the queue or prevent cleanup retries. _tail = closing.then((_) {}, onError: (Object _, StackTrace _) {}); return closing; } } final class _WorkspaceEditorMedia implements EditorMediaService, EditorAudioSource, EditorMediaCatalog, EditorGeneratedMediaCatalog { const _WorkspaceEditorMedia(this.workspace, this.projectId); final ProjectWorkspace workspace; final String projectId; @override Future> query() async => [ for (final asset in await workspace.listAssets(projectId)) _editorAsset(asset), ]; @override Future importFile( String path, { bool Function()? isCancelled, }) async { final result = await workspace.importExternalMedia(projectId, [ ExternalMediaFile(path: path), ], isCancelled: isCancelled); if (result.failures.isNotEmpty) { throw AppException.fromFailure(result.failures.first.failure); } return EditorMediaImportResult( assets: [for (final asset in result.assets) _editorAsset(asset)], added: result.added, duplicates: result.duplicates, ); } @override Future rename(String assetId, String name) => workspace.editCatalog(projectId, assetId, name: name); @override Future remove(String assetId) => workspace.editCatalog(projectId, assetId); @override Future waveform(String assetId, int audioTrackIndex) async { final asset = (await workspace.listAssets(projectId)) .where((a) => a.id == assetId) .firstOrNull; if (asset == null) { throw const CommandRejected('missingMedia', 'Audio asset is unavailable'); } return workspace.withAssetMedia( projectId, asset, (media) => CutdexRuntime(diagnostics: AppDiagnostics.report).waveform( WaveformRequest( media: media, trackSelection: TrackSelection.index(audioTrackIndex), baseBucketCount: 32768, levelCount: 1, ), ), ); } @override Future prepare(String assetId) => workspace.prepareMedia(projectId, assetId); @override Future importGenerated( String path, { required String name, }) => workspace.importGeneratedMedia(projectId, path, name: name); } EditorMediaAsset _editorAsset(AssetDocument asset) => EditorMediaAsset(id: asset.id, name: asset.name, metadata: asset.metadata);