feat: initial Cutdex application

Add the Flutter video editing application with project management, media
import, timeline editing, preview, AI assistance, diagnostics and settings.

Include shared UI and native host packages, platform runners, application
tests and release tooling.

Provide usage and contribution guides, the MIT license and third-party
notices. Exclude local credentials, build outputs and validation data.
This commit is contained in:
lingjhf committed 2026-10-05 23:36:23 +08:00
commit 27e77fff39
718 files changed
+183958

No files matched your search

+134
View File
@@ -0,0 +1,134 @@
import 'dart:math' as math;
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/theme.dart';
class AudioAssetTile extends StatelessWidget {
const AudioAssetTile({
super.key,
required this.asset,
this.showName = true,
this.aspectRatio = 16 / 9,
});
final AssetDocument asset;
final bool showName;
final double aspectRatio;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AspectRatio(
key: ValueKey('audio-cover-${asset.id}'),
aspectRatio: aspectRatio,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: _AudioWaveformCover(asset),
),
),
if (showName) ...[
const SizedBox(height: AppSpacing.small),
Tooltip(
message: asset.name,
child: Text(
asset.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall,
),
),
],
],
);
}
}
class _AudioWaveformCover extends ConsumerWidget {
const _AudioWaveformCover(this.asset);
final AssetDocument asset;
@override
Widget build(BuildContext context, WidgetRef ref) {
final waveform = ref.watch(mediaWaveformProvider(asset)).value;
final theme = Theme.of(context);
if (waveform == null) {
return Center(
child: Icon(
Icons.audio_file_outlined,
size: AppIconSize.emptyState,
color: theme.colorScheme.onSurfaceVariant,
),
);
}
return CustomPaint(
key: ValueKey('audio-waveform-${asset.id}'),
painter: _AudioCoverPainter(
waveform,
theme.extension<TimelineThemeData>()?.audioAccentColor ??
theme.colorScheme.primary,
MediaQuery.devicePixelRatioOf(context),
),
);
}
}
class _AudioCoverPainter extends CustomPainter {
const _AudioCoverPainter(this.waveform, this.color, this.devicePixelRatio);
final TimelineWaveform waveform;
final Color color;
final double devicePixelRatio;
@override
void paint(Canvas canvas, Size size) {
if (size.isEmpty) return;
final columns = math.max(1, (size.width / 2).floor());
final start = waveform.sourceStartSeconds * TimelineClock.ticksPerSecond;
final duration =
waveform.frameCount /
waveform.sampleRate *
TimelineClock.ticksPerSecond;
final paint = Paint()
..color = color
..style = PaintingStyle.fill
..isAntiAlias = false;
final strokePixels = math.max(1, devicePixelRatio.round());
final bottomPixels = math.max(1, (size.height * devicePixelRatio).floor());
for (var column = 0; column < columns; column++) {
final envelope = waveform.envelope(
(start + duration * column / columns).round(),
(start + duration * (column + 1) / columns).round(),
);
final peak = math.max(envelope.minimum.abs(), envelope.maximum.abs());
final height = math.min(size.height, math.max(1.0, peak * size.height));
final x = (column + 0.5) * size.width / columns;
final leftPixels = (x * devicePixelRatio - strokePixels / 2).round();
final topPixels = ((size.height - height) * devicePixelRatio)
.round()
.clamp(0, bottomPixels - 1);
canvas.drawRect(
Rect.fromLTWH(
leftPixels / devicePixelRatio,
topPixels / devicePixelRatio,
strokePixels / devicePixelRatio,
(bottomPixels - topPixels) / devicePixelRatio,
),
paint,
);
}
}
@override
bool shouldRepaint(_AudioCoverPainter oldDelegate) =>
oldDelegate.waveform != waveform ||
oldDelegate.color != color ||
oldDelegate.devicePixelRatio != devicePixelRatio;
}
@@ -0,0 +1,130 @@
import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
part 'background_removal_controller.g.dart';
part 'background_removal_controller.freezed.dart';
enum BackgroundRemovalFailure { download, start, rejected }
@freezed
sealed class BackgroundRemovalState with _$BackgroundRemovalState {
const factory BackgroundRemovalState.idle() = RemovalIdle;
const factory BackgroundRemovalState.downloading() = RemovalDownloading;
const factory BackgroundRemovalState.starting() = RemovalStarting;
const factory BackgroundRemovalState.started() = RemovalStarted;
const factory BackgroundRemovalState.cancelled() = RemovalCancelled;
const factory BackgroundRemovalState.failed(
BackgroundRemovalFailure failure, {
String? message,
}) = RemovalFailed;
}
@riverpod
class BackgroundRemovalController extends _$BackgroundRemovalController {
bool _cancelled = false;
ProcessingResourceRepository? _repository;
@override
BackgroundRemovalState build(
EditorTimelineSession session,
BackgroundRemovalClipTarget target,
) {
ref.onDispose(() {
_cancelled = true;
});
return const BackgroundRemovalState.idle();
}
Future<void> start(
ProcessingResourceRepository repository, {
bool download = false,
}) async {
if (state is RemovalDownloading || state is RemovalStarting) return;
final lease = ref.keepAlive();
final release = session.retainViews();
_repository = repository;
_cancelled = false;
var installed = !download;
state = download
? const BackgroundRemovalState.downloading()
: const BackgroundRemovalState.starting();
try {
if (download) {
await repository.ensureAvailable(
ProcessingCapability.backgroundRemoval,
);
installed = true;
}
if (_cancelled || !ref.mounted || !session.acceptsEdits) return;
state = const BackgroundRemovalState.starting();
final processing = ProcessingConfiguration.configured(
diagnostics: AppDiagnostics.report,
resourcesRoot: repository.root.parent.path,
);
final model = processing?.backgroundRemovalModel;
if (processing == null || model == null) {
throw AppException(AppErrorCode.startBackgroundRemovalFailed);
}
session.backgroundRemovals.configure(
backend: processing.backend.execute,
model: model,
);
await session.backgroundRemovals.start(
sequence: target.sequence,
clipId: target.clipId,
mediaId: target.mediaId,
name: target.name,
backend: processing.backend.execute,
model: model,
);
if (ref.mounted) state = const BackgroundRemovalState.started();
} on ProcessingResourceCancelledException {
if (ref.mounted) state = const BackgroundRemovalState.cancelled();
} on CommandRejected catch (error) {
if (ref.mounted) {
state = BackgroundRemovalState.failed(
BackgroundRemovalFailure.rejected,
message: error.message,
);
}
} catch (_) {
if (ref.mounted) {
state = BackgroundRemovalState.failed(
installed
? BackgroundRemovalFailure.start
: BackgroundRemovalFailure.download,
);
}
} finally {
if (ref.mounted &&
(state is RemovalDownloading || state is RemovalStarting)) {
state = const BackgroundRemovalState.cancelled();
}
_repository = null;
release();
lease.close();
}
}
void cancel(ProcessingResourceRepository repository) {
_cancelled = true;
(_repository ?? repository).cancel(ProcessingCapability.backgroundRemoval);
}
void togglePause(ProcessingResourceRepository repository) {
if (repository.downloadPausedFor(ProcessingCapability.backgroundRemoval)) {
repository.resumeDownload(ProcessingCapability.backgroundRemoval);
} else {
repository.pauseDownload(ProcessingCapability.backgroundRemoval);
}
}
}
@@ -0,0 +1,456 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'background_removal_controller.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$BackgroundRemovalState {
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is BackgroundRemovalState);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState()';
}
}
/// @nodoc
class $BackgroundRemovalStateCopyWith<$Res> {
$BackgroundRemovalStateCopyWith(
BackgroundRemovalState _,
$Res Function(BackgroundRemovalState) __,
);
}
/// Adds pattern-matching-related methods to [BackgroundRemovalState].
extension BackgroundRemovalStatePatterns on BackgroundRemovalState {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(RemovalIdle value)? idle,
TResult Function(RemovalDownloading value)? downloading,
TResult Function(RemovalStarting value)? starting,
TResult Function(RemovalStarted value)? started,
TResult Function(RemovalCancelled value)? cancelled,
TResult Function(RemovalFailed value)? failed,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle(_that);
case RemovalDownloading() when downloading != null:
return downloading(_that);
case RemovalStarting() when starting != null:
return starting(_that);
case RemovalStarted() when started != null:
return started(_that);
case RemovalCancelled() when cancelled != null:
return cancelled(_that);
case RemovalFailed() when failed != null:
return failed(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(RemovalIdle value) idle,
required TResult Function(RemovalDownloading value) downloading,
required TResult Function(RemovalStarting value) starting,
required TResult Function(RemovalStarted value) started,
required TResult Function(RemovalCancelled value) cancelled,
required TResult Function(RemovalFailed value) failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle():
return idle(_that);
case RemovalDownloading():
return downloading(_that);
case RemovalStarting():
return starting(_that);
case RemovalStarted():
return started(_that);
case RemovalCancelled():
return cancelled(_that);
case RemovalFailed():
return failed(_that);
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(RemovalIdle value)? idle,
TResult? Function(RemovalDownloading value)? downloading,
TResult? Function(RemovalStarting value)? starting,
TResult? Function(RemovalStarted value)? started,
TResult? Function(RemovalCancelled value)? cancelled,
TResult? Function(RemovalFailed value)? failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle(_that);
case RemovalDownloading() when downloading != null:
return downloading(_that);
case RemovalStarting() when starting != null:
return starting(_that);
case RemovalStarted() when started != null:
return started(_that);
case RemovalCancelled() when cancelled != null:
return cancelled(_that);
case RemovalFailed() when failed != null:
return failed(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? idle,
TResult Function()? downloading,
TResult Function()? starting,
TResult Function()? started,
TResult Function()? cancelled,
TResult Function(BackgroundRemovalFailure failure, String? message)? failed,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle();
case RemovalDownloading() when downloading != null:
return downloading();
case RemovalStarting() when starting != null:
return starting();
case RemovalStarted() when started != null:
return started();
case RemovalCancelled() when cancelled != null:
return cancelled();
case RemovalFailed() when failed != null:
return failed(_that.failure, _that.message);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() idle,
required TResult Function() downloading,
required TResult Function() starting,
required TResult Function() started,
required TResult Function() cancelled,
required TResult Function(BackgroundRemovalFailure failure, String? message)
failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle():
return idle();
case RemovalDownloading():
return downloading();
case RemovalStarting():
return starting();
case RemovalStarted():
return started();
case RemovalCancelled():
return cancelled();
case RemovalFailed():
return failed(_that.failure, _that.message);
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? idle,
TResult? Function()? downloading,
TResult? Function()? starting,
TResult? Function()? started,
TResult? Function()? cancelled,
TResult? Function(BackgroundRemovalFailure failure, String? message)?
failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle();
case RemovalDownloading() when downloading != null:
return downloading();
case RemovalStarting() when starting != null:
return starting();
case RemovalStarted() when started != null:
return started();
case RemovalCancelled() when cancelled != null:
return cancelled();
case RemovalFailed() when failed != null:
return failed(_that.failure, _that.message);
case _:
return null;
}
}
}
/// @nodoc
class RemovalIdle implements BackgroundRemovalState {
const RemovalIdle();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalIdle);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.idle()';
}
}
/// @nodoc
class RemovalDownloading implements BackgroundRemovalState {
const RemovalDownloading();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalDownloading);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.downloading()';
}
}
/// @nodoc
class RemovalStarting implements BackgroundRemovalState {
const RemovalStarting();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalStarting);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.starting()';
}
}
/// @nodoc
class RemovalStarted implements BackgroundRemovalState {
const RemovalStarted();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalStarted);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.started()';
}
}
/// @nodoc
class RemovalCancelled implements BackgroundRemovalState {
const RemovalCancelled();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalCancelled);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.cancelled()';
}
}
/// @nodoc
class RemovalFailed implements BackgroundRemovalState {
const RemovalFailed(this.failure, {this.message});
final BackgroundRemovalFailure failure;
final String? message;
/// Create a copy of BackgroundRemovalState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$RemovalFailedCopyWith<RemovalFailed> get copyWith =>
_$RemovalFailedCopyWithImpl<RemovalFailed>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is RemovalFailed &&
(identical(other.failure, failure) || other.failure == failure) &&
(identical(other.message, message) || other.message == message));
}
@override
int get hashCode {
return Object.hash(runtimeType, failure, message);
}
@override
String toString() {
return 'BackgroundRemovalState.failed(failure: $failure, message: $message)';
}
}
/// @nodoc
abstract mixin class $RemovalFailedCopyWith<$Res>
implements $BackgroundRemovalStateCopyWith<$Res> {
factory $RemovalFailedCopyWith(
RemovalFailed value,
$Res Function(RemovalFailed) _then,
) = _$RemovalFailedCopyWithImpl;
@useResult
$Res call({BackgroundRemovalFailure failure, String? message});
}
/// @nodoc
class _$RemovalFailedCopyWithImpl<$Res>
implements $RemovalFailedCopyWith<$Res> {
_$RemovalFailedCopyWithImpl(this._self, this._then);
final RemovalFailed _self;
final $Res Function(RemovalFailed) _then;
/// Create a copy of BackgroundRemovalState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
$Res call({Object? failure = null, Object? message = freezed}) {
return _then(
RemovalFailed(
null == failure
? _self.failure
: failure // ignore: cast_nullable_to_non_nullable
as BackgroundRemovalFailure,
message: freezed == message
? _self.message
: message // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
@@ -0,0 +1,124 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'background_removal_controller.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BackgroundRemovalController)
final backgroundRemovalControllerProvider =
BackgroundRemovalControllerFamily._();
final class BackgroundRemovalControllerProvider
extends
$NotifierProvider<BackgroundRemovalController, BackgroundRemovalState> {
BackgroundRemovalControllerProvider._({
required BackgroundRemovalControllerFamily super.from,
required (EditorTimelineSession, BackgroundRemovalClipTarget)
super.argument,
}) : super(
retry: null,
name: r'backgroundRemovalControllerProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$backgroundRemovalControllerHash();
@override
String toString() {
return r'backgroundRemovalControllerProvider'
''
'$argument';
}
@$internal
@override
BackgroundRemovalController create() => BackgroundRemovalController();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(BackgroundRemovalState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<BackgroundRemovalState>(value),
);
}
@override
bool operator ==(Object other) {
return other is BackgroundRemovalControllerProvider &&
other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$backgroundRemovalControllerHash() =>
r'429add9c699b92fdba9c553810f17f4a6859f4e6';
final class BackgroundRemovalControllerFamily extends $Family
with
$ClassFamilyOverride<
BackgroundRemovalController,
BackgroundRemovalState,
BackgroundRemovalState,
BackgroundRemovalState,
(EditorTimelineSession, BackgroundRemovalClipTarget)
> {
BackgroundRemovalControllerFamily._()
: super(
retry: null,
name: r'backgroundRemovalControllerProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BackgroundRemovalControllerProvider call(
EditorTimelineSession session,
BackgroundRemovalClipTarget target,
) => BackgroundRemovalControllerProvider._(
argument: (session, target),
from: this,
);
@override
String toString() => r'backgroundRemovalControllerProvider';
}
abstract class _$BackgroundRemovalController
extends $Notifier<BackgroundRemovalState> {
late final _$args =
ref.$arg as (EditorTimelineSession, BackgroundRemovalClipTarget);
EditorTimelineSession get session => _$args.$1;
BackgroundRemovalClipTarget get target => _$args.$2;
BackgroundRemovalState build(
EditorTimelineSession session,
BackgroundRemovalClipTarget target,
);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref as $Ref<BackgroundRemovalState, BackgroundRemovalState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<BackgroundRemovalState, BackgroundRemovalState>,
BackgroundRemovalState,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
}
}
@@ -0,0 +1,202 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../integrations/runtime/processing_resource_state.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
import 'background_removal_controller.dart';
export 'processing_targets.dart';
class BackgroundRemovalDialog extends ConsumerStatefulWidget {
const BackgroundRemovalDialog({
super.key,
required this.session,
required this.target,
});
final EditorTimelineSession session;
final BackgroundRemovalClipTarget target;
@override
ConsumerState<BackgroundRemovalDialog> createState() =>
_BackgroundRemovalDialogState();
}
class _BackgroundRemovalDialogState
extends ConsumerState<BackgroundRemovalDialog> {
late final VoidCallback _release;
bool _closing = false;
BackgroundRemovalControllerProvider get _provider =>
backgroundRemovalControllerProvider(widget.session, widget.target);
BackgroundRemovalState get _state => ref.read(_provider);
bool get _installing => _state is RemovalDownloading;
bool get _starting => _state is RemovalStarting;
String? get _error => switch (_state) {
RemovalFailed(:final failure, :final message) => switch (failure) {
BackgroundRemovalFailure.download =>
context.l10n.processingResourceDownloadFailed,
BackgroundRemovalFailure.start =>
context.l10n.startBackgroundRemovalFailed,
BackgroundRemovalFailure.rejected => message,
},
_ => null,
};
@override
void initState() {
super.initState();
_release = widget.session.retainViews();
}
@override
void dispose() {
_release();
super.dispose();
}
Future<void> _start(ProcessingResourceRepository repository) =>
ref.read(_provider.notifier).start(repository);
Future<void> _downloadAndStart(ProcessingResourceRepository repository) =>
ref.read(_provider.notifier).start(repository, download: true);
@override
Widget build(BuildContext context) {
ref.watch(_provider);
ref.listen(_provider, (previous, next) {
if (next is! RemovalStarted || _closing) return;
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final message = context.l10n.backgroundRemovalTaskStarted;
Navigator.of(context).pop();
messenger?.showSnackBar(SnackBar(content: Text(message)));
});
});
return ref
.watch(processingResourceRepositoryProvider)
.when(
loading: () => const DelayedLoadingIndicator(
child: AppDialog(
title: '',
width: 520,
child: Center(child: CircularProgressIndicator()),
),
),
error: (_, _) => AppDialog(
title: context.l10n.removeBackground,
width: 520,
child: Text(context.l10n.loadResourceLocationFailed),
),
data: (repository) => Consumer(
builder: (context, ref, _) {
final resources = ref.watch(
processingResourcesProvider(repository),
);
final install =
resources.installs
.where(
(item) =>
item.package.capability ==
ProcessingCapability.backgroundRemoval,
)
.firstOrNull ??
repository.installFor(ProcessingCapability.backgroundRemoval);
final installed =
install.state == ProcessingResourceState.installed ||
ProcessingConfiguration.configured(
resourcesRoot: repository.root.parent.path,
)?.backgroundRemovalModel !=
null;
final downloading =
install.state == ProcessingResourceState.downloading;
if (!installed) {
return ProcessingResourceDownloadDialog(
title: context.l10n.backgroundRemovalDownloadTask,
description: context.l10n.backgroundRemovalResourceRequired,
resourceName: context.l10n.backgroundRemovalResourceName,
downloadSize: context.l10n.subtitleResourcesDownloadSize(
formatResourceBytes(install.package.bytes),
),
downloading: downloading,
paused: resources.paused.contains(
ProcessingCapability.backgroundRemoval,
),
downloadedBytes: install.downloadedBytes,
totalBytes: install.package.bytes,
bytesPerSecond:
resources.rates[ProcessingCapability.backgroundRemoval] ??
0,
error: _error,
downloadButtonKey: const Key(
'download-background-removal-resource',
),
pauseButtonKey: const Key(
'pause-background-removal-resource',
),
backgroundButtonKey: const Key(
'background-background-removal-resource',
),
onCancel: () async {
if (downloading &&
!await confirmResourceDownloadCancellation(context)) {
return;
}
if (!mounted || !context.mounted) return;
if (downloading) {
ref.read(_provider.notifier).cancel(repository);
}
Navigator.of(context).pop();
},
onDownload: () {
if (!_installing && !downloading) {
_downloadAndStart(repository);
}
},
onTogglePause: () =>
ref.read(_provider.notifier).togglePause(repository),
onBackground: () => Navigator.of(context).pop(),
);
}
return AppDialog(
title: context.l10n.removeBackground,
width: 520,
description: context.l10n.backgroundRemovalDestructiveHint,
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(context.l10n.close),
),
FilledButton(
onPressed:
_installing || _starting || !widget.session.acceptsEdits
? null
: () => _start(repository),
child: Text(context.l10n.startBackgroundRemoval),
),
],
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (_error case final error?) ...[
const SizedBox(height: AppSpacing.compact),
Text(error),
],
],
),
);
},
),
);
}
}
@@ -0,0 +1,862 @@
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() ??
<ProcessingResourceInstall>[];
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<void> _showTaskDetails(
BuildContext context, {
required WidgetBuilder builder,
EditorTimelineSession? session,
}) async {
final release = session?.retainViews();
try {
await showAppDialog<void>(
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<void> 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<void> 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<void>(
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<void> _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<String>(
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<void> _action(Future<void> Function() action) async {
setState(() => _validationError = null);
await action();
if (mounted && !widget.details && _error != null) {
ScaffoldMessenger.maybeOf(context)
?.showSnackBar(SnackBar(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),
),
],
),
],
);
}
}
+38
View File
@@ -0,0 +1,38 @@
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
/// Subscribes to one cover frame so loading it only rebuilds its image.
class MediaAssetCover extends ConsumerWidget {
const MediaAssetCover({
super.key,
required this.asset,
required this.fallback,
this.errorFallback,
this.fit = BoxFit.contain,
this.timeMilliseconds = 0,
});
final AssetDocument asset;
final Widget fallback;
final Widget? errorFallback;
final BoxFit fit;
final int timeMilliseconds;
@override
Widget build(BuildContext context, WidgetRef ref) {
final bytes = ref
.watch(mediaCoverProvider(asset, timeMilliseconds: timeMilliseconds))
.value;
return bytes == null
? fallback
: Image.memory(
bytes,
fit: fit,
excludeFromSemantics: true,
errorBuilder: (_, _, _) => errorFallback ?? fallback,
);
}
}
+9
View File
@@ -0,0 +1,9 @@
import 'package:flutter/foundation.dart';
/// Drag data carries identities; feedback switches off inside the timeline.
class MediaAssetDrag {
MediaAssetDrag({required this.projectId, required this.assetId});
final String projectId;
final String assetId;
final feedbackVisible = ValueNotifier<bool>(true);
}
+115
View File
@@ -0,0 +1,115 @@
import 'dart:math' as math;
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/theme.dart';
import 'audio_asset_tile.dart';
import 'media_asset_cover.dart';
/// Compact full-width preview used by the media library's list layout.
class MediaAssetStrip extends StatelessWidget {
const MediaAssetStrip({super.key, required this.asset});
static const height = 46.0;
final AssetDocument asset;
@override
Widget build(BuildContext context) => SizedBox(
height: height,
child: LayoutBuilder(
builder: (context, constraints) {
if (asset.metadata['kind'] == 'audio') {
return AudioAssetTile(
asset: asset,
showName: false,
aspectRatio: constraints.maxWidth / height,
);
}
return _VisualAssetStrip(asset: asset, width: constraints.maxWidth);
},
),
);
}
class _VisualAssetStrip extends ConsumerWidget {
const _VisualAssetStrip({required this.asset, required this.width});
final AssetDocument asset;
final double width;
@override
Widget build(BuildContext context, WidgetRef ref) {
final video = asset.metadata['kind'] == 'video';
final duration = video
? ref.watch(mediaDurationProvider(asset)).value
: null;
final count = (width / (MediaAssetStrip.height * 16 / 9)).ceil().clamp(
1,
16,
);
return ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < count; index++)
Expanded(
child: MediaAssetCover(
asset: asset,
fit: BoxFit.cover,
timeMilliseconds: video && duration != null
? (duration * 1000 * index / count).floor()
: 0,
fallback: const Center(child: Icon(Icons.movie_outlined)),
errorFallback: const Center(
child: Icon(Icons.broken_image_outlined),
),
),
),
],
),
);
}
}
class MediaAssetDuration extends ConsumerWidget {
const MediaAssetDuration({super.key, required this.asset});
final AssetDocument asset;
@override
Widget build(BuildContext context, WidgetRef ref) {
if (!const {'audio', 'video'}.contains(asset.metadata['kind'])) {
return const SizedBox.shrink();
}
final duration = ref.watch(mediaDurationProvider(asset)).value;
if (duration == null) return const SizedBox.shrink();
final seconds = math.max(0, duration.floor());
final hours = seconds ~/ 3600;
final minutes = hours > 0 ? (seconds ~/ 60) % 60 : seconds ~/ 60;
final text =
'${hours > 0 ? '$hours:' : ''}'
'${minutes.toString().padLeft(2, '0')}:'
'${(seconds % 60).toString().padLeft(2, '0')}';
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: .55),
borderRadius: BorderRadius.circular(4),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
child: Text(
text,
key: ValueKey('media-duration-${asset.id}'),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white,
fontFeatures: const [FontFeature.tabularFigures()],
),
),
),
);
}
}
+505
View File
@@ -0,0 +1,505 @@
import 'package:cutdex/errors/app_failure.dart';
import 'dart:math' as math;
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import 'audio_asset_tile.dart';
import 'media_asset_drag.dart';
import 'media_asset_strip.dart';
import 'media_browser_controller.dart';
import 'unavailable_media_placeholder.dart';
import 'visual_asset_tile.dart';
extension MediaFilterLabel on MediaFilter {
String label(BuildContext context) => switch (this) {
MediaFilter.all => context.l10n.all,
MediaFilter.image => context.l10n.picture,
MediaFilter.video => context.l10n.video,
MediaFilter.audio => context.l10n.audio,
};
}
const maximumMediaGridTileWidth = 160.0;
class MediaBrowserBody extends ConsumerStatefulWidget {
const MediaBrowserBody({
super.key,
required this.projectId,
required this.grid,
this.draggable = false,
});
final String projectId;
final bool grid;
final bool draggable;
@override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
}
class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
ref.invalidate(mediaAvailabilityProvider);
}
}
MediaBrowserController get _browser =>
ref.read(mediaBrowserProvider(widget.projectId));
bool get _checkingDrop => _browser.busy;
String? get _selectedAssetId => _browser.selectedAssetId;
set _selectedAssetId(String? value) => _browser.selectedAssetId = value;
MediaFilter get _filter => _browser.filter;
bool get _isGrid => widget.grid;
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
Future<void> _action(Future<bool> Function() action) async {
final ok = await action();
if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
context.l10n.failureMessage(
ref.read(projectsProvider).asData?.value.error ??
const AppFailure(AppErrorCode.operationFailed),
),
),
),
);
}
Future<void> _rename(AssetDocument asset) async {
final controller = TextEditingController(text: asset.name);
final name = await showAppDialog<String>(
context: context,
builder: (context) => AppDialog(
title: context.l10n.renameMedia,
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(context.l10n.cancel),
),
ListenableBuilder(
listenable: controller,
builder: (context, _) => FilledButton(
onPressed: controller.text.trim().isEmpty
? null
: () => Navigator.pop(context, controller.text.trim()),
child: Text(context.l10n.save),
),
),
],
child: AppField(
label: context.l10n.name,
child: TextField(
controller: controller,
autofocus: true,
onSubmitted: (value) {
if (value.trim().isNotEmpty) Navigator.pop(context, value.trim());
},
),
),
),
);
// The route's closing animation can still read its text controller.
await Future<void>.delayed(const Duration(milliseconds: 200));
controller.dispose();
if (!mounted || name == null) return;
await _action(() => _browser.rename(asset, name));
}
Future<void> _remove(AssetDocument asset) async {
final confirmed = await showAppDialog<bool>(
context: context,
builder: (context) => AppDialog(
title: context.l10n.removeMedia,
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(context.l10n.cancel),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
child: Text(context.l10n.remove),
),
],
child: Text(context.l10n.removeMediaConfirmation(asset.name)),
),
);
if (!mounted || confirmed != true) return;
await _action(() => _browser.remove(asset));
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: ref.watch(mediaBrowserProvider(widget.projectId)),
builder: (context, _) => _buildBrowser(context),
);
Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId));
final workspace = ref.watch(projectsProvider).asData?.value;
final active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _filter == MediaFilter.all
? allAssets
: allAssets
.where((asset) => asset.metadata['kind'] == _filter.kind)
.toList();
final timelineId = active ? workspace?.timeline?.id : null;
final timeline = timelineId == null
? null
: ref
.watch(editorTimelineProvider(widget.projectId, timelineId))
.asData
?.value;
return assets.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.medium),
child: Text(
_filter != MediaFilter.all
? context.l10n.noMediaOfType(_filter.label(context))
: _desktop
? context.l10n.dragMediaHint
: context.l10n.noMedia,
textAlign: TextAlign.center,
),
),
)
: LayoutBuilder(
builder: (context, constraints) {
const spacing = AppSpacing.small;
final width = math.max(
1.0,
constraints.maxWidth - AppSpacing.compact * 2,
);
final columns = math.max(
1,
((width + spacing) / (maximumMediaGridTileWidth + spacing))
.ceil(),
);
final tileWidth = (width - spacing * (columns - 1)) / columns;
final textStyle = Theme.of(context).textTheme.bodySmall!;
final labelHeight =
MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) *
(textStyle.height ?? 1.2);
Widget item(BuildContext context, int index) {
final asset = assets[index];
return Consumer(
builder: (context, ref, _) {
final availability = ref
.watch(
mediaAvailabilityProvider(widget.projectId, asset),
)
.asData
?.value;
final unavailable =
availability != null &&
availability != MediaAvailability.available;
return AppContextMenu(
key: ValueKey(('media-menu', asset.id)),
itemsBuilder: (_) {
final available = ref
.read(projectsProvider)
.asData
?.value;
final canEdit =
available?.activeProject?.id == widget.projectId &&
available?.projectBusy == false &&
!_checkingDrop;
final sequence = timeline?.activeSequenceId;
return [
AppMenuItem(
label: context.l10n.addToTimeline,
icon: Icons.add,
onPressed:
canEdit &&
!unavailable &&
sequence != null &&
available?.timeline?.id == timelineId
? () =>
_action(() => _browser.insertAsset(asset))
: null,
),
AppMenuItem(
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
onPressed: canEdit ? () => _rename(asset) : null,
),
AppMenuItem(
label: defaultTargetPlatform == TargetPlatform.macOS
? context.l10n.revealFinder
: context.l10n.revealFileManager,
icon: Icons.folder_open,
onPressed: canEdit && _desktop
? () => _action(() => _browser.reveal(asset))
: null,
),
const AppMenuSeparator(),
AppMenuItem(
label: context.l10n.removeMedia,
icon: Icons.delete_outline,
destructive: true,
onPressed: canEdit ? () => _remove(asset) : null,
),
];
},
child: Listener(
onPointerDown: (event) {
if (event.buttons == 2) {
setState(() => _selectedAssetId = asset.id);
}
},
child: _SelectableAsset(
key: ValueKey(asset.id),
grid: _isGrid,
drag: MediaAssetDrag(
projectId: widget.projectId,
assetId: asset.id,
),
name: asset.name,
draggable:
widget.draggable &&
!workspace!.projectBusy &&
!_checkingDrop &&
!unavailable,
selected: _selectedAssetId == asset.id,
onTap: () => _browser.selectAsset(asset),
child: _assetTile(asset, availability),
),
),
);
},
);
}
return ScrollEdgeFadeBuilder(
key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)),
builder: (controller) => !_isGrid
? ListView.separated(
key: PageStorageKey(('media-list', widget.projectId)),
controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact),
itemCount: assets.length,
itemBuilder: item,
separatorBuilder: (_, _) =>
const SizedBox(height: AppSpacing.small),
)
: GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: spacing,
mainAxisSpacing: AppSpacing.compact,
mainAxisExtent:
tileWidth * 9 / 16 +
AppSpacing.small +
labelHeight +
2,
),
itemCount: assets.length,
itemBuilder: item,
),
);
},
);
}
Widget _assetTile(AssetDocument asset, MediaAvailability? availability) {
final unavailable =
availability != null && availability != MediaAvailability.available;
final cover = unavailable
? AspectRatio(
aspectRatio: 16 / 9,
child: _isGrid
? UnavailableMediaPlaceholder(availability: availability)
: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: Center(
child: Text(
availability == MediaAvailability.missing
? context.l10n.mediaMissing
: context.l10n.mediaUnavailable,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
),
),
)
: !_isGrid &&
const {'audio', 'video', 'image'}.contains(asset.metadata['kind'])
? MediaAssetStrip(asset: asset)
: switch (asset.metadata['kind']) {
'video' ||
'image' => VisualAssetTile(asset: asset, showName: false),
'audio' => AudioAssetTile(asset: asset, showName: false),
_ => AspectRatio(
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: const Icon(Icons.insert_drive_file_outlined),
),
),
};
final name = Tooltip(
// Hover still shows the full name; touch long press belongs to actions.
triggerMode: TooltipTriggerMode.manual,
message: asset.name,
child: Text(
asset.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Stack(
children: [
if (!_isGrid)
SizedBox(height: MediaAssetStrip.height, child: cover)
else
cover,
Positioned(
top: 4,
right: 4,
child: MediaAssetDuration(asset: asset),
),
],
),
),
const SizedBox(height: AppSpacing.small),
name,
],
);
}
}
class _SelectableAsset extends StatelessWidget {
const _SelectableAsset({
super.key,
required this.grid,
required this.selected,
required this.drag,
required this.name,
required this.draggable,
required this.onTap,
required this.child,
});
final bool selected;
final bool grid;
final MediaAssetDrag drag;
final String name;
final bool draggable;
final VoidCallback onTap;
final Widget child;
@override
Widget build(BuildContext context) {
final selectionDecoration = BoxDecoration(
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Theme.of(context).colorScheme.primary),
);
final tile = Semantics(
selected: selected,
child: InkWell(
onTap: onTap,
hoverColor: Colors.transparent,
highlightColor: Colors.transparent,
splashFactory: NoSplash.splashFactory,
child: Stack(
children: [
child,
if (selected && !grid)
Positioned(
top: 0,
left: 0,
right: 0,
height: MediaAssetStrip.height,
child: IgnorePointer(
child: DecoratedBox(decoration: selectionDecoration),
),
),
if (selected && grid)
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: AspectRatio(
aspectRatio: 16 / 9,
child: DecoratedBox(decoration: selectionDecoration),
),
),
),
],
),
),
);
return Draggable<MediaAssetDrag>(
data: drag,
maxSimultaneousDrags: draggable ? 1 : 0,
dragAnchorStrategy: pointerDragAnchorStrategy,
onDragStarted: onTap,
onDragEnd: (_) => drag.feedbackVisible.value = true,
feedback: ValueListenableBuilder<bool>(
valueListenable: drag.feedbackVisible,
builder: (context, visible, child) =>
visible ? child! : const SizedBox.shrink(),
child: Material(
elevation: 4,
color: Theme.of(context).colorScheme.surfaceContainerHigh,
child: SizedBox(
width: 144,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
),
),
),
child: tile,
);
}
}
@@ -0,0 +1,194 @@
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/foundation.dart';
import '../../integrations/platform/file_picker.dart';
import '../../integrations/platform/platform_capabilities.dart';
import '../../workspace/media_file_extensions.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/media_import.dart';
import '../../workspace/media_import_feedback.dart';
import '../../workspace/preview_target.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum MediaFilter {
all(null),
image('image'),
video('video'),
audio('audio');
const MediaFilter(this.kind);
final String? kind;
}
final mediaBrowserProvider = Provider.family<MediaBrowserController, String>((
ref,
projectId,
) {
final controller = MediaBrowserController(ref, projectId);
ref.onDispose(controller.dispose);
return controller;
});
/// Project-specific browsing choices are shared by every media presentation.
class MediaBrowserController extends ChangeNotifier {
MediaBrowserController(this._ref, this.projectId);
final Ref _ref;
final String projectId;
final feedback = MediaImportFeedbackController();
bool _working = false;
bool _disposed = false;
bool get busy =>
_working || _ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get active =>
!_disposed &&
_ref.mounted &&
_ref.read(projectsProvider).value?.activeProject?.id == projectId;
bool get canEdit =>
active &&
_ref.read(projectsProvider).value?.projectBusy == false &&
!busy;
bool get canImport =>
canEdit && _ref.read(platformCapabilitiesProvider).localFileSelection;
Future<ExternalMediaSelection?> pickFiles() => _import(
() => _ref
.read(filePickerProvider)
.pickFiles(allowedExtensions: selectableMediaFileExtensions),
);
Future<ExternalMediaSelection?> importFiles(List<ExternalMediaFile> files) =>
_import(() async => files);
Future<ExternalMediaSelection?> _import(
Future<List<ExternalMediaFile>> Function() select,
) async {
if (!canImport) return null;
_working = true;
notifyListeners();
try {
final files = await select();
if (!active ||
files.isEmpty ||
_ref.read(projectsProvider).value?.projectBusy != false) {
return null;
}
final result = await _ref
.read(externalMediaImportProvider(projectId).notifier)
.importFiles(files);
final asset = result?.selected.firstOrNull;
if (!_disposed && asset != null) {
_selectedAssetId = asset.id;
if (_filter != MediaFilter.all &&
asset.metadata['kind'] != _filter.kind) {
_filter = MediaFilter.all;
}
}
if (!_disposed) feedback.recordResult(result);
return result;
} catch (_) {
if (!_disposed) feedback.recordFailure();
rethrow;
} finally {
_working = false;
if (!_disposed) notifyListeners();
}
}
void selectAsset(AssetDocument asset) {
selectedAssetId = asset.id;
_ref.invalidate(mediaAvailabilityProvider(projectId, asset));
final timeline = _ref.read(projectsProvider).value?.timeline;
if (timeline != null) {
_ref
.read(previewNavigationProvider(projectId, timeline.id).notifier)
.showAsset(asset);
}
}
Future<bool> rename(AssetDocument asset, String name) async =>
canEdit &&
await _ref
.read(projectsProvider.notifier)
.editMediaAsset(projectId, asset.id, name: name);
Future<bool> remove(AssetDocument asset) async {
if (!canEdit) return false;
final removed = await _ref
.read(projectsProvider.notifier)
.editMediaAsset(projectId, asset.id);
if (removed && !_disposed && _selectedAssetId == asset.id) {
selectedAssetId = null;
}
return removed;
}
Future<bool> reveal(AssetDocument asset) async =>
canEdit &&
await _ref
.read(projectsProvider.notifier)
.revealMediaAsset(projectId, asset);
Future<bool> insertAsset(AssetDocument asset) async {
if (!canEdit ||
_ref.read(mediaAvailabilityProvider(projectId, asset)).value !=
MediaAvailability.available) {
return false;
}
final timelineId = _ref.read(projectsProvider).value?.timeline?.id;
if (timelineId == null) return false;
final session = _ref
.read(editorTimelineProvider(projectId, timelineId))
.value;
final sequence = session?.activeSequenceId;
if (session == null || sequence == null) return false;
final inserted = await _ref
.read(projectsProvider.notifier)
.insertTimelineAsset(
projectId: projectId,
session: session,
sequenceId: sequence,
assetId: asset.id,
position: session.view(sequence).playheadTick,
);
if (inserted && active) {
_ref
.read(previewNavigationProvider(projectId, timelineId).notifier)
.showTimeline();
}
return inserted;
}
@override
void dispose() {
_disposed = true;
feedback.dispose();
super.dispose();
}
String? _selectedAssetId;
MediaFilter _filter = MediaFilter.all;
bool _grid = true;
String? get selectedAssetId => _selectedAssetId;
MediaFilter get filter => _filter;
bool get grid => _grid;
set selectedAssetId(String? value) {
_selectedAssetId = value;
notifyListeners();
}
set filter(MediaFilter value) {
_filter = value;
notifyListeners();
}
set grid(bool value) {
_grid = value;
notifyListeners();
}
}
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/media_import.dart';
import '../../workspace/media_import_feedback.dart';
import 'media_browser_controller.dart';
Future<void> pickMediaFiles(MediaBrowserController browser) async {
try {
await browser.pickFiles();
} catch (_) {
// The controller retains the failure for its next visible presentation.
}
}
Future<void> importMediaFiles(
MediaBrowserController browser,
List<ExternalMediaFile> files,
) async {
try {
await browser.importFiles(files);
} catch (_) {
// The controller retains the failure for its next visible presentation.
}
}
class MediaImportFeedbackListener extends StatefulWidget {
const MediaImportFeedbackListener({
super.key,
required this.feedback,
required this.child,
});
final MediaImportFeedbackController feedback;
final Widget child;
@override
State<MediaImportFeedbackListener> createState() =>
_MediaImportFeedbackListenerState();
}
class _MediaImportFeedbackListenerState
extends State<MediaImportFeedbackListener> {
bool _scheduled = false;
bool get _visible =>
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
@override
void initState() {
super.initState();
widget.feedback.addListener(_schedule);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_schedule();
}
@override
void didUpdateWidget(covariant MediaImportFeedbackListener oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.feedback != widget.feedback) {
oldWidget.feedback.removeListener(_schedule);
widget.feedback.addListener(_schedule);
}
_schedule();
}
void _schedule() {
if (_scheduled || !widget.feedback.hasPending) return;
_scheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false;
if (!mounted || !_visible || !widget.feedback.hasPending) return;
final messenger = ScaffoldMessenger.maybeOf(context);
if (messenger == null) return;
for (final result in widget.feedback.takePending()) {
final messages = [
if (result == null) context.l10n.operationFailed,
for (final failure
in result?.result?.failures ?? <MediaImportFailure>[])
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
if (result?.failed == true) context.l10n.noImportableFiles,
];
messenger.showSnackBar(
SnackBar(
content: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(child: Text(messages.join('\n'))),
),
),
);
}
});
WidgetsBinding.instance.ensureVisualUpdate();
}
@override
void dispose() {
widget.feedback.removeListener(_schedule);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
+168
View File
@@ -0,0 +1,168 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
class MediaBrowserPage extends StatelessWidget {
const MediaBrowserPage({super.key, required this.projectId});
final String projectId;
@override
Widget build(BuildContext context) => TouchMediaBrowser(
key: const Key('media-browser-page'),
projectId: projectId,
);
}
class MediaBrowserDrawer extends StatelessWidget {
const MediaBrowserDrawer({super.key, required this.projectId});
final String projectId;
@override
Widget build(BuildContext context) => TouchMediaBrowser(
key: const Key('media-browser-drawer'),
projectId: projectId,
);
}
/// Touch controls share browser commands and item components with desktop.
class TouchMediaBrowser extends ConsumerWidget {
const TouchMediaBrowser({super.key, required this.projectId});
final String projectId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
final workspace = ref.watch(projectsProvider).value;
final timelineId = workspace?.activeProject?.id == projectId
? workspace?.timeline?.id
: null;
final timeline = timelineId == null
? null
: ref.watch(editorTimelineProvider(projectId, timelineId)).value;
return ListenableBuilder(
listenable: browser,
builder: (context, _) {
final selected = workspace?.assets
.where((asset) => asset.id == browser.selectedAssetId)
.firstOrNull;
final availability = selected == null
? null
: ref.watch(mediaAvailabilityProvider(projectId, selected)).value;
final canInsert =
browser.canEdit &&
selected != null &&
timeline?.activeSequenceId != null &&
availability == MediaAvailability.available;
return MediaImportFeedbackListener(
feedback: browser.feedback,
child: Material(
key: const Key('media-panel-surface'),
child: Column(
children: [
SizedBox(
key: const Key('media-panel-header'),
height: 56,
child: Row(
children: [
SizedBox.square(
dimension: 48,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: browser.canImport
? () => pickMediaFiles(browser)
: null,
icon: const Icon(Icons.add),
),
),
Expanded(
child: DropdownButton<MediaFilter>(
key: const Key('media-category-picker'),
isExpanded: true,
underline: const SizedBox.shrink(),
value: browser.filter,
items: [
for (final filter in MediaFilter.values)
DropdownMenuItem(
value: filter,
child: Text(filter.label(context)),
),
],
onChanged: (filter) {
if (filter != null) browser.filter = filter;
},
),
),
SizedBox.square(
dimension: 48,
child: IconButton(
key: const Key('media-layout-toggle'),
tooltip: browser.grid
? context.l10n.listLayout
: context.l10n.gridLayout,
icon: Icon(
browser.grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
),
onPressed: () => browser.grid = !browser.grid,
),
),
],
),
),
if (browser.busy) const LinearProgressIndicator(),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
projectId: projectId,
grid: browser.grid,
),
),
Padding(
padding: const EdgeInsets.all(8),
child: SizedBox(
width: double.infinity,
child: FilledButton.icon(
key: const Key('media-add-selected'),
style: FilledButton.styleFrom(
minimumSize: const Size(0, 48),
),
onPressed: !canInsert
? null
: () async {
final inserted = await browser.insertAsset(
selected,
);
if (!inserted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(context.l10n.operationFailed),
),
);
}
},
icon: const Icon(Icons.add),
label: Text(
context.l10n.addToTimeline,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
),
);
},
);
}
}
+213
View File
@@ -0,0 +1,213 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/projects.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
/// Desktop presentation owns compact controls and native file dragging.
class MediaPanel extends ConsumerStatefulWidget {
const MediaPanel({
super.key,
required this.projectId,
this.backgroundColor,
this.grid,
this.onGridChanged,
}) : assert((grid == null) == (onGridChanged == null));
final String projectId;
final Color? backgroundColor;
final bool? grid;
final ValueChanged<bool>? onGridChanged;
@override
ConsumerState<MediaPanel> createState() => _MediaPanelState();
}
class _MediaPanelState extends ConsumerState<MediaPanel> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
ref.watch(projectsProvider);
final browser = ref.watch(mediaBrowserProvider(widget.projectId));
ref.watch(externalMediaImportProvider(widget.projectId));
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableBuilder(
listenable: browser,
builder: (context, _) {
final grid = widget.grid ?? browser.grid;
final visible =
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
final enabled = browser.canImport && visible;
void toggleGrid() {
final next = !grid;
if (widget.onGridChanged case final onChanged?) {
onChanged(next);
} else {
browser.grid = next;
}
}
final content = MediaImportFeedbackListener(
feedback: browser.feedback,
child: Material(
key: const Key('media-panel-surface'),
color: widget.backgroundColor,
child: Stack(
fit: StackFit.expand,
children: [
Column(
children: [
SizedBox(
key: const Key('media-panel-header'),
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 180;
final controls = Row(
mainAxisSize: compact
? MainAxisSize.min
: MainAxisSize.max,
children: [
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(
context,
),
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
label: Text(context.l10n.importMedia),
),
),
if (compact)
const SizedBox(width: AppSpacing.tiny)
else
const Spacer(),
SizedBox(
width: 76,
child: AppSelect<MediaFilter>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.mediaCategory,
outlined: false,
controlHeight: AppControlSize.headerButton,
textStyle: AppTheme.toolbarTextStyle(
context,
),
value: browser.filter,
onChanged: (value) =>
browser.filter = value,
options: [
for (final filter in MediaFilter.values)
AppSelectOption(
filter,
filter.label(context),
),
],
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: toggleGrid,
icon: Icon(
grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
);
return compact
? SingleChildScrollView(
key: const Key('media-header-scroll'),
scrollDirection: Axis.horizontal,
child: controls,
)
: controls;
},
),
),
),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
projectId: widget.projectId,
grid: grid,
draggable: true,
),
),
],
),
if (browser.busy)
const DelayedLoadingIndicator(
child: Align(
alignment: Alignment.topCenter,
child: LinearProgressIndicator(),
),
),
if (_hovering && enabled)
const DropToAddOverlay(key: Key('media-drop-highlight')),
],
),
),
);
if (!nativeDrop) return content;
return NativeProjectDropRegion(
enabled: visible && browser.active && (enabled || browser.busy),
onEnter: (_) {
if (enabled) setState(() => _hovering = true);
},
onExit: () {
if (mounted && _hovering) setState(() => _hovering = false);
},
onDrop: (files) async {
setState(() => _hovering = false);
await importMediaFiles(browser, files);
},
child: content,
);
},
);
}
}
@@ -0,0 +1,26 @@
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'processing_targets.freezed.dart';
/// A fixed timeline target, retained even if selection or active sequence changes.
@freezed
abstract class TranscriptionClipTarget with _$TranscriptionClipTarget {
const factory TranscriptionClipTarget({
required SequenceId sequence,
required String clipId,
required String mediaId,
required String name,
required int audioStream,
}) = _TranscriptionClipTarget;
}
@freezed
abstract class BackgroundRemovalClipTarget with _$BackgroundRemovalClipTarget {
const factory BackgroundRemovalClipTarget({
required SequenceId sequence,
required String clipId,
required String mediaId,
required String name,
}) = _BackgroundRemovalClipTarget;
}
@@ -0,0 +1,855 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'processing_targets.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$TranscriptionClipTarget {
SequenceId get sequence;
String get clipId;
String get mediaId;
String get name;
int get audioStream;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$TranscriptionClipTargetCopyWith<TranscriptionClipTarget> get copyWith =>
_$TranscriptionClipTargetCopyWithImpl<TranscriptionClipTarget>(
this as TranscriptionClipTarget,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as TranscriptionClipTarget;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is TranscriptionClipTarget &&
(identical(other.sequence, _this.sequence) ||
other.sequence == _this.sequence) &&
(identical(other.clipId, _this.clipId) ||
other.clipId == _this.clipId) &&
(identical(other.mediaId, _this.mediaId) ||
other.mediaId == _this.mediaId) &&
(identical(other.name, _this.name) || other.name == _this.name) &&
(identical(other.audioStream, _this.audioStream) ||
other.audioStream == _this.audioStream));
}
@override
int get hashCode {
final _this = this as TranscriptionClipTarget;
return Object.hash(
runtimeType,
_this.sequence,
_this.clipId,
_this.mediaId,
_this.name,
_this.audioStream,
);
}
@override
String toString() {
final _this = this as TranscriptionClipTarget;
return 'TranscriptionClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name}, audioStream: ${_this.audioStream})';
}
}
/// @nodoc
abstract mixin class $TranscriptionClipTargetCopyWith<$Res> {
factory $TranscriptionClipTargetCopyWith(
TranscriptionClipTarget value,
$Res Function(TranscriptionClipTarget) _then,
) = _$TranscriptionClipTargetCopyWithImpl;
@useResult
$Res call({
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
});
}
/// @nodoc
class _$TranscriptionClipTargetCopyWithImpl<$Res>
implements $TranscriptionClipTargetCopyWith<$Res> {
_$TranscriptionClipTargetCopyWithImpl(this._self, this._then);
final TranscriptionClipTarget _self;
final $Res Function(TranscriptionClipTarget) _then;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
Object? audioStream = null,
}) {
return _then(
TranscriptionClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
audioStream: null == audioStream
? _self.audioStream
: audioStream // ignore: cast_nullable_to_non_nullable
as int,
),
);
}
}
/// Adds pattern-matching-related methods to [TranscriptionClipTarget].
extension TranscriptionClipTargetPatterns on TranscriptionClipTarget {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_TranscriptionClipTarget value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_TranscriptionClipTarget value) $default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_TranscriptionClipTarget value)? $default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
_that.audioStream,
);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
)
$default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget():
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
_that.audioStream,
);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
)?
$default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
_that.audioStream,
);
case _:
return null;
}
}
}
/// @nodoc
class _TranscriptionClipTarget implements TranscriptionClipTarget {
const _TranscriptionClipTarget({
required this.sequence,
required this.clipId,
required this.mediaId,
required this.name,
required this.audioStream,
});
@override
final SequenceId sequence;
@override
final String clipId;
@override
final String mediaId;
@override
final String name;
@override
final int audioStream;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$TranscriptionClipTargetCopyWith<_TranscriptionClipTarget> get copyWith =>
__$TranscriptionClipTargetCopyWithImpl<_TranscriptionClipTarget>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _TranscriptionClipTarget &&
(identical(other.sequence, sequence) ||
other.sequence == sequence) &&
(identical(other.clipId, clipId) || other.clipId == clipId) &&
(identical(other.mediaId, mediaId) || other.mediaId == mediaId) &&
(identical(other.name, name) || other.name == name) &&
(identical(other.audioStream, audioStream) ||
other.audioStream == audioStream));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
sequence,
clipId,
mediaId,
name,
audioStream,
);
}
@override
String toString() {
return 'TranscriptionClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name, audioStream: $audioStream)';
}
}
/// @nodoc
abstract mixin class _$TranscriptionClipTargetCopyWith<$Res>
implements $TranscriptionClipTargetCopyWith<$Res> {
factory _$TranscriptionClipTargetCopyWith(
_TranscriptionClipTarget value,
$Res Function(_TranscriptionClipTarget) _then,
) = __$TranscriptionClipTargetCopyWithImpl;
@override
@useResult
$Res call({
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
});
}
/// @nodoc
class __$TranscriptionClipTargetCopyWithImpl<$Res>
implements _$TranscriptionClipTargetCopyWith<$Res> {
__$TranscriptionClipTargetCopyWithImpl(this._self, this._then);
final _TranscriptionClipTarget _self;
final $Res Function(_TranscriptionClipTarget) _then;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
Object? audioStream = null,
}) {
return _then(
_TranscriptionClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
audioStream: null == audioStream
? _self.audioStream
: audioStream // ignore: cast_nullable_to_non_nullable
as int,
),
);
}
}
/// @nodoc
mixin _$BackgroundRemovalClipTarget {
SequenceId get sequence;
String get clipId;
String get mediaId;
String get name;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$BackgroundRemovalClipTargetCopyWith<BackgroundRemovalClipTarget>
get copyWith =>
_$BackgroundRemovalClipTargetCopyWithImpl<BackgroundRemovalClipTarget>(
this as BackgroundRemovalClipTarget,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as BackgroundRemovalClipTarget;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is BackgroundRemovalClipTarget &&
(identical(other.sequence, _this.sequence) ||
other.sequence == _this.sequence) &&
(identical(other.clipId, _this.clipId) ||
other.clipId == _this.clipId) &&
(identical(other.mediaId, _this.mediaId) ||
other.mediaId == _this.mediaId) &&
(identical(other.name, _this.name) || other.name == _this.name));
}
@override
int get hashCode {
final _this = this as BackgroundRemovalClipTarget;
return Object.hash(
runtimeType,
_this.sequence,
_this.clipId,
_this.mediaId,
_this.name,
);
}
@override
String toString() {
final _this = this as BackgroundRemovalClipTarget;
return 'BackgroundRemovalClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name})';
}
}
/// @nodoc
abstract mixin class $BackgroundRemovalClipTargetCopyWith<$Res> {
factory $BackgroundRemovalClipTargetCopyWith(
BackgroundRemovalClipTarget value,
$Res Function(BackgroundRemovalClipTarget) _then,
) = _$BackgroundRemovalClipTargetCopyWithImpl;
@useResult
$Res call({SequenceId sequence, String clipId, String mediaId, String name});
}
/// @nodoc
class _$BackgroundRemovalClipTargetCopyWithImpl<$Res>
implements $BackgroundRemovalClipTargetCopyWith<$Res> {
_$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then);
final BackgroundRemovalClipTarget _self;
final $Res Function(BackgroundRemovalClipTarget) _then;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
}) {
return _then(
BackgroundRemovalClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
),
);
}
}
/// Adds pattern-matching-related methods to [BackgroundRemovalClipTarget].
extension BackgroundRemovalClipTargetPatterns on BackgroundRemovalClipTarget {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_BackgroundRemovalClipTarget value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_BackgroundRemovalClipTarget value) $default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_BackgroundRemovalClipTarget value)? $default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
)
$default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget():
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
)?
$default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
);
case _:
return null;
}
}
}
/// @nodoc
class _BackgroundRemovalClipTarget implements BackgroundRemovalClipTarget {
const _BackgroundRemovalClipTarget({
required this.sequence,
required this.clipId,
required this.mediaId,
required this.name,
});
@override
final SequenceId sequence;
@override
final String clipId;
@override
final String mediaId;
@override
final String name;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$BackgroundRemovalClipTargetCopyWith<_BackgroundRemovalClipTarget>
get copyWith =>
__$BackgroundRemovalClipTargetCopyWithImpl<_BackgroundRemovalClipTarget>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _BackgroundRemovalClipTarget &&
(identical(other.sequence, sequence) ||
other.sequence == sequence) &&
(identical(other.clipId, clipId) || other.clipId == clipId) &&
(identical(other.mediaId, mediaId) || other.mediaId == mediaId) &&
(identical(other.name, name) || other.name == name));
}
@override
int get hashCode {
return Object.hash(runtimeType, sequence, clipId, mediaId, name);
}
@override
String toString() {
return 'BackgroundRemovalClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name)';
}
}
/// @nodoc
abstract mixin class _$BackgroundRemovalClipTargetCopyWith<$Res>
implements $BackgroundRemovalClipTargetCopyWith<$Res> {
factory _$BackgroundRemovalClipTargetCopyWith(
_BackgroundRemovalClipTarget value,
$Res Function(_BackgroundRemovalClipTarget) _then,
) = __$BackgroundRemovalClipTargetCopyWithImpl;
@override
@useResult
$Res call({SequenceId sequence, String clipId, String mediaId, String name});
}
/// @nodoc
class __$BackgroundRemovalClipTargetCopyWithImpl<$Res>
implements _$BackgroundRemovalClipTargetCopyWith<$Res> {
__$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then);
final _BackgroundRemovalClipTarget _self;
final $Res Function(_BackgroundRemovalClipTarget) _then;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
}) {
return _then(
_BackgroundRemovalClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
),
);
}
}
+267
View File
@@ -0,0 +1,267 @@
import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
part 'subtitle_download.g.dart';
part 'subtitle_download.freezed.dart';
enum SubtitleStartFailure { start, download, engine }
@freezed
abstract class SubtitleRequest with _$SubtitleRequest {
const factory SubtitleRequest({
required EditorTimelineSession session,
required SequenceId? sequence,
AssetDocument? asset,
TranscriptionClipTarget? target,
@Default('auto') String language,
@Default('none') String targetLanguage,
}) = _SubtitleRequest;
}
@freezed
sealed class SubtitleDownloadState with _$SubtitleDownloadState {
const SubtitleDownloadState._();
const factory SubtitleDownloadState.idle() = SubtitleIdle;
const factory SubtitleDownloadState.starting(SubtitleRequest request) =
SubtitleStarting;
const factory SubtitleDownloadState.downloading(
SubtitleRequest request, {
required ProcessingCapability stage,
ProcessingResourceRepository? repository,
@Default(0) double progress,
@Default(false) bool paused,
}) = SubtitleDownloading;
const factory SubtitleDownloadState.started(SubtitleRequest request) =
SubtitleStarted;
const factory SubtitleDownloadState.cancelled(SubtitleRequest request) =
SubtitleCancelled;
const factory SubtitleDownloadState.failed(
SubtitleRequest request,
SubtitleStartFailure failure,
) = SubtitleFailed;
SubtitleRequest? get request => switch (this) {
SubtitleIdle() => null,
SubtitleStarting(:final request) ||
SubtitleDownloading(:final request) ||
SubtitleStarted(:final request) ||
SubtitleCancelled(:final request) ||
SubtitleFailed(:final request) => request,
};
bool get running => this is SubtitleStarting || this is SubtitleDownloading;
}
/// Owns the download and task handoff even when its dialog is closed.
@Riverpod(keepAlive: true)
class SubtitleDownload extends _$SubtitleDownload {
ProcessingResourceRepository? _repository;
bool _cancelled = false;
@override
SubtitleDownloadState build() {
ref.onDispose(() {
_cancelled = true;
_repository?.cancelSubtitleResources();
});
return const SubtitleDownloadState.idle();
}
Future<void> start(SubtitleRequest request, {bool download = false}) async {
if (state.running) return;
_cancelled = false;
var resourceInstalled = false;
final session = request.session;
final release = session.retainViews();
state = download
? SubtitleDownloadState.downloading(
request,
stage: session.transcriptions?.recognitionAvailable == true
? ProcessingCapability.translation
: ProcessingCapability.transcription,
)
: SubtitleDownloadState.starting(request);
ProcessingResourceRepository? repository;
void changed() {
if (!ref.mounted || state is! SubtitleDownloading) return;
final current = state as SubtitleDownloading;
state = current.copyWith(
paused: repository?.subtitlePaused ?? current.paused,
);
}
try {
final service = session.transcriptions;
if (download) {
final loaded = await ref.read(
processingResourceRepositoryProvider.future,
);
repository = loaded;
if (_cancelled || !ref.mounted) {
return;
}
_repository = loaded;
final pausedBeforeLoad = (state as SubtitleDownloading).paused;
state = (state as SubtitleDownloading).copyWith(repository: loaded);
loaded.addListener(changed);
final install = loaded.ensureSubtitleResources(
available: {
if (service?.recognitionAvailable == true)
ProcessingCapability.transcription,
if (service?.translationAvailable == true)
ProcessingCapability.translation,
},
onProgress: (stage, progress) {
if (!ref.mounted) return;
if (state case SubtitleDownloading(:final paused)) {
state = SubtitleDownloadState.downloading(
request,
stage: stage,
repository: loaded,
progress: progress,
paused: paused,
);
}
},
);
if (pausedBeforeLoad) loaded.pauseSubtitleResources();
await install;
resourceInstalled = true;
if (_cancelled || !ref.mounted) {
return;
}
final processing = ProcessingConfiguration.configured(
diagnostics: AppDiagnostics.report,
resourcesRoot: loaded.root.parent.path,
);
final speechBackend = service?.backend ?? processing?.backend;
final speechModel =
service?.modelDirectory ?? processing?.transcriptionModel;
final translationBackend =
service?.translationBackend ?? processing?.backend;
final translationModel =
service?.translationModel ?? processing?.translationModel;
if (speechBackend == null ||
speechModel == null ||
translationBackend == null ||
translationModel == null) {
throw AppException(AppErrorCode.subtitleEngineUnavailable);
}
session.configureProcessing(
transcriptionBackend: speechBackend,
transcriptionModel: speechModel,
translationBackend: translationBackend,
translationModel: translationModel,
);
}
if (_cancelled || !ref.mounted) {
return;
}
await _startSubtitles(request);
if (ref.mounted) state = SubtitleDownloadState.started(request);
} on ProcessingResourceCancelledException {
if (ref.mounted) state = SubtitleDownloadState.cancelled(request);
} catch (_) {
if (ref.mounted) {
state = SubtitleDownloadState.failed(
request,
!download
? SubtitleStartFailure.start
: resourceInstalled
? SubtitleStartFailure.engine
: SubtitleStartFailure.download,
);
}
} finally {
repository?.removeListener(changed);
_repository = null;
if (ref.mounted && _cancelled && state.running) {
state = SubtitleDownloadState.cancelled(request);
}
release();
}
}
void togglePause() {
if (state case SubtitleDownloading(:final paused)) {
state = (state as SubtitleDownloading).copyWith(paused: !paused);
if (paused) {
_repository?.resumeSubtitleResources();
} else {
_repository?.pauseSubtitleResources();
}
}
}
void cancel() {
if (!state.running) return;
_cancelled = true;
_repository?.cancelSubtitleResources();
}
}
Future<void> _startSubtitles(SubtitleRequest request) async {
final mediaId = request.target?.mediaId ?? request.asset?.id;
final name = request.target?.name ?? request.asset?.name ?? mediaId;
final sequence = request.sequence;
if (sequence == null || mediaId == null || name == null) {
throw const CommandRejected(
'missingSequence',
'Sequence or media does not exist',
);
}
await request.session.subtitleWorkflows.start(
sequence: sequence,
command: StartTranscription(
mediaId: mediaId,
clipId: request.target?.clipId,
audioStream: request.target?.audioStream ?? 0,
language: request.language,
),
name: name,
targetLanguage: request.targetLanguage,
);
}
/// Configured sessions can start independently of another project's download.
@riverpod
class SubtitleStart extends _$SubtitleStart {
@override
SubtitleDownloadState build(EditorTimelineSession session) =>
const SubtitleDownloadState.idle();
void reset() {
if (!state.running) state = const SubtitleDownloadState.idle();
}
Future<void> start(SubtitleRequest request) async {
if (state.running) return;
final lease = ref.keepAlive();
final release = session.retainViews();
state = SubtitleDownloadState.starting(request);
try {
await _startSubtitles(request);
if (ref.mounted) state = SubtitleDownloadState.started(request);
} catch (_) {
if (ref.mounted) {
state = SubtitleDownloadState.failed(
request,
SubtitleStartFailure.start,
);
}
} finally {
release();
lease.close();
}
}
}
File diff suppressed because it is too large. Load diff
+174
View File
@@ -0,0 +1,174 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'subtitle_download.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Owns the download and task handoff even when its dialog is closed.
@ProviderFor(SubtitleDownload)
final subtitleDownloadProvider = SubtitleDownloadProvider._();
/// Owns the download and task handoff even when its dialog is closed.
final class SubtitleDownloadProvider
extends $NotifierProvider<SubtitleDownload, SubtitleDownloadState> {
/// Owns the download and task handoff even when its dialog is closed.
SubtitleDownloadProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'subtitleDownloadProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$subtitleDownloadHash();
@$internal
@override
SubtitleDownload create() => SubtitleDownload();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SubtitleDownloadState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SubtitleDownloadState>(value),
);
}
}
String _$subtitleDownloadHash() => r'2bf89e93b596e3b24f3880279477c91227b261b4';
/// Owns the download and task handoff even when its dialog is closed.
abstract class _$SubtitleDownload extends $Notifier<SubtitleDownloadState> {
SubtitleDownloadState build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<SubtitleDownloadState, SubtitleDownloadState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<SubtitleDownloadState, SubtitleDownloadState>,
SubtitleDownloadState,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
/// Configured sessions can start independently of another project's download.
@ProviderFor(SubtitleStart)
final subtitleStartProvider = SubtitleStartFamily._();
/// Configured sessions can start independently of another project's download.
final class SubtitleStartProvider
extends $NotifierProvider<SubtitleStart, SubtitleDownloadState> {
/// Configured sessions can start independently of another project's download.
SubtitleStartProvider._({
required SubtitleStartFamily super.from,
required EditorTimelineSession super.argument,
}) : super(
retry: null,
name: r'subtitleStartProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$subtitleStartHash();
@override
String toString() {
return r'subtitleStartProvider'
''
'($argument)';
}
@$internal
@override
SubtitleStart create() => SubtitleStart();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SubtitleDownloadState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SubtitleDownloadState>(value),
);
}
@override
bool operator ==(Object other) {
return other is SubtitleStartProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$subtitleStartHash() => r'3278b419fd819fa4dcc021815280cc1cce72dbb5';
/// Configured sessions can start independently of another project's download.
final class SubtitleStartFamily extends $Family
with
$ClassFamilyOverride<
SubtitleStart,
SubtitleDownloadState,
SubtitleDownloadState,
SubtitleDownloadState,
EditorTimelineSession
> {
SubtitleStartFamily._()
: super(
retry: null,
name: r'subtitleStartProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
/// Configured sessions can start independently of another project's download.
SubtitleStartProvider call(EditorTimelineSession session) =>
SubtitleStartProvider._(argument: session, from: this);
@override
String toString() => r'subtitleStartProvider';
}
/// Configured sessions can start independently of another project's download.
abstract class _$SubtitleStart extends $Notifier<SubtitleDownloadState> {
late final _$args = ref.$arg as EditorTimelineSession;
EditorTimelineSession get session => _$args;
SubtitleDownloadState build(EditorTimelineSession session);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<SubtitleDownloadState, SubtitleDownloadState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<SubtitleDownloadState, SubtitleDownloadState>,
SubtitleDownloadState,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args));
}
}
@@ -0,0 +1,136 @@
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../workspace/timeline_session.dart';
part 'subtitle_task_actions.g.dart';
part 'subtitle_task_actions.freezed.dart';
enum SubtitleActionKind { original, translation, cancel, retry }
@freezed
abstract class SubtitleActionFeedback with _$SubtitleActionFeedback {
const factory SubtitleActionFeedback({
required SubtitleActionKind kind,
int? cueCount,
}) = _SubtitleActionFeedback;
}
@freezed
abstract class SubtitleActionException
with _$SubtitleActionException
implements Exception {
const factory SubtitleActionException(SubtitleActionKind kind, Object cause) =
_SubtitleActionException;
}
/// One operation state is shared by the compact card and its details dialog.
@riverpod
class SubtitleTaskActions extends _$SubtitleTaskActions {
@override
AsyncValue<SubtitleActionFeedback?> build(
EditorTimelineSession session,
String jobId,
) => const AsyncData(null);
Future<List<ElementDto>> candidates(
SubtitleBackgroundTask job, {
bool translated = false,
}) async {
final recognition = job.recognition;
return session.persistence
.timeline(job.sequence)
.exportDto()
.elements
.where((element) {
final binding = element.payloadRef == null
? null
: session.mediaBinding(element.payloadRef!);
return (translated
? binding?.media.uri == recognition.source
: binding?.media.id == recognition.command.mediaId) &&
binding?.audioTrackIndex == recognition.command.audioStream;
})
.toList();
}
Future<void> apply(
SubtitleBackgroundTask job,
String clipId, {
required String expectedVersion,
bool translated = false,
}) => _run(
translated ? SubtitleActionKind.translation : SubtitleActionKind.original,
() async {
final recognition = job.recognition;
final outcome = translated
? await session.executeCommand(
job.sequence,
ApplySubtitleTranslation(
source: recognition.source!.toFilePath(),
audioStream: recognition.command.audioStream,
sourceStartMs: recognition.sourceStartMs,
taskId: job.translation!.id,
clipId: clipId,
expectedVersion: expectedVersion,
),
)
: await session.executeCommand(
job.sequence,
ApplyTranscription(
taskId: recognition.id,
clipId: clipId,
expectedVersion: expectedVersion,
),
);
final ids = (outcome.data['captionIds'] as List).cast<String>();
final view = session.view(job.sequence);
final handle = ids.isEmpty
? null
: view.version.kernelVersion.query().elementById(
ElementId(ids.first),
);
final component = handle == null
? null
: session.captionComponentFor(job.sequence, handle);
if (component != null) view.setSelection([component]);
return outcome.data['cueCount'] as int;
},
);
Future<void> cancel(SubtitleBackgroundTask job) =>
_run(SubtitleActionKind.cancel, () async {
await session.subtitleWorkflows.cancel(job);
return null;
});
Future<void> retry(SubtitleBackgroundTask job) =>
_run(SubtitleActionKind.retry, () async {
await session.subtitleWorkflows.retry(job);
return null;
});
Future<void> _run(
SubtitleActionKind kind,
Future<int?> Function() action,
) async {
if (state.isLoading) return;
final lease = ref.keepAlive();
final release = session.retainViews();
state = const AsyncLoading();
try {
final count = await action();
if (ref.mounted) {
state = AsyncData(SubtitleActionFeedback(kind: kind, cueCount: count));
}
} catch (error, stack) {
if (ref.mounted) {
state = AsyncError(SubtitleActionException(kind, error), stack);
}
} finally {
release();
lease.close();
}
}
}
@@ -0,0 +1,645 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'subtitle_task_actions.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$SubtitleActionFeedback {
SubtitleActionKind get kind;
int? get cueCount;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SubtitleActionFeedbackCopyWith<SubtitleActionFeedback> get copyWith =>
_$SubtitleActionFeedbackCopyWithImpl<SubtitleActionFeedback>(
this as SubtitleActionFeedback,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as SubtitleActionFeedback;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is SubtitleActionFeedback &&
(identical(other.kind, _this.kind) || other.kind == _this.kind) &&
(identical(other.cueCount, _this.cueCount) ||
other.cueCount == _this.cueCount));
}
@override
int get hashCode {
final _this = this as SubtitleActionFeedback;
return Object.hash(runtimeType, _this.kind, _this.cueCount);
}
@override
String toString() {
final _this = this as SubtitleActionFeedback;
return 'SubtitleActionFeedback(kind: ${_this.kind}, cueCount: ${_this.cueCount})';
}
}
/// @nodoc
abstract mixin class $SubtitleActionFeedbackCopyWith<$Res> {
factory $SubtitleActionFeedbackCopyWith(
SubtitleActionFeedback value,
$Res Function(SubtitleActionFeedback) _then,
) = _$SubtitleActionFeedbackCopyWithImpl;
@useResult
$Res call({SubtitleActionKind kind, int? cueCount});
}
/// @nodoc
class _$SubtitleActionFeedbackCopyWithImpl<$Res>
implements $SubtitleActionFeedbackCopyWith<$Res> {
_$SubtitleActionFeedbackCopyWithImpl(this._self, this._then);
final SubtitleActionFeedback _self;
final $Res Function(SubtitleActionFeedback) _then;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? kind = null, Object? cueCount = freezed}) {
return _then(
SubtitleActionFeedback(
kind: null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
cueCount: freezed == cueCount
? _self.cueCount
: cueCount // ignore: cast_nullable_to_non_nullable
as int?,
),
);
}
}
/// Adds pattern-matching-related methods to [SubtitleActionFeedback].
extension SubtitleActionFeedbackPatterns on SubtitleActionFeedback {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_SubtitleActionFeedback value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_SubtitleActionFeedback value) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_SubtitleActionFeedback value)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, int? cueCount)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that.kind, _that.cueCount);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, int? cueCount) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback():
return $default(_that.kind, _that.cueCount);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(SubtitleActionKind kind, int? cueCount)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that.kind, _that.cueCount);
case _:
return null;
}
}
}
/// @nodoc
class _SubtitleActionFeedback implements SubtitleActionFeedback {
const _SubtitleActionFeedback({required this.kind, this.cueCount});
@override
final SubtitleActionKind kind;
@override
final int? cueCount;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SubtitleActionFeedbackCopyWith<_SubtitleActionFeedback> get copyWith =>
__$SubtitleActionFeedbackCopyWithImpl<_SubtitleActionFeedback>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _SubtitleActionFeedback &&
(identical(other.kind, kind) || other.kind == kind) &&
(identical(other.cueCount, cueCount) ||
other.cueCount == cueCount));
}
@override
int get hashCode {
return Object.hash(runtimeType, kind, cueCount);
}
@override
String toString() {
return 'SubtitleActionFeedback(kind: $kind, cueCount: $cueCount)';
}
}
/// @nodoc
abstract mixin class _$SubtitleActionFeedbackCopyWith<$Res>
implements $SubtitleActionFeedbackCopyWith<$Res> {
factory _$SubtitleActionFeedbackCopyWith(
_SubtitleActionFeedback value,
$Res Function(_SubtitleActionFeedback) _then,
) = __$SubtitleActionFeedbackCopyWithImpl;
@override
@useResult
$Res call({SubtitleActionKind kind, int? cueCount});
}
/// @nodoc
class __$SubtitleActionFeedbackCopyWithImpl<$Res>
implements _$SubtitleActionFeedbackCopyWith<$Res> {
__$SubtitleActionFeedbackCopyWithImpl(this._self, this._then);
final _SubtitleActionFeedback _self;
final $Res Function(_SubtitleActionFeedback) _then;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? kind = null, Object? cueCount = freezed}) {
return _then(
_SubtitleActionFeedback(
kind: null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
cueCount: freezed == cueCount
? _self.cueCount
: cueCount // ignore: cast_nullable_to_non_nullable
as int?,
),
);
}
}
/// @nodoc
mixin _$SubtitleActionException {
SubtitleActionKind get kind;
Object get cause;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SubtitleActionExceptionCopyWith<SubtitleActionException> get copyWith =>
_$SubtitleActionExceptionCopyWithImpl<SubtitleActionException>(
this as SubtitleActionException,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as SubtitleActionException;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is SubtitleActionException &&
(identical(other.kind, _this.kind) || other.kind == _this.kind) &&
const DeepCollectionEquality().equals(other.cause, _this.cause));
}
@override
int get hashCode {
final _this = this as SubtitleActionException;
return Object.hash(
runtimeType,
_this.kind,
const DeepCollectionEquality().hash(_this.cause),
);
}
@override
String toString() {
final _this = this as SubtitleActionException;
return 'SubtitleActionException(kind: ${_this.kind}, cause: ${_this.cause})';
}
}
/// @nodoc
abstract mixin class $SubtitleActionExceptionCopyWith<$Res> {
factory $SubtitleActionExceptionCopyWith(
SubtitleActionException value,
$Res Function(SubtitleActionException) _then,
) = _$SubtitleActionExceptionCopyWithImpl;
@useResult
$Res call({SubtitleActionKind kind, Object cause});
}
/// @nodoc
class _$SubtitleActionExceptionCopyWithImpl<$Res>
implements $SubtitleActionExceptionCopyWith<$Res> {
_$SubtitleActionExceptionCopyWithImpl(this._self, this._then);
final SubtitleActionException _self;
final $Res Function(SubtitleActionException) _then;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? kind = null, Object? cause = null}) {
return _then(
SubtitleActionException(
null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
null == cause ? _self.cause : cause,
),
);
}
}
/// Adds pattern-matching-related methods to [SubtitleActionException].
extension SubtitleActionExceptionPatterns on SubtitleActionException {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_SubtitleActionException value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_SubtitleActionException value) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_SubtitleActionException value)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, Object cause)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that.kind, _that.cause);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, Object cause) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException():
return $default(_that.kind, _that.cause);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(SubtitleActionKind kind, Object cause)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that.kind, _that.cause);
case _:
return null;
}
}
}
/// @nodoc
class _SubtitleActionException implements SubtitleActionException {
const _SubtitleActionException(this.kind, this.cause);
@override
final SubtitleActionKind kind;
@override
final Object cause;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SubtitleActionExceptionCopyWith<_SubtitleActionException> get copyWith =>
__$SubtitleActionExceptionCopyWithImpl<_SubtitleActionException>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _SubtitleActionException &&
(identical(other.kind, kind) || other.kind == kind) &&
const DeepCollectionEquality().equals(other.cause, cause));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
kind,
const DeepCollectionEquality().hash(cause),
);
}
@override
String toString() {
return 'SubtitleActionException(kind: $kind, cause: $cause)';
}
}
/// @nodoc
abstract mixin class _$SubtitleActionExceptionCopyWith<$Res>
implements $SubtitleActionExceptionCopyWith<$Res> {
factory _$SubtitleActionExceptionCopyWith(
_SubtitleActionException value,
$Res Function(_SubtitleActionException) _then,
) = __$SubtitleActionExceptionCopyWithImpl;
@override
@useResult
$Res call({SubtitleActionKind kind, Object cause});
}
/// @nodoc
class __$SubtitleActionExceptionCopyWithImpl<$Res>
implements _$SubtitleActionExceptionCopyWith<$Res> {
__$SubtitleActionExceptionCopyWithImpl(this._self, this._then);
final _SubtitleActionException _self;
final $Res Function(_SubtitleActionException) _then;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? kind = null, Object? cause = null}) {
return _then(
_SubtitleActionException(
null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
null == cause ? _self.cause : cause,
),
);
}
}
@@ -0,0 +1,138 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'subtitle_task_actions.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// One operation state is shared by the compact card and its details dialog.
@ProviderFor(SubtitleTaskActions)
final subtitleTaskActionsProvider = SubtitleTaskActionsFamily._();
/// One operation state is shared by the compact card and its details dialog.
final class SubtitleTaskActionsProvider
extends
$NotifierProvider<
SubtitleTaskActions,
AsyncValue<SubtitleActionFeedback?>
> {
/// One operation state is shared by the compact card and its details dialog.
SubtitleTaskActionsProvider._({
required SubtitleTaskActionsFamily super.from,
required (EditorTimelineSession, String) super.argument,
}) : super(
retry: null,
name: r'subtitleTaskActionsProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$subtitleTaskActionsHash();
@override
String toString() {
return r'subtitleTaskActionsProvider'
''
'$argument';
}
@$internal
@override
SubtitleTaskActions create() => SubtitleTaskActions();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<SubtitleActionFeedback?> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<SubtitleActionFeedback?>>(
value,
),
);
}
@override
bool operator ==(Object other) {
return other is SubtitleTaskActionsProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$subtitleTaskActionsHash() =>
r'6308d7270d9a363b70bb03ae8dbbbbc83d2a71b7';
/// One operation state is shared by the compact card and its details dialog.
final class SubtitleTaskActionsFamily extends $Family
with
$ClassFamilyOverride<
SubtitleTaskActions,
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>,
(EditorTimelineSession, String)
> {
SubtitleTaskActionsFamily._()
: super(
retry: null,
name: r'subtitleTaskActionsProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
/// One operation state is shared by the compact card and its details dialog.
SubtitleTaskActionsProvider call(
EditorTimelineSession session,
String jobId,
) => SubtitleTaskActionsProvider._(argument: (session, jobId), from: this);
@override
String toString() => r'subtitleTaskActionsProvider';
}
/// One operation state is shared by the compact card and its details dialog.
abstract class _$SubtitleTaskActions
extends $Notifier<AsyncValue<SubtitleActionFeedback?>> {
late final _$args = ref.$arg as (EditorTimelineSession, String);
EditorTimelineSession get session => _$args.$1;
String get jobId => _$args.$2;
AsyncValue<SubtitleActionFeedback?> build(
EditorTimelineSession session,
String jobId,
);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref
as $Ref<
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>
>,
AsyncValue<SubtitleActionFeedback?>,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
}
}
@@ -0,0 +1,353 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/runtime/processing_contracts.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.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 '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
import 'subtitle_download.dart';
export 'processing_targets.dart';
class TranscriptionDialog extends ConsumerStatefulWidget {
const TranscriptionDialog({
super.key,
required this.session,
this.asset,
this.target,
}) : assert(asset == null || target == null);
const TranscriptionDialog.forCurrentTask({
super.key,
required this.session,
this.asset,
this.target,
}) : assert(asset == null || target == null);
final EditorTimelineSession session;
final AssetDocument? asset;
final TranscriptionClipTarget? target;
@override
ConsumerState<TranscriptionDialog> createState() =>
_TranscriptionDialogState();
}
class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
String _translationSource = 'auto';
String _translationTarget = 'none';
bool _closing = false;
late final VoidCallback _release;
SubtitleStartProvider get _startProvider =>
subtitleStartProvider(widget.session);
SubtitleDownloadState get _download {
final global = ref.read(subtitleDownloadProvider);
final local = ref.read(_startProvider);
if (identical(global.request?.session, widget.session) && global.running) {
return global;
}
return local is SubtitleIdle ? global : local;
}
bool get _ownsDownload =>
identical(_download.request?.session, widget.session);
bool get _installingResource =>
_ownsDownload && _download is SubtitleDownloading;
bool get _picking => _ownsDownload && _download is SubtitleStarting;
bool get _resourcePaused => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final paused) => paused,
_ => false,
}
: false;
double? get _resourceProgress => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final progress) => progress,
_ => null,
}
: null;
ProcessingCapability get _resourceStage => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final stage) => stage,
_ => ProcessingCapability.transcription,
}
: ProcessingCapability.transcription;
ProcessingResourceRepository? get _resourceRepository => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final repository) => repository,
_ => null,
}
: null;
TranscriptionClipTarget? get _target =>
_installingResource ? _download.request?.target : widget.target;
AssetDocument? get _asset =>
_installingResource ? _download.request?.asset : widget.asset;
String? get _mediaId => _target?.mediaId ?? _asset?.id;
String? get _error => !_ownsDownload
? null
: switch (_download) {
SubtitleFailed(:final failure) => switch (failure) {
SubtitleStartFailure.start => context.l10n.startTranscriptionFailed,
SubtitleStartFailure.download =>
context.l10n.processingResourceDownloadFailed,
SubtitleStartFailure.engine =>
context.l10n.subtitleEngineUnavailable,
},
_ => null,
};
@override
void initState() {
super.initState();
_release = widget.session.retainViews();
if (_ownsDownload && _download.running) {
_translationSource = _download.request!.language;
_translationTarget = _download.request!.targetLanguage;
}
}
@override
void dispose() {
_release();
super.dispose();
}
void _dismissDialog() {
if (!mounted) return;
final route = ModalRoute.of(context);
if (route == null) return;
final navigator = Navigator.of(context);
if (route.isCurrent) {
navigator.pop();
} else {
navigator.removeRoute(route);
}
}
SubtitleRequest _request() => SubtitleRequest(
session: widget.session,
sequence: _target?.sequence ?? widget.session.activeSequenceId,
target: _target,
asset: _asset,
language: _translationSource,
targetLanguage: _translationTarget,
);
Future<void> _start() => ref.read(_startProvider.notifier).start(_request());
Future<void> _downloadResourceAndStart() {
ref.read(_startProvider.notifier).reset();
return ref
.read(subtitleDownloadProvider.notifier)
.start(_request(), download: true);
}
void _toggleResourceDownload() =>
ref.read(subtitleDownloadProvider.notifier).togglePause();
void _cancelResourceDownload() =>
ref.read(subtitleDownloadProvider.notifier).cancel();
String _translationLanguageLabel(String code) =>
context.l10n.subtitleLanguageName(code);
Widget _translationLanguageMenu({
required String label,
required String value,
required String other,
required ValueChanged<String> onChanged,
bool source = false,
bool enabled = true,
}) => AppField(
label: label,
child: AppSelect<String>(
emptyLabel: context.l10n.noMatchingOptions,
label: label,
value: value,
searchable: true,
searchHint: context.l10n.searchOptions(label),
onChanged: enabled ? onChanged : null,
options: [
if (source) ...[
AppSelectOption('auto', context.l10n.autoDetect),
] else
AppSelectOption('none', context.l10n.noTranslation),
for (final code in [
'zh',
'en',
'ja',
'ko',
if (source) 'yue',
...m2m100LanguageNames.keys.where(
(code) => !const {'zh', 'en', 'ja', 'ko'}.contains(code),
),
])
AppSelectOption(
code,
_translationLanguageLabel(code),
enabled: code != other,
searchTerms: [
code,
?subtitleNativeLanguageNames[code],
?m2m100LanguageNames[code],
],
),
],
),
);
Widget _buildModelDownloadDialog() {
final packages =
_resourceRepository?.catalog ?? defaultProcessingResourceCatalog;
final service = widget.session.transcriptions;
final downloadBytes = packages
.where(
(package) =>
ProcessingResourceRepository.subtitleCapabilities.contains(
package.capability,
) &&
!(package.capability == ProcessingCapability.transcription &&
service?.recognitionAvailable == true) &&
!(package.capability == ProcessingCapability.translation &&
service?.translationAvailable == true),
)
.fold<int>(0, (total, package) => total + package.bytes);
final totalBytes = packages
.where(
(package) => ProcessingResourceRepository.subtitleCapabilities
.contains(package.capability),
)
.fold<int>(0, (total, package) => total + package.bytes);
final progressTotal = _resourceRepository?.subtitleTotalBytes ?? totalBytes;
final downloadedBytes =
_resourceRepository?.subtitleDownloadedBytes ??
((_resourceProgress ?? 0) * progressTotal).round();
return ProcessingResourceDownloadDialog(
title: context.l10n.subtitleResourceDownloadTask,
description: context.l10n.subtitleResourcesRequired,
resourceName: _resourceStage == ProcessingCapability.transcription
? context.l10n.speechResourceStage
: context.l10n.translationResourceStage,
downloadSize: context.l10n.subtitleResourcesDownloadSize(
formatResourceBytes(downloadBytes),
),
downloading: _installingResource,
paused: _resourcePaused,
downloadedBytes: downloadedBytes,
totalBytes: progressTotal,
bytesPerSecond: _resourceRepository?.subtitleDownloadBytesPerSecond ?? 0,
error: _error,
downloadButtonKey: const Key('download-transcription-resource'),
pauseButtonKey: const Key('download-transcription-resource'),
backgroundButtonKey: const Key('background-transcription-resource'),
onCancel: () async {
if (_installingResource &&
!await confirmResourceDownloadCancellation(context)) {
return;
}
if (!mounted) return;
_cancelResourceDownload();
_dismissDialog();
},
onDownload: _downloadResourceAndStart,
onTogglePause: _toggleResourceDownload,
onBackground: _dismissDialog,
);
}
@override
Widget build(BuildContext context) {
ref.watch(subtitleDownloadProvider);
ref.watch(_startProvider);
void handleResult(SubtitleDownloadState next) {
if (_closing || !identical(next.request?.session, widget.session)) return;
if (next is SubtitleStarted || next is SubtitleCancelled) {
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final message = context.l10n.subtitleTaskStarted;
_dismissDialog();
if (next is SubtitleStarted) {
messenger?.showSnackBar(SnackBar(content: Text(message)));
}
});
}
}
ref.listen(subtitleDownloadProvider, (_, next) => handleResult(next));
ref.listen(_startProvider, (_, next) => handleResult(next));
return ListenableBuilder(
listenable: widget.session,
builder: (context, _) {
final service = widget.session.transcriptions;
if (service?.recognitionAvailable != true ||
service?.translationAvailable != true ||
_installingResource) {
return _buildModelDownloadDialog();
}
final busy =
(service?.tasks.any((task) => !task.terminal) ?? false) ||
(service?.translationTasks.any((task) => !task.terminal) ?? false);
return AppDialog(
title: _target == null
? context.l10n.transcribe
: context.l10n.generateCaptions,
withShadow: true,
width: 560,
actions: [
if (_mediaId != null && service != null)
FilledButton(
onPressed: busy || _picking || !widget.session.acceptsEdits
? null
: _start,
child: Text(context.l10n.generateCaptions),
),
],
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
_translationLanguageMenu(
label: context.l10n.sourceLanguage,
value: _translationSource,
other: _translationTarget,
source: true,
enabled: !busy && !_picking,
onChanged: (value) =>
setState(() => _translationSource = value),
),
const SizedBox(height: AppSpacing.compact),
_translationLanguageMenu(
label: context.l10n.translationLanguage,
value: _translationTarget,
other: _translationSource,
enabled:
service?.translationAvailable == true &&
!busy &&
!_picking,
onChanged: (value) =>
setState(() => _translationTarget = value),
),
if (service?.translationAvailable != true)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.small),
child: Text(context.l10n.translationNotConfigured),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.compact),
child: Text(_error!),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,58 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/media_availability.dart';
class UnavailableMediaPlaceholder extends StatelessWidget {
const UnavailableMediaPlaceholder({
super.key,
required this.availability,
this.showLabel = true,
this.isPreview = false,
});
final MediaAvailability availability;
final bool showLabel;
final bool isPreview;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final label = availability == MediaAvailability.missing
? context.l10n.mediaMissing
: context.l10n.mediaUnavailable;
// Project covers share the canvas background, including missing media.
return ColoredBox(
color: isPreview
? Colors.transparent
: AppSurfaces.of(context).previewBackground,
child: Center(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.broken_image_outlined,
size: isPreview ? 32 : 24,
color: theme.colorScheme.error,
),
if (showLabel) ...[
const SizedBox(height: AppSpacing.gap),
Text(
label,
style:
(isPreview
? theme.textTheme.bodyMedium
: theme.textTheme.bodySmall)
?.copyWith(color: theme.colorScheme.error),
),
],
],
),
),
),
);
}
}
+53
View File
@@ -0,0 +1,53 @@
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/material.dart';
import 'media_asset_cover.dart';
import 'package:cutdex_ui/theme.dart';
class VisualAssetTile extends StatelessWidget {
const VisualAssetTile({super.key, required this.asset, this.showName = true});
final AssetDocument asset;
final bool showName;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AspectRatio(
key: ValueKey('visual-cover-${asset.id}'),
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: MediaAssetCover(
asset: asset,
fallback: Center(
child: Icon(
asset.metadata['kind'] == 'image'
? Icons.image_outlined
: Icons.movie_outlined,
size: AppIconSize.emptyState,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
),
),
if (showName) ...[
const SizedBox(height: AppSpacing.small),
Tooltip(
message: asset.name,
child: Text(
asset.name,
key: ValueKey('visual-name-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
],
],
);
}
}