import 'package:cutdex/shared/widgets/error_notification_host.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'subtitle_download.dart'; import 'subtitle_task_actions.dart'; import 'package:cutdex/l10n/l10n.dart'; import 'package:cutdex_sdk/editor.dart'; import 'package:flutter/material.dart'; import '../../integrations/runtime/processing_resource_repository.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../shared/widgets/confirm_resource_download_cancel.dart'; import '../../workspace/background_task_registry.dart'; import '../../workspace/background_task_state.dart'; import '../../integrations/runtime/processing_resource_state.dart'; import '../../workspace/timeline_session.dart'; import 'transcription_dialog.dart'; class BackgroundTasksDialog extends StatelessWidget { const BackgroundTasksDialog({super.key, required this.session}); final EditorTimelineSession session; @override Widget build(BuildContext context) => AppDialog( title: context.l10n.backgroundTasks, width: 560, height: 520, child: BackgroundTasksContent(session: session), ); } class BackgroundTasksContent extends ConsumerWidget { const BackgroundTasksContent({ super.key, this.session, this.registry, this.repository, }) : assert(session != null || registry != null); final EditorTimelineSession? session; final BackgroundTaskRegistry? registry; final ProcessingResourceRepository? repository; @override Widget build(BuildContext context, WidgetRef ref) { final snapshot = ref.watch( backgroundTasksProvider(registry: registry, session: session), ); final resources = repository == null ? null : ref.watch(processingResourcesProvider(repository!)); final subtitleEntries = snapshot.subtitles; final removalEntries = snapshot.removals; final subtitleDownloading = resources?.subtitleDownloading == true; final resourceDownloads = resources?.installs .where( (install) => (install.state == ProcessingResourceState.downloading && !(subtitleDownloading && ProcessingResourceRepository.subtitleCapabilities .contains(install.package.capability))) || install.state == ProcessingResourceState.failed, ) .toList() ?? []; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ if (subtitleEntries.isEmpty && !subtitleDownloading && resourceDownloads.isEmpty && removalEntries.isEmpty) SizedBox( key: const Key('background-tasks-empty-state'), height: AppMenuMetrics.rowHeight, child: Padding( padding: const EdgeInsets.symmetric( horizontal: AppMenuMetrics.iconGap, ), child: Align( alignment: AlignmentDirectional.centerStart, child: Text( context.l10n.noBackgroundTasks, style: Theme.of(context).textTheme.bodyMedium?.copyWith( color: Theme.of(context).colorScheme.onSurfaceVariant, fontSize: AppMenuMetrics.fontSize, height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize, ), ), ), ), ) else Flexible( child: SingleChildScrollView( primary: false, child: Column( mainAxisSize: MainAxisSize.min, children: [ if (subtitleDownloading) _ResourceDownloadCard( repository: repository!, subtitleBundle: true, ), for (final (index, install) in resourceDownloads.indexed) ...[ if (index > 0 || subtitleDownloading) const SizedBox(height: 2), _ResourceDownloadCard( repository: repository!, install: install, ), ], for (final (index, entry) in removalEntries.indexed) ...[ if (index > 0 || resourceDownloads.isNotEmpty || subtitleDownloading) const SizedBox(height: 2), _BackgroundRemovalTaskCard( key: ValueKey(entry.task.id), entry: entry, ), ], for (final (index, entry) in subtitleEntries.reversed.indexed) ...[ if (index > 0 || resourceDownloads.isNotEmpty || removalEntries.isNotEmpty || subtitleDownloading) const SizedBox(height: 2), _SubtitleTaskCard( key: ValueKey(entry.job.recognition.id), entry: entry, ), ], ], ), ), ), ], ); } } String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty ? owner.timelineName : '${owner.projectName} · ${owner.timelineName}'; Future _showTaskDetails( BuildContext context, { required WidgetBuilder builder, EditorTimelineSession? session, }) async { final release = session?.retainViews(); try { await showAppDialog( context: context, builder: (context) => AppDialog( title: context.l10n.backgroundTaskDetails, width: 560, actions: [ TextButton( onPressed: () => Navigator.of(context).pop(), child: Text(context.l10n.close), ), ], child: builder(context), ), ); } finally { release?.call(); } } class _SubtitleTaskDetails extends ConsumerWidget { const _SubtitleTaskDetails(this.initial); final SubtitleTaskEntry initial; @override Widget build(BuildContext context, WidgetRef ref) { final latest = ref.watch( backgroundTasksProvider(session: initial.owner.session).select( (snapshot) => snapshot.subtitles .where((entry) => entry.job.id == initial.job.id) .firstOrNull, ), ); if (latest == null) return Text(context.l10n.noBackgroundTasks); return _SubtitleTaskCard( entry: latest.copyWith(owner: initial.owner), details: true, ); } } class _RemovalTaskDetails extends ConsumerWidget { const _RemovalTaskDetails(this.initial); final RemovalTaskEntry initial; @override Widget build(BuildContext context, WidgetRef ref) { final latest = ref.watch( backgroundTasksProvider(session: initial.owner.session).select( (snapshot) => snapshot.removals .where((entry) => entry.task.id == initial.task.id) .firstOrNull, ), ); if (latest == null) return Text(context.l10n.noBackgroundTasks); return _BackgroundRemovalTaskCard( entry: latest.copyWith(owner: initial.owner), details: true, ); } } class _TaskSummary extends StatelessWidget { const _TaskSummary({ required this.name, required this.status, required this.onTap, this.active = false, this.progress, this.progressDetails, this.action, }); final String name, status; final VoidCallback onTap; final bool active; final double? progress; final Widget? progressDetails; final Widget? action; @override Widget build(BuildContext context) => Material( type: MaterialType.transparency, borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius), clipBehavior: Clip.antiAlias, child: InkWell( onTap: onTap, borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius), hoverColor: AppSidebarColors.of(context).hover, highlightColor: Colors.transparent, splashColor: Colors.transparent, child: Padding( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8), child: Row( children: [ Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ Text(name, maxLines: 1, overflow: TextOverflow.ellipsis), const SizedBox(height: 4), if (progressDetails case final details?) details else ...[ Text( '$status${active && progress != null ? " · ${(progress! * 100).floor()}%" : ""}', style: Theme.of(context).textTheme.bodySmall, ), if (active) ...[ const SizedBox(height: 6), LinearProgressIndicator(value: progress), ], ], ], ), ), ?action, ], ), ), ), ); } class _BackgroundRemovalTaskCard extends StatelessWidget { const _BackgroundRemovalTaskCard({ super.key, required this.entry, this.details = false, }); final RemovalTaskEntry entry; final bool details; @override Widget build(BuildContext context) { final total = entry.total; final completed = entry.completed; final progressValue = total == null || total <= 0 || completed == null ? null : completed / total; final active = !entry.terminal; final status = switch (entry.status) { BackgroundRemovalStatus.queued => context.l10n.preparingMedia, BackgroundRemovalStatus.running => context.l10n.removeBackground, BackgroundRemovalStatus.applying => context.l10n.backgroundRemovalApplying, BackgroundRemovalStatus.succeeded => context.l10n.backgroundRemovalComplete, BackgroundRemovalStatus.failed => context.l10n.backgroundRemovalFailed, BackgroundRemovalStatus.cancelling => context.l10n.cancelling, BackgroundRemovalStatus.cancelled => context.l10n.cancelled, BackgroundRemovalStatus.interrupted => context.l10n.interruptedTask, }; if (!details) { return _TaskSummary( name: entry.name, status: status, active: active, progress: progressValue, action: active ? TextButton( onPressed: entry.status == BackgroundRemovalStatus.cancelling ? null : () => entry.owner.session.backgroundRemovals.cancel( entry.task.id, ), child: Text(context.l10n.cancel), ) : null, onTap: () => _showTaskDetails( context, session: entry.owner.session, builder: (_) => _RemovalTaskDetails(entry), ), ); } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Text(entry.name, style: Theme.of(context).textTheme.titleSmall), Text( _ownerName(entry.owner), style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: AppSpacing.small), Text(status), if (entry.error case final error?) Text( context.l10n.errorMessage(error), style: TextStyle(color: Theme.of(context).colorScheme.error), ), if (active) ...[ const SizedBox(height: AppSpacing.small), LinearProgressIndicator(value: progressValue), if (progressValue != null) Align( alignment: Alignment.centerRight, child: Text('${(progressValue * 100).floor()}%'), ), Align( alignment: Alignment.centerRight, child: TextButton( onPressed: entry.status == BackgroundRemovalStatus.cancelling ? null : () => entry.owner.session.backgroundRemovals.cancel( entry.task.id, ), child: Text(context.l10n.cancel), ), ), ], ], ); } } class _ResourceDownloadCard extends ConsumerWidget { const _ResourceDownloadCard({ required this.repository, this.install, this.subtitleBundle = false, this.details = false, }) : assert(subtitleBundle || install != null); final ProcessingResourceRepository repository; final ProcessingResourceInstall? install; final bool subtitleBundle; final bool details; @override Widget build(BuildContext context, WidgetRef ref) { final snapshot = ref.watch(processingResourcesProvider(repository)); final install = this.install == null ? null : snapshot.installs .where((item) => item.package.id == this.install!.package.id) .firstOrNull ?? this.install; final downloading = subtitleBundle ? snapshot.subtitleDownloading : install!.state == ProcessingResourceState.downloading; final paused = downloading && (subtitleBundle ? snapshot.subtitlePaused : snapshot.paused.contains(install!.package.capability)); final label = paused ? context.l10n.downloadPaused : subtitleBundle ? downloading ? context.l10n.downloadingResource : context.l10n.backgroundTaskCompleted : switch (install!.state) { ProcessingResourceState.downloading => context.l10n.downloadingResource, ProcessingResourceState.installed => context.l10n.backgroundTaskCompleted, ProcessingResourceState.notInstalled => context.l10n.cancelled, ProcessingResourceState.failed => context.l10n.backgroundTaskFailed, }; final name = subtitleBundle ? context.l10n.subtitleResourceDownloadTask : install!.package.capability == ProcessingCapability.backgroundRemoval ? context.l10n.backgroundRemovalDownloadTask : install.package.name; final downloadedBytes = subtitleBundle ? snapshot.subtitleDownloadedBytes : install!.downloadedBytes; final totalBytes = subtitleBundle ? snapshot.subtitleTotalBytes : install!.package.bytes; Future cancel() async { if (!await confirmResourceDownloadCancellation(context)) return; if (subtitleBundle) { if (repository.subtitleDownloading) { repository.cancelSubtitleResources(); } } else if (repository.installFor(install!.package.capability).state == ProcessingResourceState.downloading) { repository.cancel(install.package.capability); } } Future retry() async { try { await repository.ensureAvailable(install!.package.capability); } catch (_) { // Repository publishes the error in task details. } } void togglePause() { if (subtitleBundle) { if (paused) { repository.resumeSubtitleResources(); } else { repository.pauseSubtitleResources(); } } else if (paused) { repository.resumeDownload(install!.package.capability); } else { repository.pauseDownload(install!.package.capability); } } if (!details) { return _TaskSummary( name: name, status: label, active: downloading, progressDetails: downloading ? ResourceDownloadProgress( downloadedBytes: downloadedBytes, totalBytes: totalBytes, bytesPerSecond: subtitleBundle ? snapshot.subtitleBytesPerSecond : snapshot.rates[install!.package.capability] ?? 0, status: paused ? label : '', paused: paused, ) : null, action: Row( mainAxisSize: MainAxisSize.min, children: [ if (downloading) TextButton( key: const Key('background-download-pause-button'), onPressed: togglePause, child: Text( paused ? context.l10n.resumeDownload : context.l10n.pauseDownload, ), ), TextButton( onPressed: downloading ? cancel : retry, child: Text( downloading ? context.l10n.cancel : context.l10n.retryTask, ), ), ], ), onTap: () { final download = ref.read(subtitleDownloadProvider); final activeDownload = subtitleBundle && download.running && download.request?.session.acceptsEdits == true ? download.request : null; if (activeDownload != null) { showAppDialog( context: context, builder: (_) => TranscriptionDialog.forCurrentTask( session: activeDownload.session, ), ); return; } _showTaskDetails( context, builder: (_) => _ResourceDownloadCard( repository: repository, install: subtitleBundle ? null : repository.installFor(install!.package.capability), subtitleBundle: subtitleBundle, details: true, ), ); }, ); } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Text(name, style: Theme.of(context).textTheme.titleSmall), const SizedBox(height: AppSpacing.small), if (!downloading) Text(label), if (install?.error != null) Text(context.l10n.failureMessage(install!.error!)), if (downloading) ...[ ResourceDownloadProgress( downloadedBytes: downloadedBytes, totalBytes: totalBytes, bytesPerSecond: subtitleBundle ? snapshot.subtitleBytesPerSecond : snapshot.rates[install!.package.capability] ?? 0, status: paused ? label : '', paused: paused, ), ], if (downloading || install?.state == ProcessingResourceState.failed) Align( alignment: Alignment.centerRight, child: Row( mainAxisSize: MainAxisSize.min, children: [ if (downloading) TextButton( onPressed: togglePause, child: Text( paused ? context.l10n.resumeDownload : context.l10n.pauseDownload, ), ), TextButton( onPressed: downloading ? cancel : retry, child: Text( downloading ? context.l10n.cancel : context.l10n.retryTask, ), ), ], ), ), ], ); } } class _SubtitleTaskCard extends ConsumerStatefulWidget { const _SubtitleTaskCard({ super.key, required this.entry, this.details = false, }); final SubtitleTaskEntry entry; EditorTimelineSession get session => entry.owner.session; SubtitleBackgroundTask get job => entry.job; final bool details; TranscriptionClipTarget? get target => job.recognition.command.clipId == null ? null : TranscriptionClipTarget( sequence: job.sequence, clipId: job.recognition.command.clipId!, mediaId: job.recognition.command.mediaId, name: entry.name, audioStream: job.recognition.command.audioStream, ); @override ConsumerState<_SubtitleTaskCard> createState() => _SubtitleTaskCardState(); } class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> { SubtitleTaskActionsProvider get _provider => subtitleTaskActionsProvider(widget.session, widget.job.id); SubtitleTaskActions get _actions => ref.read(_provider.notifier); bool get _picking => ref.read(_provider).isLoading; String? _validationError; String? get _error { final value = ref.read(_provider); if (_validationError != null) return _validationError; if (value.error case SubtitleActionException(:final kind, :final cause)) { if (cause is CommandRejected && cause.code == 'staleVersion') { return context.l10n.timelineChanged; } final message = context.l10n.errorMessage(cause); return switch (kind) { SubtitleActionKind.original => context.l10n.applyCaptionsError(message), SubtitleActionKind.translation => context.l10n.applyTranslatedCaptionsError(message), _ => message, }; } final result = value.value; return switch (result?.kind) { SubtitleActionKind.original => context.l10n.captionsAdded( result!.cueCount.toString(), ), SubtitleActionKind.translation => context.l10n.translatedCaptionsAdded( result!.cueCount.toString(), ), _ => null, }; } Future _applyResult({bool translated = false}) async { if (_picking) return; final job = widget.job; final version = widget.session.version; String? clip = widget.target?.clipId; if (clip == null) { final candidates = await _actions.candidates(job, translated: translated); if (!mounted) return; if (candidates.isEmpty) { setState( () => _validationError = translated ? context.l10n.placeTranslationMediaFirst : context.l10n.placeMediaFirst, ); return; } clip = await showAppDialog( context: context, builder: (context) => AppDialog( title: context.l10n.selectTargetClip, child: Column( mainAxisSize: MainAxisSize.min, children: [ for (final candidate in candidates) AppDialogOption( label: '${candidate.name ?? context.l10n.clip} · ${candidate.id.value}', onPressed: () => Navigator.pop(context, candidate.id.value), ), ], ), ), ); } if (clip == null || !mounted) return; setState(() => _validationError = null); await _actions.apply( job, clip, expectedVersion: version, translated: translated, ); } String _failureMessage(String? code) => switch (code) { 'notConfigured' => context.l10n.transcriptionAccessFailed, 'noAudio' => context.l10n.transcriptionNoAudio, 'invalidResult' => context.l10n.transcriptionInvalidResult, 'workerExited' => context.l10n.transcriptionWorkerExited, 'processingFailed' => context.l10n.transcriptionProcessingFailed, final value? => context.l10n.transcriptionError(value), null => context.l10n.transcriptionFailed, }; Future _action(Future Function() action) async { setState(() => _validationError = null); await action(); if (mounted && !widget.details && _error != null) { ErrorNotificationHost.maybeOf(context) ?.show(ErrorNotification(content: Text(_error!))); } } @override Widget build(BuildContext context) { ref.watch(_provider); final job = widget.job; final taskSession = widget.session; final entry = widget.entry; final total = entry.total; final completed = entry.completed; final value = total == null || total <= 0 || completed == null ? null : (completed / total).clamp(0.0, 1.0); final status = entry.status; final failure = entry.error; final label = switch (status) { TranscriptionStatus.queued => !entry.hasTranslation ? context.l10n.preparingMedia : context.l10n.preparingTranslation, TranscriptionStatus.running => !entry.hasTranslation ? context.l10n.transcribing : context.l10n.translatingCaptions, TranscriptionStatus.cancelling => context.l10n.cancelling, TranscriptionStatus.succeeded => entry.followingUp ? context.l10n.preparingTranslation : context.l10n.captionsGenerated, TranscriptionStatus.failed => failure == 'sourceLanguageUnknown' ? context.l10n.sourceLanguageUnknown : _failureMessage(failure), TranscriptionStatus.cancelled => context.l10n.cancelled, TranscriptionStatus.interrupted => context.l10n.interruptedTask, }; if (!widget.details) { return _TaskSummary( name: entry.name, status: status == TranscriptionStatus.failed ? context.l10n.backgroundTaskFailed : entry.recognitionAvailable && entry.terminal && status == TranscriptionStatus.succeeded ? '$label · ${context.l10n.captionCount(entry.resultCues.length)}' : label, active: !entry.terminal, progress: entry.followingUp && entry.recognitionTerminal ? null : value, action: !entry.terminal ? TextButton( onPressed: _picking ? null : () => _action(() => _actions.cancel(job)), child: Text(context.l10n.cancel), ) : status == TranscriptionStatus.failed || status == TranscriptionStatus.interrupted || status == TranscriptionStatus.cancelled ? TextButton( onPressed: _picking || !taskSession.acceptsEdits ? null : () => _action(() => _actions.retry(job)), child: Text(context.l10n.retryTask), ) : null, onTap: () => _showTaskDetails( context, session: taskSession, builder: (_) => _SubtitleTaskDetails(entry), ), ); } return Column( crossAxisAlignment: CrossAxisAlignment.stretch, mainAxisSize: MainAxisSize.min, children: [ Text(entry.name, style: Theme.of(context).textTheme.titleSmall), Text( _ownerName(entry.owner), style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: AppSpacing.small), Text(label), if (!entry.terminal) ...[ const SizedBox(height: AppSpacing.small), LinearProgressIndicator( value: entry.followingUp && entry.recognitionTerminal ? null : value, ), const SizedBox(height: AppSpacing.small), if (!entry.hasTranslation) Text(context.l10n.recognizedCaptions(entry.recognizedCues)), if (value != null && !(entry.followingUp && entry.recognitionTerminal)) Text('${(value * 100).floor()}%'), if (!entry.hasTranslation && entry.recentCues.isNotEmpty) Text(entry.recentCues.join('\n')), ], Text( '${context.l10n.sourceLanguage}: ${context.l10n.subtitleLanguageName(entry.sourceLanguage)}', ), if (entry.targetLanguage != 'none') Text( '${context.l10n.translationLanguage}: ${context.l10n.subtitleLanguageName(entry.targetLanguage)}', ), if (entry.recognitionAvailable) ...[ Text(context.l10n.captionCount(entry.recognizedCues)), const SizedBox(height: AppSpacing.small), SizedBox( height: 160, child: ListView.builder( primary: false, itemCount: entry.resultCues.length, itemBuilder: (context, index) => Padding( padding: const EdgeInsets.symmetric(vertical: 4), child: SelectableText(entry.resultCues[index]), ), ), ), ], if (_error != null) ...[ const SizedBox(height: AppSpacing.small), Text(_error!), ], Wrap( alignment: WrapAlignment.end, spacing: 8, children: [ if (!entry.terminal) TextButton( onPressed: _picking ? null : () => _action(() => _actions.cancel(job)), child: Text(context.l10n.cancel), ), if (entry.terminal && (status == TranscriptionStatus.failed || status == TranscriptionStatus.interrupted || status == TranscriptionStatus.cancelled)) TextButton( onPressed: _picking || !widget.session.acceptsEdits ? null : () => _action(() => _actions.retry(job)), child: Text(context.l10n.retryTask), ), if (entry.recognitionAvailable) TextButton( onPressed: _picking || !widget.session.acceptsEdits ? null : _applyResult, child: Text(context.l10n.applyOriginalCaptions), ), if (entry.translationAvailable) TextButton( onPressed: _picking || !widget.session.acceptsEdits ? null : () => _applyResult(translated: true), child: Text(context.l10n.applyTranslatedCaptions), ), ], ), ], ); } }