import 'dart:io'; import 'package:cutdex_sdk/editor.dart'; import 'package:cutdex_sdk/timeline/model.dart'; import 'package:cutdex_sdk/tools.dart'; import '../workspace/project_state.dart'; import 'application_command_dependencies.dart'; /// Application navigation adapter; project persistence and playback stay with owners. class ApplicationCommandHost implements EditorCommandHost { ApplicationCommandHost(this.dependencies, {required this.refresh}); final ApplicationCommandDependencies dependencies; final Future Function() refresh; @override Set get supportedOperations => applicationOperations; @override Future execute( EditorCommand command, CommandContext context, ) async { final state = await dependencies.projectState(); if (context.isCancelled()) { throw const CommandRejected('cancelled', 'Cancelled before execution'); } if (!supportedOperations.contains(command.operation)) { throw const CommandRejected( 'unsupported', 'Choose a sequence workspace for editing', ); } if (!applicationReadOperations.contains(command.operation) && state.projectBusy) { throw const CommandRejected( 'workspaceBusy', 'Another workspace operation is running', ); } void requireProject(String id) { if (state.activeProject?.id != id) { throw const CommandRejected( 'missingProject', 'Open the addressed project first', ); } } void requireTimeline(String projectId, String timelineId) { requireProject(projectId); if (state.timeline?.id != timelineId) { throw const CommandRejected( 'missingTimeline', 'Open the addressed timeline first', ); } } Map projectData(RecentProject project) => { 'projectId': project.id, 'name': project.name, 'path': project.path, }; CommandResult result(Map data) => CommandResult( status: CommandStatus.succeeded, message: 'Workspace state', data: data, ); switch (command) { case QueryProjects(): return result({ 'active': state.activeProject == null ? null : projectData(state.activeProject!), 'recent': state.recent.map(projectData).toList(), 'busy': state.projectBusy, }); case ListTimelines(): requireProject(command.projectId); return result({ 'projectId': command.projectId, 'activeTimelineId': state.timeline?.id, 'timelines': [ for (final timeline in state.timelines) {'timelineId': timeline.id, 'name': timeline.name}, ], 'sequences': [ for (final sequence in state.timeline?.sequences ?? []) {'sequenceId': sequence.id.value, 'name': sequence.name}, ], }); case CreateProject(): if (command.name.trim().isEmpty) { throw const CommandRejected( 'invalidArguments', 'Use a nonempty project name', ); } if (!await dependencies.createProject(command.name)) { final current = await dependencies.projectState(); throw CommandRejected( 'projectCreationFailed', current.error?.toString() ?? 'Project creation did not complete', ); } await refresh(); final current = await dependencies.projectState(); return result({ 'project': projectData(current.activeProject!), 'activeTimelineId': current.timeline?.id, }); case OpenProject(): if (!File(command.path).isAbsolute) { throw const CommandRejected( 'invalidArguments', 'Use an absolute project path', ); } final String canonicalPath; try { canonicalPath = await Directory(command.path).resolveSymbolicLinks(); } on FileSystemException { throw const CommandRejected( 'missingProject', 'Project path is not readable', ); } final known = [ ?state.activeProject, ...state.recent, ].where((project) => project.path == canonicalPath).firstOrNull; if (known != null && command.projectId != null && known.id != command.projectId) { throw CommandRejected( 'projectIdMismatch', 'This path belongs to project ${known.id}. Use project.query to read the current project.', ); } final opened = await dependencies.openProject( command.path, expectedId: command.projectId, ); if (!opened) throw StateError('Project open did not complete'); await refresh(); final current = await dependencies.projectState(); return result({ 'project': projectData(current.activeProject!), 'activeTimelineId': current.timeline?.id, }); case CreateTimeline(): requireProject(command.projectId); if (command.name.trim().isEmpty) { throw const CommandRejected( 'invalidArguments', 'Timeline name is empty', ); } final before = state.timelines.map((timeline) => timeline.id).toSet(); if (!await dependencies.createTimeline(command.name)) { throw StateError('Timeline creation did not complete'); } await refresh(); final current = await dependencies.projectState(); final created = current.timelines .where((timeline) => !before.contains(timeline.id)) .single; return result({ 'projectId': command.projectId, 'timelineId': created.id, 'name': created.name, 'activeTimelineId': current.timeline?.id, }); case OpenTimeline(): requireProject(command.projectId); if (!state.timelines.any( (timeline) => timeline.id == command.timelineId, )) { throw const CommandRejected( 'missingTimeline', 'Timeline does not exist', ); } if (state.timeline?.id != command.timelineId && !await dependencies.openTimeline( command.projectId, command.timelineId, )) { throw StateError('Timeline open did not complete'); } await refresh(); return result({ 'projectId': command.projectId, 'timelineId': command.timelineId, 'activeTimelineId': command.timelineId, 'sequences': [ for (final sequence in (await dependencies.projectState()).timeline!.sequences) {'sequenceId': sequence.id.value, 'name': sequence.name}, ], }); case SelectSequence(): requireTimeline(command.projectId, command.timelineId); if (!state.timeline!.sequences.any( (s) => s.id.value == command.sequenceId, )) { throw const CommandRejected( 'missingSequence', 'Sequence does not exist', ); } final session = await dependencies.timeline( command.projectId, command.timelineId, ); if (context.isCancelled()) { throw const CommandRejected( 'cancelled', 'Cancelled before selection', ); } session.commands.ensureOpen(null); await dependencies .preview(command.projectId, command.timelineId) .closeSource(); session.commands.ensureOpen(null); session.selectSequence(SequenceId(command.sequenceId)); return result({'sequenceId': command.sequenceId}); case SourcePreviewCommand(): requireTimeline(command.projectId, command.timelineId); final target = dependencies.preview( command.projectId, command.timelineId, ); switch (command.action) { case SourcePreviewAction.query: break; case SourcePreviewAction.open: final asset = state.assets .where((a) => a.id == command.mediaId) .firstOrNull; if (asset == null) { throw const CommandRejected( 'missingMedia', 'Media is not in the current project', ); } await target.openSource(asset); case SourcePreviewAction.close: await target.closeSource(); case SourcePreviewAction.play || SourcePreviewAction.pause || SourcePreviewAction.seek: if (command.mediaId == null) { throw const CommandRejected( 'invalidArguments', 'Source media ID is required', ); } await target.control( command.mediaId!, command.action, at: command.at, ); } final source = target.source; return result({ 'mediaId': target.asset?.id, 'available': source != null, 'ready': source != null && !source.busy && source.error == null, 'playing': source?.playing ?? false, 'failed': source?.error != null, 'position': CommandTime( source?.positionTick ?? 0, TimelineClock.ticksPerSecond, ).toJson(), 'duration': CommandTime( source?.durationTick ?? 0, TimelineClock.ticksPerSecond, ).toJson(), }); default: throw const CommandRejected( 'unsupported', 'Unsupported application operation', ); } } }