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

@@ -0,0 +1,81 @@
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'timeline_session.dart';
part 'background_task_registry.g.dart';
part 'background_task_registry.freezed.dart';
@Riverpod(keepAlive: true)
Raw<BackgroundTaskRegistry> backgroundTaskRegistry(Ref ref) {
final registry = BackgroundTaskRegistry();
ref.onDispose(registry.dispose);
return registry;
}
@freezed
abstract class BackgroundTaskSession with _$BackgroundTaskSession {
const factory BackgroundTaskSession({
required String projectId,
required String projectName,
required String timelineId,
required String timelineName,
required EditorTimelineSession session,
}) = _BackgroundTaskSession;
}
/// Application-level index of task owners. Tasks remain owned by their editor
/// session; global UI observes them without depending on the visible timeline.
final class BackgroundTaskRegistry extends ChangeNotifier {
final _entries = <EditorTimelineSession, BackgroundTaskSession>{};
bool _disposed = false;
List<BackgroundTaskSession> get entries => List.unmodifiable(_entries.values);
int get runningCount => _entries.values.fold(
0,
(count, entry) =>
count +
entry.session.subtitleWorkflows.runningCount +
entry.session.backgroundRemovals.runningCount,
);
void register({
required String projectId,
required String projectName,
required EditorTimelineSession session,
}) {
if (_disposed || _entries.containsKey(session)) return;
_entries[session] = BackgroundTaskSession(
projectId: projectId,
projectName: projectName,
timelineId: session.document.id,
timelineName: session.document.name,
session: session,
);
session.addListener(_changed);
notifyListeners();
}
void unregister(EditorTimelineSession session) {
if (_entries.remove(session) == null) return;
session.removeListener(_changed);
if (!_disposed) notifyListeners();
}
void _changed() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
if (_disposed) return;
_disposed = true;
for (final session in _entries.keys) {
session.removeListener(_changed);
}
_entries.clear();
super.dispose();
}
}
@@ -0,0 +1,483 @@
// 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_task_registry.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$BackgroundTaskSession implements DiagnosticableTreeMixin {
String get projectId;
String get projectName;
String get timelineId;
String get timelineName;
EditorTimelineSession get session;
/// Create a copy of BackgroundTaskSession
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$BackgroundTaskSessionCopyWith<BackgroundTaskSession> get copyWith =>
_$BackgroundTaskSessionCopyWithImpl<BackgroundTaskSession>(
this as BackgroundTaskSession,
_$identity,
);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
final _this = this as BackgroundTaskSession;
properties
..add(DiagnosticsProperty('type', 'BackgroundTaskSession'))
..add(DiagnosticsProperty('projectId', _this.projectId))
..add(DiagnosticsProperty('projectName', _this.projectName))
..add(DiagnosticsProperty('timelineId', _this.timelineId))
..add(DiagnosticsProperty('timelineName', _this.timelineName))
..add(DiagnosticsProperty('session', _this.session));
}
@override
bool operator ==(Object other) {
final _this = this as BackgroundTaskSession;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is BackgroundTaskSession &&
(identical(other.projectId, _this.projectId) ||
other.projectId == _this.projectId) &&
(identical(other.projectName, _this.projectName) ||
other.projectName == _this.projectName) &&
(identical(other.timelineId, _this.timelineId) ||
other.timelineId == _this.timelineId) &&
(identical(other.timelineName, _this.timelineName) ||
other.timelineName == _this.timelineName) &&
(identical(other.session, _this.session) ||
other.session == _this.session));
}
@override
int get hashCode {
final _this = this as BackgroundTaskSession;
return Object.hash(
runtimeType,
_this.projectId,
_this.projectName,
_this.timelineId,
_this.timelineName,
_this.session,
);
}
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
final _this = this as BackgroundTaskSession;
return 'BackgroundTaskSession(projectId: ${_this.projectId}, projectName: ${_this.projectName}, timelineId: ${_this.timelineId}, timelineName: ${_this.timelineName}, session: ${_this.session})';
}
}
/// @nodoc
abstract mixin class $BackgroundTaskSessionCopyWith<$Res> {
factory $BackgroundTaskSessionCopyWith(
BackgroundTaskSession value,
$Res Function(BackgroundTaskSession) _then,
) = _$BackgroundTaskSessionCopyWithImpl;
@useResult
$Res call({
String projectId,
String projectName,
String timelineId,
String timelineName,
EditorTimelineSession session,
});
}
/// @nodoc
class _$BackgroundTaskSessionCopyWithImpl<$Res>
implements $BackgroundTaskSessionCopyWith<$Res> {
_$BackgroundTaskSessionCopyWithImpl(this._self, this._then);
final BackgroundTaskSession _self;
final $Res Function(BackgroundTaskSession) _then;
/// Create a copy of BackgroundTaskSession
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? projectId = null,
Object? projectName = null,
Object? timelineId = null,
Object? timelineName = null,
Object? session = null,
}) {
return _then(
BackgroundTaskSession(
projectId: null == projectId
? _self.projectId
: projectId // ignore: cast_nullable_to_non_nullable
as String,
projectName: null == projectName
? _self.projectName
: projectName // ignore: cast_nullable_to_non_nullable
as String,
timelineId: null == timelineId
? _self.timelineId
: timelineId // ignore: cast_nullable_to_non_nullable
as String,
timelineName: null == timelineName
? _self.timelineName
: timelineName // ignore: cast_nullable_to_non_nullable
as String,
session: null == session
? _self.session
: session // ignore: cast_nullable_to_non_nullable
as EditorTimelineSession,
),
);
}
}
/// Adds pattern-matching-related methods to [BackgroundTaskSession].
extension BackgroundTaskSessionPatterns on BackgroundTaskSession {
/// 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(_BackgroundTaskSession value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _BackgroundTaskSession() 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(_BackgroundTaskSession value) $default,
) {
final _that = this;
switch (_that) {
case _BackgroundTaskSession():
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(_BackgroundTaskSession value)? $default,
) {
final _that = this;
switch (_that) {
case _BackgroundTaskSession() 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(
String projectId,
String projectName,
String timelineId,
String timelineName,
EditorTimelineSession session,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _BackgroundTaskSession() when $default != null:
return $default(
_that.projectId,
_that.projectName,
_that.timelineId,
_that.timelineName,
_that.session,
);
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(
String projectId,
String projectName,
String timelineId,
String timelineName,
EditorTimelineSession session,
)
$default,
) {
final _that = this;
switch (_that) {
case _BackgroundTaskSession():
return $default(
_that.projectId,
_that.projectName,
_that.timelineId,
_that.timelineName,
_that.session,
);
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(
String projectId,
String projectName,
String timelineId,
String timelineName,
EditorTimelineSession session,
)?
$default,
) {
final _that = this;
switch (_that) {
case _BackgroundTaskSession() when $default != null:
return $default(
_that.projectId,
_that.projectName,
_that.timelineId,
_that.timelineName,
_that.session,
);
case _:
return null;
}
}
}
/// @nodoc
class _BackgroundTaskSession
with DiagnosticableTreeMixin
implements BackgroundTaskSession {
const _BackgroundTaskSession({
required this.projectId,
required this.projectName,
required this.timelineId,
required this.timelineName,
required this.session,
});
@override
final String projectId;
@override
final String projectName;
@override
final String timelineId;
@override
final String timelineName;
@override
final EditorTimelineSession session;
/// Create a copy of BackgroundTaskSession
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$BackgroundTaskSessionCopyWith<_BackgroundTaskSession> get copyWith =>
__$BackgroundTaskSessionCopyWithImpl<_BackgroundTaskSession>(
this,
_$identity,
);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'BackgroundTaskSession'))
..add(DiagnosticsProperty('projectId', projectId))
..add(DiagnosticsProperty('projectName', projectName))
..add(DiagnosticsProperty('timelineId', timelineId))
..add(DiagnosticsProperty('timelineName', timelineName))
..add(DiagnosticsProperty('session', session));
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _BackgroundTaskSession &&
(identical(other.projectId, projectId) ||
other.projectId == projectId) &&
(identical(other.projectName, projectName) ||
other.projectName == projectName) &&
(identical(other.timelineId, timelineId) ||
other.timelineId == timelineId) &&
(identical(other.timelineName, timelineName) ||
other.timelineName == timelineName) &&
(identical(other.session, session) || other.session == session));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
projectId,
projectName,
timelineId,
timelineName,
session,
);
}
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return 'BackgroundTaskSession(projectId: $projectId, projectName: $projectName, timelineId: $timelineId, timelineName: $timelineName, session: $session)';
}
}
/// @nodoc
abstract mixin class _$BackgroundTaskSessionCopyWith<$Res>
implements $BackgroundTaskSessionCopyWith<$Res> {
factory _$BackgroundTaskSessionCopyWith(
_BackgroundTaskSession value,
$Res Function(_BackgroundTaskSession) _then,
) = __$BackgroundTaskSessionCopyWithImpl;
@override
@useResult
$Res call({
String projectId,
String projectName,
String timelineId,
String timelineName,
EditorTimelineSession session,
});
}
/// @nodoc
class __$BackgroundTaskSessionCopyWithImpl<$Res>
implements _$BackgroundTaskSessionCopyWith<$Res> {
__$BackgroundTaskSessionCopyWithImpl(this._self, this._then);
final _BackgroundTaskSession _self;
final $Res Function(_BackgroundTaskSession) _then;
/// Create a copy of BackgroundTaskSession
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? projectId = null,
Object? projectName = null,
Object? timelineId = null,
Object? timelineName = null,
Object? session = null,
}) {
return _then(
_BackgroundTaskSession(
projectId: null == projectId
? _self.projectId
: projectId // ignore: cast_nullable_to_non_nullable
as String,
projectName: null == projectName
? _self.projectName
: projectName // ignore: cast_nullable_to_non_nullable
as String,
timelineId: null == timelineId
? _self.timelineId
: timelineId // ignore: cast_nullable_to_non_nullable
as String,
timelineName: null == timelineName
? _self.timelineName
: timelineName // ignore: cast_nullable_to_non_nullable
as String,
session: null == session
? _self.session
: session // ignore: cast_nullable_to_non_nullable
as EditorTimelineSession,
),
);
}
}
@@ -0,0 +1,58 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'background_task_registry.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(backgroundTaskRegistry)
final backgroundTaskRegistryProvider = BackgroundTaskRegistryProvider._();
final class BackgroundTaskRegistryProvider
extends
$FunctionalProvider<
Raw<BackgroundTaskRegistry>,
Raw<BackgroundTaskRegistry>,
Raw<BackgroundTaskRegistry>
>
with $Provider<Raw<BackgroundTaskRegistry>> {
BackgroundTaskRegistryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'backgroundTaskRegistryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$backgroundTaskRegistryHash();
@$internal
@override
$ProviderElement<Raw<BackgroundTaskRegistry>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
Raw<BackgroundTaskRegistry> create(Ref ref) {
return backgroundTaskRegistry(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Raw<BackgroundTaskRegistry> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Raw<BackgroundTaskRegistry>>(value),
);
}
}
String _$backgroundTaskRegistryHash() =>
r'efee10c01b9a917cbf9b5692c633d13c8de4394c';
+205
View File
@@ -0,0 +1,205 @@
import 'package:cutdex_sdk/editor.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'background_task_registry.dart';
import 'timeline_session.dart';
part 'background_task_state.g.dart';
part 'background_task_state.freezed.dart';
@freezed
abstract class SubtitleTaskEntry with _$SubtitleTaskEntry {
const factory SubtitleTaskEntry({
required BackgroundTaskSession owner,
required SubtitleBackgroundTask job,
required TranscriptionStatus status,
required bool terminal,
required bool followingUp,
required String name,
required String sourceLanguage,
required String targetLanguage,
required bool hasTranslation,
required bool recognitionTerminal,
required bool recognitionAvailable,
required bool translationAvailable,
@Default([]) List<String> recentCues,
@Default([]) List<String> resultCues,
int? completed,
int? total,
String? error,
@Default(0) int recognizedCues,
@Default(0) int translatedCues,
}) = _SubtitleTaskEntry;
}
@freezed
abstract class RemovalTaskEntry with _$RemovalTaskEntry {
const factory RemovalTaskEntry({
required BackgroundTaskSession owner,
required BackgroundRemovalTask task,
required BackgroundRemovalStatus status,
required String name,
required bool terminal,
int? completed,
int? total,
String? error,
}) = _RemovalTaskEntry;
}
@freezed
abstract class BackgroundTasksSnapshot with _$BackgroundTasksSnapshot {
const factory BackgroundTasksSnapshot({
@Default([]) List<SubtitleTaskEntry> subtitles,
@Default([]) List<RemovalTaskEntry> removals,
@Default(0) int runningCount,
}) = _BackgroundTasksSnapshot;
}
@riverpod
class BackgroundTasks extends _$BackgroundTasks {
final _observed = <EditorTimelineSession>{};
@override
BackgroundTasksSnapshot build({
BackgroundTaskRegistry? registry,
EditorTimelineSession? session,
}) {
assert(registry != null || session != null);
registry?.addListener(_changed);
ref.onDispose(() {
registry?.removeListener(_changed);
for (final owner in _observed) {
owner.removeListener(_changed);
}
_observed.clear();
});
return _snapshot();
}
void _changed() {
if (ref.mounted) state = _snapshot();
}
BackgroundTasksSnapshot _snapshot() {
final owners =
registry?.entries ??
[
BackgroundTaskSession(
projectId: '',
projectName: '',
timelineId: session!.document.id,
timelineName: session!.document.name,
session: session!,
),
];
// Registry already observes its sessions; a standalone task view needs its own listener.
final next = registry == null
? owners.map((owner) => owner.session).toSet()
: <EditorTimelineSession>{};
for (final owner in _observed.difference(next)) {
owner.removeListener(_changed);
}
for (final owner in next.difference(_observed)) {
owner.addListener(_changed);
}
_observed
..clear()
..addAll(next);
final subtitles = <SubtitleTaskEntry>[];
final removals = <RemovalTaskEntry>[];
var runningCount = 0;
for (final owner in owners) {
final timeline = owner.session;
runningCount +=
timeline.subtitleWorkflows.runningCount +
timeline.backgroundRemovals.runningCount;
final jobs = timeline.subtitleWorkflows.tasks;
final ids = jobs.map((job) => job.recognition.id).toSet();
final sequence = timeline.activeSequenceId;
if (sequence != null) {
for (final task
in timeline.transcriptions?.tasks ?? <EditorTranscriptionTask>[]) {
if (ids.contains(task.id)) continue;
final translation = timeline.transcriptions?.translationTasks
.where(
(item) =>
item.command.source == task.result?.subtitles.toFilePath(),
)
.lastOrNull;
subtitles.add(
_subtitle(
owner,
SubtitleBackgroundTask(
id: task.id,
sequence: sequence,
name: task.command.mediaId,
recognition: task,
targetLanguage: translation?.command.targetLanguage ?? 'none',
translation: translation,
),
),
);
}
}
subtitles.addAll(jobs.map((job) => _subtitle(owner, job)));
removals.addAll(
timeline.backgroundRemovals.tasks.reversed.map(
(task) => RemovalTaskEntry(
owner: owner,
task: task,
status: task.status,
name: task.name,
terminal: task.terminal,
completed: task.progress?.completed,
total: task.progress?.total,
error: task.error,
),
),
);
}
return BackgroundTasksSnapshot(
subtitles: subtitles,
removals: removals,
runningCount: runningCount,
);
}
SubtitleTaskEntry _subtitle(
BackgroundTaskSession owner,
SubtitleBackgroundTask job,
) => SubtitleTaskEntry(
owner: owner,
job: job,
status: job.status,
terminal: job.terminal,
followingUp: job.followingUp,
name: job.name,
sourceLanguage: job.recognition.command.language,
targetLanguage: job.targetLanguage,
hasTranslation: job.translation != null,
recognitionTerminal: job.recognition.terminal,
recognitionAvailable: job.recognition.result != null,
translationAvailable: job.translation?.result != null,
recentCues: job.recognition.timelineCues.reversed
.take(3)
.toList()
.reversed
.map((cue) => cue.text)
.toList(),
resultCues:
job.translation?.result?.document.cues
.map((cue) => cue.text)
.toList() ??
job.recognition.result?.cues.map((cue) => cue.text).toList() ??
[],
completed:
job.translation?.progress?.completed ??
job.recognition.progress?.completed,
total: job.translation?.progress?.total ?? job.recognition.progress?.total,
error: job.error ?? job.translation?.error ?? job.recognition.error,
recognizedCues:
job.recognition.result?.cues.length ??
job.recognition.timelineCues.length,
translatedCues: job.translation?.result?.document.cues.length ?? 0,
);
}
File diff suppressed because it is too large. Load diff
+129
View File
@@ -0,0 +1,129 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'background_task_state.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BackgroundTasks)
final backgroundTasksProvider = BackgroundTasksFamily._();
final class BackgroundTasksProvider
extends $NotifierProvider<BackgroundTasks, BackgroundTasksSnapshot> {
BackgroundTasksProvider._({
required BackgroundTasksFamily super.from,
required ({
BackgroundTaskRegistry? registry,
EditorTimelineSession? session,
})
super.argument,
}) : super(
retry: null,
name: r'backgroundTasksProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$backgroundTasksHash();
@override
String toString() {
return r'backgroundTasksProvider'
''
'$argument';
}
@$internal
@override
BackgroundTasks create() => BackgroundTasks();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(BackgroundTasksSnapshot value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<BackgroundTasksSnapshot>(value),
);
}
@override
bool operator ==(Object other) {
return other is BackgroundTasksProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$backgroundTasksHash() => r'fad7fdf299e66a594525ca8b215e57e460a135d0';
final class BackgroundTasksFamily extends $Family
with
$ClassFamilyOverride<
BackgroundTasks,
BackgroundTasksSnapshot,
BackgroundTasksSnapshot,
BackgroundTasksSnapshot,
({BackgroundTaskRegistry? registry, EditorTimelineSession? session})
> {
BackgroundTasksFamily._()
: super(
retry: null,
name: r'backgroundTasksProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BackgroundTasksProvider call({
BackgroundTaskRegistry? registry,
EditorTimelineSession? session,
}) => BackgroundTasksProvider._(
argument: (registry: registry, session: session),
from: this,
);
@override
String toString() => r'backgroundTasksProvider';
}
abstract class _$BackgroundTasks extends $Notifier<BackgroundTasksSnapshot> {
late final _$args =
ref.$arg
as ({
BackgroundTaskRegistry? registry,
EditorTimelineSession? session,
});
BackgroundTaskRegistry? get registry => _$args.registry;
EditorTimelineSession? get session => _$args.session;
BackgroundTasksSnapshot build({
BackgroundTaskRegistry? registry,
EditorTimelineSession? session,
});
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref as $Ref<BackgroundTasksSnapshot, BackgroundTasksSnapshot>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<BackgroundTasksSnapshot, BackgroundTasksSnapshot>,
BackgroundTasksSnapshot,
Object?,
Object?
>;
return element.handleCreate(
ref,
() => build(registry: _$args.registry, session: _$args.session),
);
}
}
+121
View File
@@ -0,0 +1,121 @@
import 'dart:io';
import 'package:cutdex_sdk/project.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'media_import.dart';
import 'projects.dart';
part 'external_media_import.g.dart';
part 'external_media_import.freezed.dart';
@freezed
abstract class ExternalMediaSelection with _$ExternalMediaSelection {
const factory ExternalMediaSelection({
required List<AssetDocument> selected,
MediaImportResult? result,
@Default(false) bool failed,
}) = _ExternalMediaSelection;
}
@riverpod
MediaFileResolver mediaFileResolver(Ref ref) => const MediaFileResolver();
/// Resolves aliases once for both the media browser and the attachment composer.
class MediaFileResolver {
const MediaFileResolver();
Future<Map<ExternalMediaFile, Set<String>>> resolve(
List<ExternalMediaFile> files,
List<AssetDocument> assets,
) async {
final locations = <ExternalMediaFile, Set<String>>{};
for (final file in files) {
final candidates = {file.sourceUri.toString()};
final path = file.localPath;
if (path != null &&
!assets.any(
(asset) => candidates.contains(mediaSourceLocation(asset)),
) &&
File(path).existsSync()) {
try {
candidates.add(
Uri.file(await File(path).resolveSymbolicLinks()).toString(),
);
} on FileSystemException {
// Unavailable sources are reported by the importer.
}
}
locations[file] = candidates;
}
return locations;
}
}
@riverpod
class ExternalMediaImport extends _$ExternalMediaImport {
@override
AsyncValue<ExternalMediaSelection?> build(String projectId) =>
const AsyncData(null);
Future<ExternalMediaSelection?> importFiles(
List<ExternalMediaFile> files,
) async {
if (state.isLoading || files.isEmpty) return null;
final workspace = ref.read(projectsProvider).value;
if (workspace?.activeProject?.id != projectId || workspace!.projectBusy) {
return null;
}
final lease = ref.keepAlive();
final projects = ref.read(projectsProvider.notifier);
final resolver = ref.read(mediaFileResolverProvider);
state = const AsyncLoading();
try {
final locations = await resolver.resolve(files, workspace.assets);
if (!ref.mounted ||
ref.read(projectsProvider).value?.activeProject?.id != projectId) {
return null;
}
final existing = <AssetDocument>[];
final missing = <ExternalMediaFile>[];
for (final file in files) {
final asset = workspace.assets
.where(
(asset) => locations[file]!.contains(mediaSourceLocation(asset)),
)
.firstOrNull;
if (asset == null) {
missing.add(file);
} else if (!existing.any((item) => item.id == asset.id)) {
existing.add(asset);
}
}
final result = missing.isEmpty
? null
: await projects.importExternalMedia(projectId, missing);
final importedLocations = {
for (final file in missing) ...locations[file]!,
};
final selected = <String, AssetDocument>{
for (final asset in existing) asset.id: asset,
for (final asset in result?.assets ?? <AssetDocument>[])
if (importedLocations.contains(mediaSourceLocation(asset)))
asset.id: asset,
};
final value = ExternalMediaSelection(
selected: selected.values.toList(),
result: result,
failed: missing.isNotEmpty && result == null,
);
if (ref.mounted) state = AsyncData(value);
return value;
} catch (error, stack) {
if (ref.mounted) state = AsyncError(error, stack);
rethrow;
} finally {
if (ref.mounted && state.isLoading) state = const AsyncData(null);
lease.close();
}
}
}
@@ -0,0 +1,430 @@
// 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 'external_media_import.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$ExternalMediaSelection {
List<AssetDocument> get selected;
MediaImportResult? get result;
bool get failed;
/// Create a copy of ExternalMediaSelection
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ExternalMediaSelectionCopyWith<ExternalMediaSelection> get copyWith =>
_$ExternalMediaSelectionCopyWithImpl<ExternalMediaSelection>(
this as ExternalMediaSelection,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as ExternalMediaSelection;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is ExternalMediaSelection &&
const DeepCollectionEquality().equals(
other.selected,
_this.selected,
) &&
(identical(other.result, _this.result) ||
other.result == _this.result) &&
(identical(other.failed, _this.failed) ||
other.failed == _this.failed));
}
@override
int get hashCode {
final _this = this as ExternalMediaSelection;
return Object.hash(
runtimeType,
const DeepCollectionEquality().hash(_this.selected),
_this.result,
_this.failed,
);
}
@override
String toString() {
final _this = this as ExternalMediaSelection;
return 'ExternalMediaSelection(selected: ${_this.selected}, result: ${_this.result}, failed: ${_this.failed})';
}
}
/// @nodoc
abstract mixin class $ExternalMediaSelectionCopyWith<$Res> {
factory $ExternalMediaSelectionCopyWith(
ExternalMediaSelection value,
$Res Function(ExternalMediaSelection) _then,
) = _$ExternalMediaSelectionCopyWithImpl;
@useResult
$Res call({
List<AssetDocument> selected,
MediaImportResult? result,
bool failed,
});
$MediaImportResultCopyWith<$Res>? get result;
}
/// @nodoc
class _$ExternalMediaSelectionCopyWithImpl<$Res>
implements $ExternalMediaSelectionCopyWith<$Res> {
_$ExternalMediaSelectionCopyWithImpl(this._self, this._then);
final ExternalMediaSelection _self;
final $Res Function(ExternalMediaSelection) _then;
/// Create a copy of ExternalMediaSelection
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? selected = null,
Object? result = freezed,
Object? failed = null,
}) {
return _then(
ExternalMediaSelection(
selected: null == selected
? _self.selected
: selected // ignore: cast_nullable_to_non_nullable
as List<AssetDocument>,
result: freezed == result
? _self.result
: result // ignore: cast_nullable_to_non_nullable
as MediaImportResult?,
failed: null == failed
? _self.failed
: failed // ignore: cast_nullable_to_non_nullable
as bool,
),
);
}
/// Create a copy of ExternalMediaSelection
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$MediaImportResultCopyWith<$Res>? get result {
if (_self.result == null) {
return null;
}
return $MediaImportResultCopyWith<$Res>(_self.result!, (value) {
return _then(_self.copyWith(result: value));
});
}
}
/// Adds pattern-matching-related methods to [ExternalMediaSelection].
extension ExternalMediaSelectionPatterns on ExternalMediaSelection {
/// 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(_ExternalMediaSelection value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _ExternalMediaSelection() 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(_ExternalMediaSelection value) $default,
) {
final _that = this;
switch (_that) {
case _ExternalMediaSelection():
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(_ExternalMediaSelection value)? $default,
) {
final _that = this;
switch (_that) {
case _ExternalMediaSelection() 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(
List<AssetDocument> selected,
MediaImportResult? result,
bool failed,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _ExternalMediaSelection() when $default != null:
return $default(_that.selected, _that.result, _that.failed);
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(
List<AssetDocument> selected,
MediaImportResult? result,
bool failed,
)
$default,
) {
final _that = this;
switch (_that) {
case _ExternalMediaSelection():
return $default(_that.selected, _that.result, _that.failed);
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(
List<AssetDocument> selected,
MediaImportResult? result,
bool failed,
)?
$default,
) {
final _that = this;
switch (_that) {
case _ExternalMediaSelection() when $default != null:
return $default(_that.selected, _that.result, _that.failed);
case _:
return null;
}
}
}
/// @nodoc
class _ExternalMediaSelection implements ExternalMediaSelection {
const _ExternalMediaSelection({
required List<AssetDocument> selected,
this.result,
this.failed = false,
}) : _selected = selected;
final List<AssetDocument> _selected;
@override
List<AssetDocument> get selected {
if (_selected is EqualUnmodifiableListView) return _selected;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_selected);
}
@override
final MediaImportResult? result;
@override
@JsonKey()
final bool failed;
/// Create a copy of ExternalMediaSelection
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ExternalMediaSelectionCopyWith<_ExternalMediaSelection> get copyWith =>
__$ExternalMediaSelectionCopyWithImpl<_ExternalMediaSelection>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _ExternalMediaSelection &&
const DeepCollectionEquality().equals(other.selected, _selected) &&
(identical(other.result, result) || other.result == result) &&
(identical(other.failed, failed) || other.failed == failed));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
const DeepCollectionEquality().hash(_selected),
result,
failed,
);
}
@override
String toString() {
return 'ExternalMediaSelection(selected: $selected, result: $result, failed: $failed)';
}
}
/// @nodoc
abstract mixin class _$ExternalMediaSelectionCopyWith<$Res>
implements $ExternalMediaSelectionCopyWith<$Res> {
factory _$ExternalMediaSelectionCopyWith(
_ExternalMediaSelection value,
$Res Function(_ExternalMediaSelection) _then,
) = __$ExternalMediaSelectionCopyWithImpl;
@override
@useResult
$Res call({
List<AssetDocument> selected,
MediaImportResult? result,
bool failed,
});
@override
$MediaImportResultCopyWith<$Res>? get result;
}
/// @nodoc
class __$ExternalMediaSelectionCopyWithImpl<$Res>
implements _$ExternalMediaSelectionCopyWith<$Res> {
__$ExternalMediaSelectionCopyWithImpl(this._self, this._then);
final _ExternalMediaSelection _self;
final $Res Function(_ExternalMediaSelection) _then;
/// Create a copy of ExternalMediaSelection
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? selected = null,
Object? result = freezed,
Object? failed = null,
}) {
return _then(
_ExternalMediaSelection(
selected: null == selected
? _self._selected
: selected // ignore: cast_nullable_to_non_nullable
as List<AssetDocument>,
result: freezed == result
? _self.result
: result // ignore: cast_nullable_to_non_nullable
as MediaImportResult?,
failed: null == failed
? _self.failed
: failed // ignore: cast_nullable_to_non_nullable
as bool,
),
);
}
/// Create a copy of ExternalMediaSelection
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$MediaImportResultCopyWith<$Res>? get result {
if (_self.result == null) {
return null;
}
return $MediaImportResultCopyWith<$Res>(_self.result!, (value) {
return _then(_self.copyWith(result: value));
});
}
}
+170
View File
@@ -0,0 +1,170 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'external_media_import.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(mediaFileResolver)
final mediaFileResolverProvider = MediaFileResolverProvider._();
final class MediaFileResolverProvider
extends
$FunctionalProvider<
MediaFileResolver,
MediaFileResolver,
MediaFileResolver
>
with $Provider<MediaFileResolver> {
MediaFileResolverProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'mediaFileResolverProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$mediaFileResolverHash();
@$internal
@override
$ProviderElement<MediaFileResolver> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
MediaFileResolver create(Ref ref) {
return mediaFileResolver(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(MediaFileResolver value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<MediaFileResolver>(value),
);
}
}
String _$mediaFileResolverHash() => r'429dfc500e860cdc0bee600c538901466b8e5375';
@ProviderFor(ExternalMediaImport)
final externalMediaImportProvider = ExternalMediaImportFamily._();
final class ExternalMediaImportProvider
extends
$NotifierProvider<
ExternalMediaImport,
AsyncValue<ExternalMediaSelection?>
> {
ExternalMediaImportProvider._({
required ExternalMediaImportFamily super.from,
required String super.argument,
}) : super(
retry: null,
name: r'externalMediaImportProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$externalMediaImportHash();
@override
String toString() {
return r'externalMediaImportProvider'
''
'($argument)';
}
@$internal
@override
ExternalMediaImport create() => ExternalMediaImport();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<ExternalMediaSelection?> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<ExternalMediaSelection?>>(
value,
),
);
}
@override
bool operator ==(Object other) {
return other is ExternalMediaImportProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$externalMediaImportHash() =>
r'48bf943d1132cec15af783c748bbe2a096b65196';
final class ExternalMediaImportFamily extends $Family
with
$ClassFamilyOverride<
ExternalMediaImport,
AsyncValue<ExternalMediaSelection?>,
AsyncValue<ExternalMediaSelection?>,
AsyncValue<ExternalMediaSelection?>,
String
> {
ExternalMediaImportFamily._()
: super(
retry: null,
name: r'externalMediaImportProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
ExternalMediaImportProvider call(String projectId) =>
ExternalMediaImportProvider._(argument: projectId, from: this);
@override
String toString() => r'externalMediaImportProvider';
}
abstract class _$ExternalMediaImport
extends $Notifier<AsyncValue<ExternalMediaSelection?>> {
late final _$args = ref.$arg as String;
String get projectId => _$args;
AsyncValue<ExternalMediaSelection?> build(String projectId);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref
as $Ref<
AsyncValue<ExternalMediaSelection?>,
AsyncValue<ExternalMediaSelection?>
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<ExternalMediaSelection?>,
AsyncValue<ExternalMediaSelection?>
>,
AsyncValue<ExternalMediaSelection?>,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args));
}
}
+49
View File
@@ -0,0 +1,49 @@
import 'dart:async';
import 'dart:io';
import 'package:cutdex_sdk/project.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'projects.dart';
part 'media_availability.g.dart';
enum MediaAvailability { available, missing, inaccessible }
@riverpod
FutureOr<MediaAvailability> mediaAvailability(
Ref ref,
String projectId,
AssetDocument asset,
) async {
try {
return await ref
.read(projectsProvider.notifier)
.withAssetMedia(
projectId,
asset,
(media) => checkMediaAvailability(media.uri),
);
} on FileSystemException catch (error) {
return error.osError?.errorCode == 2
? MediaAvailability.missing
: MediaAvailability.inaccessible;
} catch (_) {
return MediaAvailability.inaccessible;
}
}
Future<MediaAvailability> checkMediaAvailability(Uri uri) async {
if (uri.scheme != 'file') return MediaAvailability.inaccessible;
try {
final file = await File.fromUri(uri).open();
await file.close();
return MediaAvailability.available;
} on FileSystemException catch (error) {
// ENOENT on POSIX and ERROR_FILE/PATH_NOT_FOUND on Windows.
return (error.osError?.errorCode == 2 ||
(Platform.isWindows && error.osError?.errorCode == 3))
? MediaAvailability.missing
: MediaAvailability.inaccessible;
}
}
+91
View File
@@ -0,0 +1,91 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'media_availability.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(mediaAvailability)
final mediaAvailabilityProvider = MediaAvailabilityFamily._();
final class MediaAvailabilityProvider
extends
$FunctionalProvider<
AsyncValue<MediaAvailability>,
MediaAvailability,
FutureOr<MediaAvailability>
>
with
$FutureModifier<MediaAvailability>,
$FutureProvider<MediaAvailability> {
MediaAvailabilityProvider._({
required MediaAvailabilityFamily super.from,
required (String, AssetDocument) super.argument,
}) : super(
retry: null,
name: r'mediaAvailabilityProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$mediaAvailabilityHash();
@override
String toString() {
return r'mediaAvailabilityProvider'
''
'$argument';
}
@$internal
@override
$FutureProviderElement<MediaAvailability> $createElement(
$ProviderPointer pointer,
) => $FutureProviderElement(pointer);
@override
FutureOr<MediaAvailability> create(Ref ref) {
final argument = this.argument as (String, AssetDocument);
return mediaAvailability(ref, argument.$1, argument.$2);
}
@override
bool operator ==(Object other) {
return other is MediaAvailabilityProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$mediaAvailabilityHash() => r'e579c9b0cff0bfce1a719014d0298bf229809702';
final class MediaAvailabilityFamily extends $Family
with
$FunctionalFamilyOverride<
FutureOr<MediaAvailability>,
(String, AssetDocument)
> {
MediaAvailabilityFamily._()
: super(
retry: null,
name: r'mediaAvailabilityProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
MediaAvailabilityProvider call(String projectId, AssetDocument asset) =>
MediaAvailabilityProvider._(argument: (projectId, asset), from: this);
@override
String toString() => r'mediaAvailabilityProvider';
}
+8
View File
@@ -0,0 +1,8 @@
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/runtime.dart';
/// Runs generation while the workspace retains the owning project and grants.
typedef AssetMediaLoader = Future<T> Function<T>(
AssetDocument asset,
Future<T> Function(MediaReference media) action,
);
@@ -0,0 +1,23 @@
import 'package:cutdex_sdk/runtime.dart';
import '../l10n/app_localizations.dart';
extension MediaColorLabel on RenderColorSpace {
String label(AppLocalizations l10n) => switch (this) {
RenderColorSpace.rec709 => 'Rec.709',
RenderColorSpace.sRGB => 'sRGB',
RenderColorSpace.displayP3 => 'Display P3',
RenderColorSpace.rec2020HLG => 'Rec.2020 HLG',
RenderColorSpace.rec2020PQ => 'Rec.2020 PQ',
RenderColorSpace.linearRec2020 => l10n.linearRec2020,
};
}
/// A viewing assumption is separate from detected metadata and authored overrides.
RenderColorSpace? resolveMediaColor({
required RenderColorSpace? detected,
required RenderColorSpace? override,
required bool metadataReported,
}) =>
override ??
(metadataReported && detected == null ? RenderColorSpace.rec709 : null);
+85
View File
@@ -0,0 +1,85 @@
import 'package:flutter/foundation.dart'
show TargetPlatform, defaultTargetPlatform, kIsWeb;
import 'package:path/path.dart' as p;
const supportedVideoFileExtensions = <String>[
'mp4',
'mov',
'm4v',
'mkv',
'webm',
'avi',
'wmv',
'asf',
'flv',
'rm',
'rmvb',
'ts',
'mts',
'm2ts',
'mpeg',
'mpg',
'mxf',
'3gp',
];
/// Windows can probe video streams embedded in some optical-disc files.
/// Listing a candidate does not imply DVD filesystem or menu support.
List<String> get selectableVideoFileExtensions =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.windows
? const [...supportedVideoFileExtensions, 'iso']
: supportedVideoFileExtensions;
const supportedAudioFileExtensions = <String>[
'mp3',
'wav',
'aif',
'aiff',
'm4a',
'aac',
'flac',
'ogg',
'opus',
'caf',
'wma',
'amr',
'ac3',
'ape',
'wv',
'dts',
];
const supportedImageFileExtensions = <String>[
'jpg',
'jpeg',
'png',
'webp',
'heic',
'heif',
'tif',
'tiff',
'bmp',
'gif',
'avif',
];
/// Timeline drops accept playable media; images use project asset insertion.
List<String> get selectableTimelineFileExtensions => List.unmodifiable([
...selectableVideoFileExtensions,
...supportedAudioFileExtensions,
]);
/// File pickers in the media library and composer share the same candidates.
List<String> get selectableMediaFileExtensions => List.unmodifiable([
...selectableTimelineFileExtensions,
...supportedImageFileExtensions,
]);
/// A supported browser category, not a decoder capability verification.
String? mediaKindForPath(String path) {
final extension = p.extension(path).toLowerCase().replaceFirst('.', '');
if (selectableVideoFileExtensions.contains(extension)) return 'video';
if (supportedAudioFileExtensions.contains(extension)) return 'audio';
if (supportedImageFileExtensions.contains(extension)) return 'image';
return null;
}
+59
View File
@@ -0,0 +1,59 @@
import 'package:cutdex_sdk/project.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:path/path.dart' as p;
import '../errors/app_failure.dart';
part 'media_import.freezed.dart';
/// A selected local file or document supplied by a platform provider.
@freezed
sealed class ExternalMediaFile with _$ExternalMediaFile {
const ExternalMediaFile._();
const factory ExternalMediaFile({required String path}) = LocalMediaFile;
const factory ExternalMediaFile.content({
required Uri uri,
required String name,
int? byteLength,
}) = ContentMediaFile;
String? get localPath => switch (this) {
LocalMediaFile(:final path) => path,
ContentMediaFile() => null,
};
Uri get sourceUri => switch (this) {
LocalMediaFile(:final path) => p.toUri(path),
ContentMediaFile(:final uri) => uri,
};
String get displayName => switch (this) {
LocalMediaFile(:final path) => p.basename(path),
ContentMediaFile(:final name) => name,
};
}
const mediaSourceUriKey = 'cutdex.sourceUri';
String? mediaSourceLocation(AssetDocument asset) => switch (asset.storage) {
AssetStorage.external => asset.location,
AssetStorage.managed => asset.metadata[mediaSourceUriKey] as String?,
};
@freezed
abstract class MediaImportFailure with _$MediaImportFailure {
const factory MediaImportFailure({
required String name,
required AppFailure failure,
}) = _MediaImportFailure;
}
@freezed
abstract class MediaImportResult with _$MediaImportResult {
const factory MediaImportResult({
required List<AssetDocument> assets,
required int added,
required int duplicates,
required List<MediaImportFailure> failures,
}) = _MediaImportResult;
}
File diff suppressed because it is too large. Load diff
+29
View File
@@ -0,0 +1,29 @@
import 'package:flutter/foundation.dart';
import 'external_media_import.dart';
/// Import failures remain available until a visible presentation consumes them.
class MediaImportFeedbackController extends ChangeNotifier {
final _pending = <ExternalMediaSelection?>[];
bool get hasPending => _pending.isNotEmpty;
void recordResult(ExternalMediaSelection? result) {
if (result == null ||
!result.failed && result.result?.failures.isNotEmpty != true) {
return;
}
_pending.add(result);
notifyListeners();
}
void recordFailure() {
_pending.add(null);
notifyListeners();
}
List<ExternalMediaSelection?> takePending() {
final notices = List<ExternalMediaSelection?>.of(_pending);
_pending.clear();
return notices;
}
}
@@ -0,0 +1,19 @@
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
/// Convert source metadata once, without extending the range past its end.
RationalTime mediaTimelineDuration(MediaTime duration) {
final ticks =
BigInt.from(duration.numerator) *
BigInt.from(TimelineClock.ticksPerSecond) ~/
BigInt.from(duration.denominator);
if (ticks <= BigInt.zero) {
throw AppException(AppErrorCode.invalidMediaDuration);
}
if (ticks > BigInt.from(0x7fffffffffffffff)) {
throw AppException(AppErrorCode.mediaDurationOutOfRange);
}
return RationalTime.timelineTicks(ticks.toInt());
}
@@ -0,0 +1,101 @@
import 'package:cutdex/errors/app_failure.dart';
import 'dart:io';
import 'package:path/path.dart' as p;
enum ProjectLocationStatus { ready, missing, unavailable, notWritable }
class ProjectLocationDirectory {
const ProjectLocationDirectory();
Future<ProjectLocationStatus> inspect(String path) async {
if (!p.isAbsolute(path)) return ProjectLocationStatus.unavailable;
try {
final directory = Directory(path);
if (await directory.exists()) {
await _checkWritable(directory);
return ProjectLocationStatus.ready;
}
// Never recreate a missing external/network location on the system disk.
// Its mount point may still exist even though the volume is disconnected.
if (_isExternalPath(path)) return ProjectLocationStatus.unavailable;
var ancestor = directory;
while (!await ancestor.exists()) {
if (await FileSystemEntity.type(ancestor.path, followLinks: false) !=
FileSystemEntityType.notFound) {
return ProjectLocationStatus.unavailable;
}
final parent = ancestor.parent;
if (parent.path == ancestor.path) {
return ProjectLocationStatus.unavailable;
}
ancestor = parent;
}
await _checkWritable(ancestor);
return ProjectLocationStatus.missing;
} on FileSystemException catch (error) {
return _isPermissionError(error)
? ProjectLocationStatus.notWritable
: ProjectLocationStatus.unavailable;
}
}
Future<void> prepare(String path) async {
final status = await inspect(path);
if (status == ProjectLocationStatus.notWritable) {
throw AppException(AppErrorCode.projectLocationNotWritable);
}
if (status == ProjectLocationStatus.unavailable) {
throw AppException(AppErrorCode.projectLocationUnavailable);
}
try {
final directory = Directory(path);
if (status == ProjectLocationStatus.missing) {
await directory.create(recursive: true);
}
await _checkWritable(directory);
} on FileSystemException {
throw AppException(AppErrorCode.projectLocationCreateFailed);
}
}
bool _isExternalPath(String path) {
if (Platform.isWindows) {
// Only the system drive is known to be local without a volume query.
final systemDrive = Platform.environment['SystemDrive'];
return systemDrive == null ||
p.windows.rootPrefix(path).toLowerCase() !=
'${systemDrive.toLowerCase()}\\';
}
final normalized = p.normalize(path);
return const [
'/Volumes',
'/mnt',
'/media',
'/run/media',
'/net',
].any((root) => normalized == root || p.isWithin(root, normalized));
}
bool _isPermissionError(FileSystemException error) =>
(Platform.isWindows ? const [5, 19] : const [1, 13, 30]).contains(
error.osError?.errorCode,
);
Future<void> _checkWritable(Directory directory) async {
final probe = File(
p.join(
directory.path,
'.cutdex-write-$pid-${DateTime.now().microsecondsSinceEpoch}',
),
);
var created = false;
try {
await probe.create(exclusive: true);
created = true;
} finally {
if (created) await probe.delete();
}
}
}
@@ -0,0 +1,54 @@
import 'dart:io';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:path/path.dart' as p;
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../project_state.dart';
part 'project_locator.g.dart';
part 'project_locator.freezed.dart';
@Riverpod(keepAlive: true)
ProjectLocator projectLocator(Ref ref) => ProjectLocator();
/// Resolves a persisted location without opening the project database.
class ProjectLocator {
Future<ProjectLocation> locate(RecentProject project) async {
final type = await FileSystemEntity.type(project.path, followLinks: true);
return switch (type) {
FileSystemEntityType.directory => ProjectLocation.available(project),
FileSystemEntityType.notFound => ProjectLocation.unavailable(
project,
_missingAvailability(project.path),
),
_ => ProjectLocation.unavailable(project, .invalid),
};
}
ProjectAvailability _missingAvailability(String path) {
final parts = p.split(path);
if (parts.length >= 3 && parts[1] == 'Volumes') {
final volume = p.join(parts[0], parts[1], parts[2]);
if (!Directory(volume).existsSync()) return .volumeOffline;
}
return .missing;
}
}
@freezed
abstract class ProjectLocation with _$ProjectLocation {
const ProjectLocation._();
const factory ProjectLocation(RecentProject project) = _ProjectLocation;
factory ProjectLocation.available(RecentProject project) =>
ProjectLocation(project.copyWith(availability: .available));
factory ProjectLocation.unavailable(
RecentProject project,
ProjectAvailability availability,
) => ProjectLocation(project.copyWith(availability: availability));
ProjectAvailability get availability => project.availability;
}
@@ -0,0 +1,337 @@
// 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 'project_locator.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$ProjectLocation {
RecentProject get project;
/// Create a copy of ProjectLocation
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ProjectLocationCopyWith<ProjectLocation> get copyWith =>
_$ProjectLocationCopyWithImpl<ProjectLocation>(
this as ProjectLocation,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as ProjectLocation;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is ProjectLocation &&
(identical(other.project, _this.project) ||
other.project == _this.project));
}
@override
int get hashCode {
final _this = this as ProjectLocation;
return Object.hash(runtimeType, _this.project);
}
@override
String toString() {
final _this = this as ProjectLocation;
return 'ProjectLocation(project: ${_this.project})';
}
}
/// @nodoc
abstract mixin class $ProjectLocationCopyWith<$Res> {
factory $ProjectLocationCopyWith(
ProjectLocation value,
$Res Function(ProjectLocation) _then,
) = _$ProjectLocationCopyWithImpl;
@useResult
$Res call({RecentProject project});
$RecentProjectCopyWith<$Res> get project;
}
/// @nodoc
class _$ProjectLocationCopyWithImpl<$Res>
implements $ProjectLocationCopyWith<$Res> {
_$ProjectLocationCopyWithImpl(this._self, this._then);
final ProjectLocation _self;
final $Res Function(ProjectLocation) _then;
/// Create a copy of ProjectLocation
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? project = null}) {
return _then(
ProjectLocation(
null == project
? _self.project
: project // ignore: cast_nullable_to_non_nullable
as RecentProject,
),
);
}
/// Create a copy of ProjectLocation
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$RecentProjectCopyWith<$Res> get project {
return $RecentProjectCopyWith<$Res>(_self.project, (value) {
return _then(_self.copyWith(project: value));
});
}
}
/// Adds pattern-matching-related methods to [ProjectLocation].
extension ProjectLocationPatterns on ProjectLocation {
/// 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(_ProjectLocation value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _ProjectLocation() 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(_ProjectLocation value) $default,
) {
final _that = this;
switch (_that) {
case _ProjectLocation():
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(_ProjectLocation value)? $default,
) {
final _that = this;
switch (_that) {
case _ProjectLocation() 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(RecentProject project)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _ProjectLocation() when $default != null:
return $default(_that.project);
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(RecentProject project) $default,
) {
final _that = this;
switch (_that) {
case _ProjectLocation():
return $default(_that.project);
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(RecentProject project)? $default,
) {
final _that = this;
switch (_that) {
case _ProjectLocation() when $default != null:
return $default(_that.project);
case _:
return null;
}
}
}
/// @nodoc
class _ProjectLocation extends ProjectLocation {
const _ProjectLocation(this.project) : super._();
@override
final RecentProject project;
/// Create a copy of ProjectLocation
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ProjectLocationCopyWith<_ProjectLocation> get copyWith =>
__$ProjectLocationCopyWithImpl<_ProjectLocation>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _ProjectLocation &&
(identical(other.project, project) || other.project == project));
}
@override
int get hashCode {
return Object.hash(runtimeType, project);
}
@override
String toString() {
return 'ProjectLocation(project: $project)';
}
}
/// @nodoc
abstract mixin class _$ProjectLocationCopyWith<$Res>
implements $ProjectLocationCopyWith<$Res> {
factory _$ProjectLocationCopyWith(
_ProjectLocation value,
$Res Function(_ProjectLocation) _then,
) = __$ProjectLocationCopyWithImpl;
@override
@useResult
$Res call({RecentProject project});
@override
$RecentProjectCopyWith<$Res> get project;
}
/// @nodoc
class __$ProjectLocationCopyWithImpl<$Res>
implements _$ProjectLocationCopyWith<$Res> {
__$ProjectLocationCopyWithImpl(this._self, this._then);
final _ProjectLocation _self;
final $Res Function(_ProjectLocation) _then;
/// Create a copy of ProjectLocation
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? project = null}) {
return _then(
_ProjectLocation(
null == project
? _self.project
: project // ignore: cast_nullable_to_non_nullable
as RecentProject,
),
);
}
/// Create a copy of ProjectLocation
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$RecentProjectCopyWith<$Res> get project {
return $RecentProjectCopyWith<$Res>(_self.project, (value) {
return _then(_self.copyWith(project: value));
});
}
}
@@ -0,0 +1,51 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'project_locator.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(projectLocator)
final projectLocatorProvider = ProjectLocatorProvider._();
final class ProjectLocatorProvider
extends $FunctionalProvider<ProjectLocator, ProjectLocator, ProjectLocator>
with $Provider<ProjectLocator> {
ProjectLocatorProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'projectLocatorProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$projectLocatorHash();
@$internal
@override
$ProviderElement<ProjectLocator> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
ProjectLocator create(Ref ref) {
return projectLocator(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(ProjectLocator value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<ProjectLocator>(value),
);
}
}
String _$projectLocatorHash() => r'b20be00ffdfc988f6e3eacd3af000be913568322';
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,70 @@
import 'package:drift/drift.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../persistence/app_database.dart';
import '../project_state.dart';
part 'recent_projects.g.dart';
@Riverpod(keepAlive: true)
RecentProjectsRepository recentProjects(Ref ref) =>
DriftRecentProjectsRepository(ref.watch(appDatabaseProvider));
abstract interface class RecentProjectsRepository {
Future<String?> lastTimeline(String projectId);
Future<void> rememberTimeline(String projectId, String timelineId);
Future<List<RecentProject>> load();
Future<void> save(List<RecentProject> projects);
}
class DriftRecentProjectsRepository implements RecentProjectsRepository {
DriftRecentProjectsRepository(this._database);
final AppDatabase _database;
@override
Future<String?> lastTimeline(String projectId) =>
(_database.select(_database.lastOpenedTimelines)
..where((table) => table.projectId.equals(projectId)))
.getSingleOrNull()
.then((row) => row?.timelineId);
@override
Future<void> rememberTimeline(String projectId, String timelineId) =>
_database
.into(_database.lastOpenedTimelines)
.insertOnConflictUpdate(
LastOpenedTimelinesCompanion.insert(
projectId: projectId,
timelineId: timelineId,
),
);
@override
Future<List<RecentProject>> load() async {
final rows = await (_database.select(
_database.recentProjectRecords,
)..orderBy([(table) => OrderingTerm.asc(table.position)])).get();
return [
for (final row in rows)
RecentProject(id: row.id, name: row.name, path: row.path),
];
}
@override
Future<void> save(List<RecentProject> projects) =>
_database.transaction(() async {
await _database.delete(_database.recentProjectRecords).go();
await _database.batch((batch) {
batch.insertAll(_database.recentProjectRecords, [
for (final (position, project) in projects.indexed)
RecentProjectRecordsCompanion.insert(
id: project.id,
name: project.name,
path: project.path,
position: position,
),
]);
});
});
}
@@ -0,0 +1,57 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'recent_projects.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(recentProjects)
final recentProjectsProvider = RecentProjectsProvider._();
final class RecentProjectsProvider
extends
$FunctionalProvider<
RecentProjectsRepository,
RecentProjectsRepository,
RecentProjectsRepository
>
with $Provider<RecentProjectsRepository> {
RecentProjectsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'recentProjectsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$recentProjectsHash();
@$internal
@override
$ProviderElement<RecentProjectsRepository> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
RecentProjectsRepository create(Ref ref) {
return recentProjects(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(RecentProjectsRepository value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<RecentProjectsRepository>(value),
);
}
}
String _$recentProjectsHash() => r'ca0054cd01bba053c99058ffadd6342bae057ed6';
@@ -0,0 +1,12 @@
/// Names already chosen by the caller, persisted verbatim on creation.
final class TimelineCreationNames {
const TimelineCreationNames({
required this.timeline,
required this.sequence,
required this.storyline,
});
final String timeline;
final String sequence;
final String storyline;
}
@@ -0,0 +1,44 @@
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'media_timeline_duration.dart';
/// Validated source metadata shared by timeline insertion entry points.
final class PreparedMediaMetadata {
PreparedMediaMetadata._({
required this.duration,
required this.kind,
required this.hasAudio,
required List<MediaTrackTiming> audioTracks,
}) : audioTracks = List.unmodifiable(audioTracks);
factory PreparedMediaMetadata.image() => PreparedMediaMetadata._(
duration: RationalTime.seconds(5),
kind: EditorMediaKind.image,
hasAudio: false,
audioTracks: const [],
);
factory PreparedMediaMetadata.fromInfo(MediaInfo info) {
if (info.isProtected ||
(info.videoTrackCount == 0 && info.audioTrackCount == 0)) {
throw AppException(AppErrorCode.mediaNoTracks);
}
return PreparedMediaMetadata._(
duration: mediaTimelineDuration(info.duration),
kind: info.videoTrackCount > 0
? EditorMediaKind.video
: EditorMediaKind.audio,
hasAudio: info.audioTrackCount > 0,
audioTracks: info.audioTracks,
);
}
final RationalTime duration;
final EditorMediaKind kind;
final bool hasAudio;
final List<MediaTrackTiming> audioTracks;
}
@@ -0,0 +1,109 @@
import 'dart:async';
import 'package:cutdex_sdk/preview.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'preview_target.dart';
import 'timeline_session.dart';
part 'preview_controller_registry.g.dart';
@Riverpod(keepAlive: true)
PreviewControllerRegistry previewControllerRegistry(Ref ref) {
final registry = PreviewControllerRegistry(
ref.read(runtimeConnectionProvider),
);
ref.onDispose(registry.dispose);
return registry;
}
/// Owns native preview controllers independently of the currently visible
/// timeline. Prepared controllers make timeline selection a synchronous swap.
final class PreviewControllerRegistry {
PreviewControllerRegistry(this._runtime);
final CutdexRuntime _runtime;
final _controllers = <(String, String), PreviewController>{};
final _preparing = <(String, String), Future<PreviewController>>{};
bool _disposed = false;
PreviewController? cached((String, String) ids) => _controllers[ids];
FutureOr<PreviewController?> prepare(
(String, String) ids,
EditorTimelineSession timeline,
) {
if (_disposed) throw StateError('Preview registry is closed');
final sequence = timeline.activeSequenceId;
if (sequence == null || timeline.sequenceDurationTicks(sequence) == 0) {
return null;
}
final cached = _controllers[ids];
if (cached != null) return cached;
final pending = _preparing[ids];
if (pending != null) return pending;
final future = _initialize(ids, timeline);
_preparing[ids] = future;
return future;
}
Future<PreviewController> _initialize(
(String, String) ids,
EditorTimelineSession timeline,
) async {
final controller = PreviewController(
timeline: timeline,
activeSequence: () => timeline.activeSequenceId,
viewForSequence: timeline.view,
runtime: _runtime,
);
try {
await controller.initialize();
if (_disposed) {
await controller.close();
throw StateError('Preview registry is closed');
}
_controllers[ids] = controller;
return controller;
} catch (_) {
await controller.close().catchError((Object _) {});
rethrow;
} finally {
_preparing.remove(ids);
}
}
Future<void> invalidate((String, String) ids) async {
final controller = _controllers.remove(ids);
if (controller != null) await controller.close();
}
Future<void> retainProject(
String projectId, {
Set<String> keep = const {},
}) async {
for (final entry in _controllers.entries.toList()) {
if (entry.key.$1 != projectId && keep.contains(entry.key.$1)) {
await entry.value.pauseForCanvasInteraction();
}
}
final stale = _controllers.keys
.where((ids) => ids.$1 != projectId && !keep.contains(ids.$1))
.toList();
for (final ids in stale) {
await invalidate(ids);
}
}
void dispose() {
if (_disposed) return;
_disposed = true;
final controllers = _controllers.values.toList();
_controllers.clear();
_preparing.clear();
for (final controller in controllers) {
unawaited(controller.close().catchError((Object _) {}));
}
}
}
@@ -0,0 +1,58 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'preview_controller_registry.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(previewControllerRegistry)
final previewControllerRegistryProvider = PreviewControllerRegistryProvider._();
final class PreviewControllerRegistryProvider
extends
$FunctionalProvider<
PreviewControllerRegistry,
PreviewControllerRegistry,
PreviewControllerRegistry
>
with $Provider<PreviewControllerRegistry> {
PreviewControllerRegistryProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'previewControllerRegistryProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$previewControllerRegistryHash();
@$internal
@override
$ProviderElement<PreviewControllerRegistry> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
PreviewControllerRegistry create(Ref ref) {
return previewControllerRegistry(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(PreviewControllerRegistry value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<PreviewControllerRegistry>(value),
);
}
}
String _$previewControllerRegistryHash() =>
r'ec6788d52acb279d31cd745f0e244d604f09a890';
+244
View File
@@ -0,0 +1,244 @@
import 'dart:async';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/preview.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import 'projects.dart';
import '../diagnostics/app_diagnostics.dart';
part 'preview_target.g.dart';
part 'preview_target.freezed.dart';
@Riverpod(keepAlive: true)
CutdexRuntime runtimeConnection(Ref ref) =>
CutdexRuntime(diagnostics: AppDiagnostics.report);
@Riverpod(keepAlive: true)
Raw<PreviewTarget> previewTarget(Ref ref, String projectId, String timelineId) {
final target = PreviewTarget(
createSource: (asset, tick, remember) {
final timeline = ref
.read(projectsProvider.notifier)
.cachedTimelineSession(projectId, timelineId);
final sequence = timeline?.activeSequenceId;
return SourcePreviewController(
loadMedia: <T>(action) => ref
.read(projectsProvider.notifier)
.withAssetMedia(projectId, asset, action),
frameDuration: sequence == null
? TimelineFormat.fps30.frameDuration
: timeline!.persistence.timeline(sequence).format.frameDuration,
positionTick: tick,
rememberPosition: remember,
runtime: ref.read(runtimeConnectionProvider),
);
},
beforeOpen: () async {
final session = await ref
.read(projectsProvider.notifier)
.openTimelineSession(projectId, timelineId);
final sequence = session.activeSequenceId;
if (sequence != null &&
session.preview?.queryPreview(sequence).available == true) {
await session.preview!.controlPreview(sequence, PreviewAction.pause);
}
},
);
ref.listen(projectsProvider, (_, next) {
final state = next.asData?.value;
if (state != null &&
(state.activeProject?.id != projectId ||
state.timeline?.id != timelineId)) {
unawaited(target.closeSource().catchError((Object _) {}));
}
});
ref.onDispose(target.dispose);
return target;
}
@freezed
sealed class PreviewTargetState with _$PreviewTargetState {
const factory PreviewTargetState.timeline() = TimelinePreviewTarget;
const factory PreviewTargetState.source(
AssetDocument asset,
SourcePreviewController? controller, {
@Default(true) bool opening,
Object? error,
}) = SourcePreviewTarget;
}
@Riverpod(keepAlive: true)
class PreviewNavigation extends _$PreviewNavigation {
late PreviewTarget _target;
@override
PreviewTargetState build(String projectId, String timelineId) {
final target = _target = ref.watch(
previewTargetProvider(projectId, timelineId),
);
void changed() {
if (ref.mounted) state = target.state;
}
target.addListener(changed);
ref.onDispose(() => target.removeListener(changed));
return target.state;
}
void showAsset(AssetDocument asset) => _target.showAsset(asset);
Future<void> openSource(AssetDocument asset) => _target.openSource(asset);
void showTimeline() => _target.showTimeline();
}
typedef SourcePreviewFactory = SourcePreviewController Function(
AssetDocument asset,
int position,
void Function(int) remember,
);
/// Owns source navigation and its one controller; widgets only render it.
class PreviewTarget extends ChangeNotifier {
PreviewTarget({this.createSource, this.beforeOpen});
final SourcePreviewFactory? createSource;
final Future<void> Function()? beforeOpen;
PreviewTargetState _state = const PreviewTargetState.timeline();
PreviewTargetState get state => _state;
AssetDocument? get asset => switch (_state) {
SourcePreviewTarget(:final asset) => asset,
_ => null,
};
SourcePreviewController? get source => switch (_state) {
SourcePreviewTarget(:final controller) => controller,
_ => null,
};
VoidCallback? togglePlayback;
final positions = <String, int>{};
Future<void> _opening = Future.value();
Future<void> _closing = Future.value();
bool _disposed = false;
void showAsset(AssetDocument value) {
unawaited(openSource(value).catchError((Object _) {}));
}
Future<void> openSource(AssetDocument value) {
if (_disposed) return Future.error(StateError('Preview target is closed'));
if (asset?.id == value.id && source?.error == null) return _opening;
final previous = source;
final closing = previous == null
? Future<void>.value()
: previous.close().whenComplete(previous.dispose);
_closing = Future.wait([_closing.catchError((Object _) {}), closing])
.then((_) {});
unawaited(_closing.catchError((Object _) {}));
final created = createSource?.call(
value,
positions[value.id] ?? 0,
(tick) => positions[value.id] = tick,
);
_state = PreviewTargetState.source(value, created);
togglePlayback = created == null
? null
: () => unawaited(created.togglePlayback());
_opening =
() async {
await _closing;
if (created == null) {
if (!_disposed && asset?.id == value.id) {
_state = PreviewTargetState.source(
value,
created,
opening: false,
);
notifyListeners();
}
return;
}
if (_disposed || !identical(source, created)) {
throw StateError('Source preview changed');
}
await created.initialize(beforeOpen?.call() ?? Future<void>.value());
if (_disposed || !identical(source, created)) {
throw StateError('Source preview changed');
}
if (created.error != null) throw StateError('Source preview failed');
_state = PreviewTargetState.source(value, created, opening: false);
notifyListeners();
}().catchError((Object error, StackTrace stack) {
AppDiagnostics.failure(
'preview',
'openSource',
error,
stack,
context: {'mediaId': value.id},
);
if (!_disposed &&
identical(source, created) &&
asset?.id == value.id) {
_state = PreviewTargetState.source(
value,
created,
opening: false,
error: error,
);
notifyListeners();
}
Error.throwWithStackTrace(error, stack);
});
notifyListeners();
return _opening;
}
void showTimeline() {
unawaited(closeSource().catchError((Object _) {}));
}
Future<void> closeSource() {
final previous = source;
_state = const PreviewTargetState.timeline();
togglePlayback = null;
if (!_disposed) notifyListeners();
final closing = previous == null
? Future<void>.value()
: previous.close().whenComplete(previous.dispose);
_closing = Future.wait([_closing.catchError((Object _) {}), closing])
.then((_) {});
unawaited(_closing.catchError((Object _) {}));
return _closing;
}
Future<void> control(
String mediaId,
SourcePreviewAction action, {
CommandTime? at,
}) async {
if (asset?.id != mediaId || source == null) {
throw const CommandRejected(
'sourceUnavailable',
'Open the addressed source first',
);
}
final current = source!;
await _opening;
if (!identical(source, current) || asset?.id != mediaId) {
throw const CommandRejected('sourceChanged', 'Source preview changed');
}
await current.control(action, at: at);
if (!identical(source, current)) {
throw StateError('Source changed during control');
}
}
@override
void dispose() {
if (_disposed) return;
_disposed = true;
unawaited(closeSource().catchError((Object _) {}));
super.dispose();
}
}
+391
View File
@@ -0,0 +1,391 @@
// 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 'preview_target.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$PreviewTargetState implements DiagnosticableTreeMixin {
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties..add(DiagnosticsProperty('type', 'PreviewTargetState'));
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is PreviewTargetState);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return 'PreviewTargetState()';
}
}
/// @nodoc
class $PreviewTargetStateCopyWith<$Res> {
$PreviewTargetStateCopyWith(
PreviewTargetState _,
$Res Function(PreviewTargetState) __,
);
}
/// Adds pattern-matching-related methods to [PreviewTargetState].
extension PreviewTargetStatePatterns on PreviewTargetState {
/// 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(TimelinePreviewTarget value)? timeline,
TResult Function(SourcePreviewTarget value)? source,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case TimelinePreviewTarget() when timeline != null:
return timeline(_that);
case SourcePreviewTarget() when source != null:
return source(_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(TimelinePreviewTarget value) timeline,
required TResult Function(SourcePreviewTarget value) source,
}) {
final _that = this;
switch (_that) {
case TimelinePreviewTarget():
return timeline(_that);
case SourcePreviewTarget():
return source(_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(TimelinePreviewTarget value)? timeline,
TResult? Function(SourcePreviewTarget value)? source,
}) {
final _that = this;
switch (_that) {
case TimelinePreviewTarget() when timeline != null:
return timeline(_that);
case SourcePreviewTarget() when source != null:
return source(_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()? timeline,
TResult Function(
AssetDocument asset,
SourcePreviewController? controller,
bool opening,
Object? error,
)?
source,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case TimelinePreviewTarget() when timeline != null:
return timeline();
case SourcePreviewTarget() when source != null:
return source(
_that.asset,
_that.controller,
_that.opening,
_that.error,
);
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() timeline,
required TResult Function(
AssetDocument asset,
SourcePreviewController? controller,
bool opening,
Object? error,
)
source,
}) {
final _that = this;
switch (_that) {
case TimelinePreviewTarget():
return timeline();
case SourcePreviewTarget():
return source(
_that.asset,
_that.controller,
_that.opening,
_that.error,
);
}
}
/// 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()? timeline,
TResult? Function(
AssetDocument asset,
SourcePreviewController? controller,
bool opening,
Object? error,
)?
source,
}) {
final _that = this;
switch (_that) {
case TimelinePreviewTarget() when timeline != null:
return timeline();
case SourcePreviewTarget() when source != null:
return source(
_that.asset,
_that.controller,
_that.opening,
_that.error,
);
case _:
return null;
}
}
}
/// @nodoc
class TimelinePreviewTarget
with DiagnosticableTreeMixin
implements PreviewTargetState {
const TimelinePreviewTarget();
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties..add(DiagnosticsProperty('type', 'PreviewTargetState.timeline'));
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is TimelinePreviewTarget);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return 'PreviewTargetState.timeline()';
}
}
/// @nodoc
class SourcePreviewTarget
with DiagnosticableTreeMixin
implements PreviewTargetState {
const SourcePreviewTarget(
this.asset,
this.controller, {
this.opening = true,
this.error,
});
final AssetDocument asset;
final SourcePreviewController? controller;
@JsonKey()
final bool opening;
final Object? error;
/// Create a copy of PreviewTargetState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SourcePreviewTargetCopyWith<SourcePreviewTarget> get copyWith =>
_$SourcePreviewTargetCopyWithImpl<SourcePreviewTarget>(this, _$identity);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'PreviewTargetState.source'))
..add(DiagnosticsProperty('asset', asset))
..add(DiagnosticsProperty('controller', controller))
..add(DiagnosticsProperty('opening', opening))
..add(DiagnosticsProperty('error', error));
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is SourcePreviewTarget &&
(identical(other.asset, asset) || other.asset == asset) &&
(identical(other.controller, controller) ||
other.controller == controller) &&
(identical(other.opening, opening) || other.opening == opening) &&
const DeepCollectionEquality().equals(other.error, error));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
asset,
controller,
opening,
const DeepCollectionEquality().hash(error),
);
}
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return 'PreviewTargetState.source(asset: $asset, controller: $controller, opening: $opening, error: $error)';
}
}
/// @nodoc
abstract mixin class $SourcePreviewTargetCopyWith<$Res>
implements $PreviewTargetStateCopyWith<$Res> {
factory $SourcePreviewTargetCopyWith(
SourcePreviewTarget value,
$Res Function(SourcePreviewTarget) _then,
) = _$SourcePreviewTargetCopyWithImpl;
@useResult
$Res call({
AssetDocument asset,
SourcePreviewController? controller,
bool opening,
Object? error,
});
}
/// @nodoc
class _$SourcePreviewTargetCopyWithImpl<$Res>
implements $SourcePreviewTargetCopyWith<$Res> {
_$SourcePreviewTargetCopyWithImpl(this._self, this._then);
final SourcePreviewTarget _self;
final $Res Function(SourcePreviewTarget) _then;
/// Create a copy of PreviewTargetState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
$Res call({
Object? asset = null,
Object? controller = freezed,
Object? opening = null,
Object? error = freezed,
}) {
return _then(
SourcePreviewTarget(
null == asset
? _self.asset
: asset // ignore: cast_nullable_to_non_nullable
as AssetDocument,
freezed == controller
? _self.controller
: controller // ignore: cast_nullable_to_non_nullable
as SourcePreviewController?,
opening: null == opening
? _self.opening
: opening // ignore: cast_nullable_to_non_nullable
as bool,
error: freezed == error ? _self.error : error,
),
);
}
}
+235
View File
@@ -0,0 +1,235 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'preview_target.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(runtimeConnection)
final runtimeConnectionProvider = RuntimeConnectionProvider._();
final class RuntimeConnectionProvider
extends $FunctionalProvider<CutdexRuntime, CutdexRuntime, CutdexRuntime>
with $Provider<CutdexRuntime> {
RuntimeConnectionProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'runtimeConnectionProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$runtimeConnectionHash();
@$internal
@override
$ProviderElement<CutdexRuntime> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
CutdexRuntime create(Ref ref) {
return runtimeConnection(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(CutdexRuntime value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<CutdexRuntime>(value),
);
}
}
String _$runtimeConnectionHash() => r'd185bc1cb6bb09b060b1d53ccf09097ac56f910c';
@ProviderFor(previewTarget)
final previewTargetProvider = PreviewTargetFamily._();
final class PreviewTargetProvider
extends
$FunctionalProvider<
Raw<PreviewTarget>,
Raw<PreviewTarget>,
Raw<PreviewTarget>
>
with $Provider<Raw<PreviewTarget>> {
PreviewTargetProvider._({
required PreviewTargetFamily super.from,
required (String, String) super.argument,
}) : super(
retry: null,
name: r'previewTargetProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$previewTargetHash();
@override
String toString() {
return r'previewTargetProvider'
''
'$argument';
}
@$internal
@override
$ProviderElement<Raw<PreviewTarget>> $createElement(
$ProviderPointer pointer,
) => $ProviderElement(pointer);
@override
Raw<PreviewTarget> create(Ref ref) {
final argument = this.argument as (String, String);
return previewTarget(ref, argument.$1, argument.$2);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(Raw<PreviewTarget> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<Raw<PreviewTarget>>(value),
);
}
@override
bool operator ==(Object other) {
return other is PreviewTargetProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$previewTargetHash() => r'89b3bfb214aa3bebed0086d73b15c5f9fd5cfea1';
final class PreviewTargetFamily extends $Family
with $FunctionalFamilyOverride<Raw<PreviewTarget>, (String, String)> {
PreviewTargetFamily._()
: super(
retry: null,
name: r'previewTargetProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
PreviewTargetProvider call(String projectId, String timelineId) =>
PreviewTargetProvider._(argument: (projectId, timelineId), from: this);
@override
String toString() => r'previewTargetProvider';
}
@ProviderFor(PreviewNavigation)
final previewNavigationProvider = PreviewNavigationFamily._();
final class PreviewNavigationProvider
extends $NotifierProvider<PreviewNavigation, PreviewTargetState> {
PreviewNavigationProvider._({
required PreviewNavigationFamily super.from,
required (String, String) super.argument,
}) : super(
retry: null,
name: r'previewNavigationProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$previewNavigationHash();
@override
String toString() {
return r'previewNavigationProvider'
''
'$argument';
}
@$internal
@override
PreviewNavigation create() => PreviewNavigation();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(PreviewTargetState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<PreviewTargetState>(value),
);
}
@override
bool operator ==(Object other) {
return other is PreviewNavigationProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$previewNavigationHash() => r'c19564d7ba2764444380bceb154c9d7e06431f80';
final class PreviewNavigationFamily extends $Family
with
$ClassFamilyOverride<
PreviewNavigation,
PreviewTargetState,
PreviewTargetState,
PreviewTargetState,
(String, String)
> {
PreviewNavigationFamily._()
: super(
retry: null,
name: r'previewNavigationProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
PreviewNavigationProvider call(String projectId, String timelineId) =>
PreviewNavigationProvider._(
argument: (projectId, timelineId),
from: this,
);
@override
String toString() => r'previewNavigationProvider';
}
abstract class _$PreviewNavigation extends $Notifier<PreviewTargetState> {
late final _$args = ref.$arg as (String, String);
String get projectId => _$args.$1;
String get timelineId => _$args.$2;
PreviewTargetState build(String projectId, String timelineId);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<PreviewTargetState, PreviewTargetState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<PreviewTargetState, PreviewTargetState>,
PreviewTargetState,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
}
}
+14
View File
@@ -0,0 +1,14 @@
import 'package:cutdex_sdk/project.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'project_assets_changed.freezed.dart';
@freezed
abstract class ProjectAssetsChanged with _$ProjectAssetsChanged {
factory ProjectAssetsChanged(String projectId, List<AssetDocument> assets) =>
ProjectAssetsChanged.snapshot(projectId, List.unmodifiable(assets));
const factory ProjectAssetsChanged.snapshot(
String projectId,
List<AssetDocument> assets,
) = _ProjectAssetsChanged;
}
@@ -0,0 +1,344 @@
// 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 'project_assets_changed.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$ProjectAssetsChanged {
String get projectId;
List<AssetDocument> get assets;
/// Create a copy of ProjectAssetsChanged
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ProjectAssetsChangedCopyWith<ProjectAssetsChanged> get copyWith =>
_$ProjectAssetsChangedCopyWithImpl<ProjectAssetsChanged>(
this as ProjectAssetsChanged,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as ProjectAssetsChanged;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is ProjectAssetsChanged &&
(identical(other.projectId, _this.projectId) ||
other.projectId == _this.projectId) &&
const DeepCollectionEquality().equals(other.assets, _this.assets));
}
@override
int get hashCode {
final _this = this as ProjectAssetsChanged;
return Object.hash(
runtimeType,
_this.projectId,
const DeepCollectionEquality().hash(_this.assets),
);
}
@override
String toString() {
final _this = this as ProjectAssetsChanged;
return 'ProjectAssetsChanged(projectId: ${_this.projectId}, assets: ${_this.assets})';
}
}
/// @nodoc
abstract mixin class $ProjectAssetsChangedCopyWith<$Res> {
factory $ProjectAssetsChangedCopyWith(
ProjectAssetsChanged value,
$Res Function(ProjectAssetsChanged) _then,
) = _$ProjectAssetsChangedCopyWithImpl;
@useResult
$Res call({String projectId, List<AssetDocument> assets});
}
/// @nodoc
class _$ProjectAssetsChangedCopyWithImpl<$Res>
implements $ProjectAssetsChangedCopyWith<$Res> {
_$ProjectAssetsChangedCopyWithImpl(this._self, this._then);
final ProjectAssetsChanged _self;
final $Res Function(ProjectAssetsChanged) _then;
/// Create a copy of ProjectAssetsChanged
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? projectId = null, Object? assets = null}) {
return _then(
ProjectAssetsChanged(
null == projectId
? _self.projectId
: projectId // ignore: cast_nullable_to_non_nullable
as String,
null == assets
? _self.assets
: assets // ignore: cast_nullable_to_non_nullable
as List<AssetDocument>,
),
);
}
}
/// Adds pattern-matching-related methods to [ProjectAssetsChanged].
extension ProjectAssetsChangedPatterns on ProjectAssetsChanged {
/// 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(_ProjectAssetsChanged value)? snapshot,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _ProjectAssetsChanged() when snapshot != null:
return snapshot(_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(_ProjectAssetsChanged value) snapshot,
}) {
final _that = this;
switch (_that) {
case _ProjectAssetsChanged():
return snapshot(_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(_ProjectAssetsChanged value)? snapshot,
}) {
final _that = this;
switch (_that) {
case _ProjectAssetsChanged() when snapshot != null:
return snapshot(_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(String projectId, List<AssetDocument> assets)? snapshot,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _ProjectAssetsChanged() when snapshot != null:
return snapshot(_that.projectId, _that.assets);
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(String projectId, List<AssetDocument> assets)
snapshot,
}) {
final _that = this;
switch (_that) {
case _ProjectAssetsChanged():
return snapshot(_that.projectId, _that.assets);
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(String projectId, List<AssetDocument> assets)? snapshot,
}) {
final _that = this;
switch (_that) {
case _ProjectAssetsChanged() when snapshot != null:
return snapshot(_that.projectId, _that.assets);
case _:
return null;
}
}
}
/// @nodoc
class _ProjectAssetsChanged implements ProjectAssetsChanged {
const _ProjectAssetsChanged(this.projectId, List<AssetDocument> assets)
: _assets = assets;
@override
final String projectId;
final List<AssetDocument> _assets;
@override
List<AssetDocument> get assets {
if (_assets is EqualUnmodifiableListView) return _assets;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_assets);
}
/// Create a copy of ProjectAssetsChanged
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ProjectAssetsChangedCopyWith<_ProjectAssetsChanged> get copyWith =>
__$ProjectAssetsChangedCopyWithImpl<_ProjectAssetsChanged>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _ProjectAssetsChanged &&
(identical(other.projectId, projectId) ||
other.projectId == projectId) &&
const DeepCollectionEquality().equals(other.assets, _assets));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
projectId,
const DeepCollectionEquality().hash(_assets),
);
}
@override
String toString() {
return 'ProjectAssetsChanged.snapshot(projectId: $projectId, assets: $assets)';
}
}
/// @nodoc
abstract mixin class _$ProjectAssetsChangedCopyWith<$Res>
implements $ProjectAssetsChangedCopyWith<$Res> {
factory _$ProjectAssetsChangedCopyWith(
_ProjectAssetsChanged value,
$Res Function(_ProjectAssetsChanged) _then,
) = __$ProjectAssetsChangedCopyWithImpl;
@override
@useResult
$Res call({String projectId, List<AssetDocument> assets});
}
/// @nodoc
class __$ProjectAssetsChangedCopyWithImpl<$Res>
implements _$ProjectAssetsChangedCopyWith<$Res> {
__$ProjectAssetsChangedCopyWithImpl(this._self, this._then);
final _ProjectAssetsChanged _self;
final $Res Function(_ProjectAssetsChanged) _then;
/// Create a copy of ProjectAssetsChanged
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? projectId = null, Object? assets = null}) {
return _then(
_ProjectAssetsChanged(
null == projectId
? _self.projectId
: projectId // ignore: cast_nullable_to_non_nullable
as String,
null == assets
? _self._assets
: assets // ignore: cast_nullable_to_non_nullable
as List<AssetDocument>,
),
);
}
}
+41
View File
@@ -0,0 +1,41 @@
import 'package:cutdex_sdk/project.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../errors/app_failure.dart';
part 'project_state.freezed.dart';
enum ProjectAvailability {
available,
missing,
volumeOffline,
invalid,
unavailable;
bool get canOpen => this == available;
}
@freezed
abstract class RecentProject with _$RecentProject {
const factory RecentProject({
required String id,
required String name,
required String path,
@Default(ProjectAvailability.available) ProjectAvailability availability,
}) = _RecentProject;
}
@freezed
abstract class ProjectState with _$ProjectState {
const factory ProjectState({
@Default([]) List<RecentProject> recent,
RecentProject? activeProject,
@Default([]) List<TimelineSummary> timelines,
@Default([]) List<AssetDocument> assets,
TimelineDocument? timeline,
@Default(false) bool projectBusy,
String? openingTimelineId,
@Default(false) bool creatingTimeline,
AppFailure? error,
}) = _ProjectState;
}
File diff suppressed because it is too large. Load diff
+754
View File
@@ -0,0 +1,754 @@
import 'package:cutdex/errors/app_failure.dart';
import 'dart:async';
import 'dart:io';
import 'dart:ui' show PlatformDispatcher;
import '../diagnostics/app_diagnostics.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart' as p;
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../features/settings/language_settings.dart';
import '../l10n/app_localizations.dart';
import '../integrations/app_failure_adapter.dart';
import 'project_state.dart';
import 'media_import.dart';
import 'timeline_session.dart';
import 'background_task_registry.dart';
import 'timeline_view_state.dart';
import 'preview_controller_registry.dart';
import 'package:cutdex_sdk/editor.dart';
import '../integrations/runtime/processing_configuration.dart';
import 'persistence/project_workspace.dart';
import 'persistence/timeline_creation_names.dart';
import 'persistence/project_locator.dart';
import 'persistence/recent_projects.dart';
import 'persistence/project_location_directory.dart';
import '../persistence/app_settings_repositories.dart';
part 'projects.g.dart';
@Riverpod(keepAlive: true)
class Projects extends _$Projects {
static const maxTimelineCount = 50;
late ProjectWorkspace _workspace;
bool _workspaceReady = false;
AppLocalizations get _localizations {
final configured = ref.read(languageSettingsProvider).asData?.value;
final locale =
configured?.locale ??
resolveAppLocale(
PlatformDispatcher.instance.locales,
AppLocalizations.supportedLocales,
);
return lookupAppLocalizations(locale);
}
TimelineCreationNames _creationNames([String? timelineName]) {
final l10n = _localizations;
return TimelineCreationNames(
timeline: timelineName ?? l10n.defaultTimelineName(1),
sequence: l10n.primarySequence,
storyline: l10n.primaryStoryline,
);
}
EditorTimelineSession? cachedTimelineSession(
String projectId,
String timelineId,
) {
if (!_workspaceReady || state.value?.activeProject?.id != projectId) {
return null;
}
return _workspace.cachedTimelineSession(projectId, timelineId);
}
Future<T> withAssetMedia<T>(
String? projectId,
AssetDocument asset,
Future<T> Function(MediaReference media) action,
) async {
await future;
if (projectId == null) throw AppException(AppErrorCode.openProjectFirst);
return _workspace.withAssetMedia(projectId, asset, action);
}
@override
Future<ProjectState> build() async {
try {
await ref.read(languageSettingsProvider.future);
} catch (error, stackTrace) {
AppDiagnostics.failure('project', 'loadLanguage', error, stackTrace);
}
String? resources;
try {
resources = await ref
.read(resourceLocationSettingsRepositoryProvider)
.load();
} catch (error, stackTrace) {
AppDiagnostics.failure(
'project',
'loadResourceLocation',
error,
stackTrace,
);
}
final workspace = ProjectWorkspace(
creationNames: _creationNames(),
processing: ProcessingConfiguration.configured(
diagnostics: AppDiagnostics.report,
resourcesRoot: resources,
),
backgroundTasks: ref.read(backgroundTaskRegistryProvider),
);
_workspace = workspace;
_workspaceReady = true;
ref.onDispose(() => unawaited(workspace.close()));
final assetSubscription = workspace.assetChanges.listen((event) {
final current = state.value;
if (ref.mounted && current?.activeProject?.id == event.projectId) {
state = AsyncData(current!.copyWith(assets: event.assets));
}
});
ref.onDispose(() => unawaited(assetSubscription.cancel()));
try {
final repository = ref.read(recentProjectsProvider);
final recent = await repository.load();
final locations = await Future.wait([
for (final project in recent)
ref.read(projectLocatorProvider).locate(project),
]);
final resolved = [for (final location in locations) location.project];
return ProjectState(recent: resolved);
} catch (error, stackTrace) {
AppDiagnostics.failure(
'project',
'loadRecentProjects',
error,
stackTrace,
);
return const ProjectState(
error: AppFailure(AppErrorCode.loadRecentProjectsFailed),
);
}
}
/// Freeze workspace commands before closing; failed saves leave it recoverable.
Future<bool> prepareToQuit() async {
await future;
final current = state.requireValue;
if (current.projectBusy ||
current.creatingTimeline ||
current.openingTimelineId != null ||
_workspace.hasBackgroundTasks) {
throw PlatformException(code: 'workspaceBusy');
}
state = AsyncData(state.requireValue.copyWith(projectBusy: true));
try {
await _workspace.close();
await AppDiagnostics.instance?.store.flush();
return true;
} catch (error, stack) {
AppDiagnostics.failure('project', 'close', error, stack);
state = AsyncData(state.requireValue.copyWith(projectBusy: false));
throw PlatformException(code: 'saveFailed');
}
}
Future<bool> _perform(Future<void> Function() action) async {
await future;
if (!ref.mounted || state.requireValue.projectBusy) return false;
state = AsyncData(
state.requireValue.copyWith(projectBusy: true, error: null),
);
try {
await action();
return true;
} on ProjectOpenSuperseded {
return false;
} catch (error, stackTrace) {
AppDiagnostics.failure('project', 'operation', error, stackTrace);
if (ref.mounted) {
final failure = projectFailureFromError(error);
state = AsyncData(state.requireValue.copyWith(error: failure));
}
return false;
} finally {
if (ref.mounted) {
state = AsyncData(state.requireValue.copyWith(projectBusy: false));
}
}
}
Future<bool> open(
String path, {
String? name,
String? expectedId,
String? timelineId,
String? initialTimelineName,
bool Function()? isCurrent,
}) => _perform(() async {
final previous = state.requireValue;
var published = false;
void checkCurrent() {
if (!ref.mounted || isCurrent?.call() == false) {
throw ProjectOpenSuperseded();
}
}
try {
checkCurrent();
final timelines = await _workspace.open(
path,
name: name,
expectedId: expectedId,
creationNames: _creationNames(initialTimelineName),
isCurrent: isCurrent,
);
checkCurrent();
final file = _workspace.project!;
final assets = await _workspace.listAssets(file.info.id);
checkCurrent();
final active = RecentProject(
id: file.info.id,
name: file.info.name,
path: file.directory.path,
availability: ProjectAvailability.available,
);
final previousRecent = state.requireValue.recent;
final existingIndex = previousRecent.indexWhere(
(item) => item.id == active.id || item.path == active.path,
);
final recent = [
if (existingIndex == -1) active,
for (final (index, item) in previousRecent.indexed)
if (index == existingIndex)
active
else if (item.id != active.id && item.path != active.path)
item,
].take(20).toList();
TimelineDocument? selectedDocument;
if (timelines.isNotEmpty) {
var selectedId = timelineId;
if (selectedId == null) {
try {
selectedId = await ref
.read(recentProjectsProvider)
.lastTimeline(active.id);
} catch (_) {
// App settings storage must not block opening the project.
}
}
final selected =
timelines
.where((timeline) => timeline.id == selectedId)
.firstOrNull ??
(timelineId == null ? timelines.first : null);
if (timelineId != null && selected == null) {
throw AppException(AppErrorCode.timelineMissing);
}
if (selected != null) {
selectedDocument = await _workspace.loadTimeline(
active.id,
selected.id,
);
}
}
checkCurrent();
if (selectedDocument != null) {
await _prepareTimeline(active.id, selectedDocument);
}
checkCurrent();
await ref
.read(previewControllerRegistryProvider)
.retainProject(active.id, keep: _workspace.cachedProjectIds);
checkCurrent();
state = AsyncData(
state.requireValue.copyWith(
activeProject: active,
recent: recent,
timelines: timelines,
assets: assets,
timeline: selectedDocument,
),
);
published = true;
if (selectedDocument != null) {
await _rememberTimeline(active.id, selectedDocument.id);
}
try {
await ref.read(recentProjectsProvider).save(recent);
} catch (_) {
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
error: const AppFailure(AppErrorCode.recentProjectSaveFailed),
),
);
}
}
} catch (_) {
checkCurrent();
rethrow;
} finally {
final old = previous.activeProject;
if (!published &&
ref.mounted &&
old != null &&
_workspace.project?.info.id != old.id) {
await _workspace.open(old.path, expectedId: old.id);
if (previous.timeline != null) {
await _prepareTimeline(old.id, previous.timeline!);
}
await ref
.read(previewControllerRegistryProvider)
.retainProject(old.id, keep: _workspace.cachedProjectIds);
}
}
});
Future<bool> createProject(
String name, {
required String initialTimelineName,
}) async {
final value = name.trim();
if (value.isEmpty ||
RegExp(r'[/\\\x00-\x1F]').hasMatch(value) ||
const {'.', '..'}.contains(value)) {
await future;
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
error: const AppFailure(AppErrorCode.projectNameInvalid),
),
);
}
return false;
}
String? root;
try {
root = await ref.read(projectLocationSettingsRepositoryProvider).load();
} on ProjectLocationUnavailableException {
await future;
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
error: const AppFailure(
AppErrorCode.projectLocationDefaultUnavailable,
),
),
);
}
return false;
}
if (root == null || root.trim().isEmpty) {
await future;
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
error: const AppFailure(AppErrorCode.chooseProjectLocation),
),
);
}
return false;
}
try {
await const ProjectLocationDirectory().prepare(root);
} on StateError catch (error) {
await future;
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(error: projectFailureFromError(error)),
);
}
return false;
}
return open(
p.join(root, '$value.cutdex'),
name: value,
initialTimelineName: initialTimelineName,
);
}
Future<List<TimelineSummary>> listProjectTimelines(
RecentProject project,
) async {
await future;
return _workspace.listProjectTimelines(
project.path,
expectedId: project.id,
);
}
Future<bool> removeRecentProject(String projectId) => _perform(() async {
final recent = state.requireValue.recent
.where((project) => project.id != projectId)
.toList();
await ref.read(recentProjectsProvider).save(recent);
if (!ref.mounted) return;
state = AsyncData(state.requireValue.copyWith(recent: recent));
});
Future<bool> restoreRecentProject(RecentProject project, int index) =>
_perform(() async {
final recent = [...state.requireValue.recent];
if (recent.any((item) => item.id == project.id)) return;
recent.insert(index.clamp(0, recent.length), project);
await ref.read(recentProjectsProvider).save(recent);
if (!ref.mounted) return;
state = AsyncData(state.requireValue.copyWith(recent: recent));
});
Future<bool> renameProject(RecentProject project, String name) =>
_perform(() async {
final value = name.trim();
await _workspace.renameProject(project, value);
if (!ref.mounted) return;
final current = state.requireValue;
final renamed = project.copyWith(name: value);
final recent = [
for (final item in current.recent)
if (item.id == project.id) renamed else item,
];
state = AsyncData(
current.copyWith(
recent: recent,
activeProject: current.activeProject?.id == project.id
? current.activeProject!.copyWith(name: value)
: current.activeProject,
),
);
await ref.read(recentProjectsProvider).save(recent);
});
Future<bool> renameTimeline(
RecentProject project,
String timelineId,
String name,
) => _perform(() async {
final value = name.trim();
await _workspace.renameTimeline(project, timelineId, value);
if (!ref.mounted || state.requireValue.activeProject?.id != project.id) {
return;
}
final current = state.requireValue;
state = AsyncData(
current.copyWith(
timelines: [
for (final timeline in current.timelines)
if (timeline.id == timelineId)
TimelineSummary(
id: timeline.id,
name: value,
revision: timeline.revision,
pinned: timeline.pinned,
)
else
timeline,
],
timeline: current.timeline?.id == timelineId
? TimelineDocument(
id: current.timeline!.id,
name: value,
sequences: current.timeline!.sequences,
defaultSequenceId: current.timeline!.defaultSequenceId,
payloads: current.timeline!.payloads,
settings: current.timeline!.settings,
revision: current.timeline!.revision,
)
: current.timeline,
),
);
});
Future<bool> setTimelinePinned(String timelineId, bool pinned) =>
_perform(() async {
final current = state.requireValue;
final project = current.activeProject;
if (project == null) throw AppException(AppErrorCode.openProjectFirst);
final timelines = await _workspace.setTimelinePinned(
project,
timelineId,
pinned,
);
if (ref.mounted && state.requireValue.activeProject?.id == project.id) {
state = AsyncData(state.requireValue.copyWith(timelines: timelines));
}
});
Future<bool> deleteTimeline(String timelineId) => _perform(() async {
final current = state.requireValue;
final project = current.activeProject;
if (project == null) throw AppException(AppErrorCode.openProjectFirst);
if (current.timelines.length <= 1) {
throw AppException(AppErrorCode.timelineRequired);
}
final deletedIndex = current.timelines.indexWhere(
(timeline) => timeline.id == timelineId,
);
if (deletedIndex < 0) throw AppException(AppErrorCode.timelineMissing);
final replacementId =
current.timelines[deletedIndex > 0 ? deletedIndex - 1 : 1].id;
final timelines = await _workspace.deleteTimeline(project, timelineId);
if (!ref.mounted || state.requireValue.activeProject?.id != project.id) {
return;
}
TimelineDocument? selected = state.requireValue.timeline;
if (selected?.id == timelineId) {
selected = await _workspace.loadTimeline(project.id, replacementId);
await _prepareTimeline(project.id, selected);
}
if (!ref.mounted || state.requireValue.activeProject?.id != project.id) {
return;
}
state = AsyncData(
state.requireValue.copyWith(timelines: timelines, timeline: selected),
);
if (selected != null) await _rememberTimeline(project.id, selected.id);
});
Future<bool> createTimeline({String? name}) async {
await future;
final current = state.requireValue;
if (current.projectBusy ||
current.creatingTimeline ||
current.openingTimelineId != null ||
current.activeProject == null) {
return false;
}
if (current.timelines.length >= maxTimelineCount) return false;
state = AsyncData(current.copyWith(creatingTimeline: true, error: null));
try {
final timelineName = name?.trim().isNotEmpty == true
? name!.trim()
: _nextUntitledTimelineName(current.timelines);
final created = await _workspace.createPreparedTimeline(
timelineName,
creationNames: _creationNames(timelineName),
);
await _prepareTimeline(current.activeProject!.id, created.document);
if (!ref.mounted) return true;
state = AsyncData(
state.requireValue.copyWith(
timelines: created.timelines,
timeline: created.document,
creatingTimeline: false,
),
);
await _rememberTimeline(current.activeProject!.id, created.document.id);
return true;
} catch (error) {
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
creatingTimeline: false,
error: _failureFor(error),
),
);
}
return false;
}
}
String _nextUntitledTimelineName(List<TimelineSummary> timelines) {
final names = timelines.map((timeline) => timeline.name).toSet();
final base = _localizations.untitledTimeline;
if (!names.contains(base)) return base;
for (var suffix = 2; ; suffix++) {
final candidate = '$base ($suffix)';
if (!names.contains(candidate)) return candidate;
}
}
Future<MediaImportResult?> importExternalMedia(
String projectId,
List<ExternalMediaFile> files, {
bool Function()? isCancelled,
}) async {
MediaImportResult? result;
await _perform(() async {
result = await _workspace.importExternalMedia(
projectId,
files,
isCancelled: isCancelled,
);
});
return result;
}
Future<bool> insertTimelineAsset({
required String projectId,
required EditorTimelineSession session,
required SequenceId sequenceId,
required String assetId,
required int position,
}) => _perform(() async {
final current = state.requireValue;
if (current.activeProject?.id != projectId ||
current.timeline?.id != session.document.id) {
throw AppException(AppErrorCode.projectSwitched);
}
await session.commands.insertMedia(
sequence: sequenceId,
assetId: assetId,
position: position,
);
});
Future<bool> editMediaAsset(
String projectId,
String assetId, {
String? name,
}) => _perform(() async {
final assets = await _workspace.editAsset(projectId, assetId, name: name);
if (ref.mounted && state.requireValue.activeProject?.id == projectId) {
state = AsyncData(state.requireValue.copyWith(assets: assets));
}
});
Future<bool> revealMediaAsset(String projectId, AssetDocument asset) =>
_perform(() async {
await _workspace.withAssetMedia(projectId, asset, (media) async {
if (media.uri.scheme != 'file') {
throw AppException(AppErrorCode.notLocalMedia);
}
final path = media.uri.toFilePath();
final result = Platform.isMacOS
? await Process.run('/usr/bin/open', ['-R', path])
: Platform.isWindows
? await Process.run('explorer.exe', ['/select,', path])
: await Process.run('xdg-open', [File(path).parent.path]);
if (result.exitCode != 0) {
throw AppException(AppErrorCode.revealMediaFailed);
}
});
});
Future<EditorTimelineSession> openTimelineSession(
String projectId,
String timelineId,
) async {
final current = await future;
if (current.activeProject?.id != projectId ||
current.timeline?.id != timelineId) {
throw AppException(
current.activeProject?.id != projectId
? AppErrorCode.openMatchingProject
: AppErrorCode.openTimelineFailed,
);
}
return _workspace.openTimelineSession(projectId, current.timeline!);
}
Future<EditorTimelineSession> _prepareTimeline(
String projectId,
TimelineDocument document,
) async {
final session = await _workspace.openTimelineSession(projectId, document);
await TimelineViewStateBinding.prepare(
projectId: projectId,
timelineId: document.id,
session: session,
repository: ref.read(timelineViewSettingsRepositoryProvider),
);
try {
await ref.read(previewControllerRegistryProvider).prepare((
projectId,
document.id,
), session);
} catch (error, stackTrace) {
AppDiagnostics.failure('preview', 'prepare', error, stackTrace);
}
return session;
}
Future<WorkspaceTimelineLease> leaseTimeline(
String projectId,
String timelineId,
) async {
await future;
return _workspace.leaseTimeline(projectId, timelineId);
}
Future<bool> openTimeline(String projectId, String timelineId) async {
await future;
final current = state.requireValue;
if (current.projectBusy ||
current.creatingTimeline ||
current.openingTimelineId != null ||
current.activeProject?.id != projectId) {
return false;
}
if (current.timeline?.id == timelineId) return true;
final cachedTimeline = _workspace.cachedTimelineDocument(
projectId,
timelineId,
);
final cachedSession = _workspace.cachedTimelineSession(
projectId,
timelineId,
);
if (cachedTimeline != null && cachedSession != null) {
state = AsyncData(
current.copyWith(timeline: cachedTimeline, error: null),
);
await _rememberTimeline(projectId, timelineId);
return true;
}
state = AsyncData(
current.copyWith(openingTimelineId: timelineId, error: null),
);
try {
final timeline = await _workspace.loadTimeline(projectId, timelineId);
await _prepareTimeline(projectId, timeline);
if (!ref.mounted) return true;
state = AsyncData(
state.requireValue.copyWith(
timeline: timeline,
openingTimelineId: null,
),
);
await _rememberTimeline(projectId, timelineId);
return true;
} catch (error) {
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
openingTimelineId: null,
error: _failureFor(error),
),
);
}
return false;
}
}
Future<void> _rememberTimeline(String projectId, String timelineId) async {
try {
await ref
.read(recentProjectsProvider)
.rememberTimeline(projectId, timelineId);
} catch (_) {
if (ref.mounted) {
state = AsyncData(
state.requireValue.copyWith(
error: const AppFailure(AppErrorCode.lastProjectSaveFailed),
),
);
}
}
}
AppFailure _failureFor(Object error) => projectFailureFromError(error);
}
+54
View File
@@ -0,0 +1,54 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'projects.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(Projects)
final projectsProvider = ProjectsProvider._();
final class ProjectsProvider
extends $AsyncNotifierProvider<Projects, ProjectState> {
ProjectsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'projectsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$projectsHash();
@$internal
@override
Projects create() => Projects();
}
String _$projectsHash() => r'7112bbc5f1f4389d91f20aa9ec2ac5d28136eefe';
abstract class _$Projects extends $AsyncNotifier<ProjectState> {
FutureOr<ProjectState> build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<AsyncValue<ProjectState>, ProjectState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<ProjectState>, ProjectState>,
AsyncValue<ProjectState>,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
+61
View File
@@ -0,0 +1,61 @@
import 'dart:async';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../persistence/app_settings_repositories.dart';
import 'projects.dart';
import 'timeline_session.dart';
import 'timeline_view_state.dart';
part 'timeline_provider.g.dart';
@riverpod
FutureOr<EditorTimelineSession> editorTimeline(
Ref ref,
String projectId,
String timelineId,
) {
final ids = (projectId, timelineId);
final projects = ref.read(projectsProvider.notifier);
final cached = projects.cachedTimelineSession(projectId, timelineId);
if (cached != null) return _bindTimeline(ref, ids, cached);
return projects.openTimelineSession(projectId, timelineId).then((session) {
if (!ref.mounted) return session;
return _bindTimeline(ref, ids, session);
});
}
FutureOr<EditorTimelineSession> _bindTimeline(
Ref ref,
(String, String) ids,
EditorTimelineSession session,
) {
final binding = TimelineViewStateBinding.attach(
projectId: ids.$1,
timelineId: ids.$2,
session: session,
repository: ref.read(timelineViewSettingsRepositoryProvider),
);
if (binding is TimelineViewStateBinding) {
return _retainTimeline(ref, session, binding);
}
return binding.then((resolved) => _retainTimeline(ref, session, resolved));
}
EditorTimelineSession _retainTimeline(
Ref ref,
EditorTimelineSession session,
TimelineViewStateBinding binding,
) {
if (ref.mounted) {
final releaseViews = session.retainViews();
ref.onDispose(() {
unawaited(binding.close());
releaseViews();
});
} else {
unawaited(binding.close());
}
return session;
}
+91
View File
@@ -0,0 +1,91 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'timeline_provider.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(editorTimeline)
final editorTimelineProvider = EditorTimelineFamily._();
final class EditorTimelineProvider
extends
$FunctionalProvider<
AsyncValue<EditorTimelineSession>,
EditorTimelineSession,
FutureOr<EditorTimelineSession>
>
with
$FutureModifier<EditorTimelineSession>,
$FutureProvider<EditorTimelineSession> {
EditorTimelineProvider._({
required EditorTimelineFamily super.from,
required (String, String) super.argument,
}) : super(
retry: null,
name: r'editorTimelineProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$editorTimelineHash();
@override
String toString() {
return r'editorTimelineProvider'
''
'$argument';
}
@$internal
@override
$FutureProviderElement<EditorTimelineSession> $createElement(
$ProviderPointer pointer,
) => $FutureProviderElement(pointer);
@override
FutureOr<EditorTimelineSession> create(Ref ref) {
final argument = this.argument as (String, String);
return editorTimeline(ref, argument.$1, argument.$2);
}
@override
bool operator ==(Object other) {
return other is EditorTimelineProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$editorTimelineHash() => r'7c6aceb0f85c2e6508c78d62568a45fdd46bc075';
final class EditorTimelineFamily extends $Family
with
$FunctionalFamilyOverride<
FutureOr<EditorTimelineSession>,
(String, String)
> {
EditorTimelineFamily._()
: super(
retry: null,
name: r'editorTimelineProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
EditorTimelineProvider call(String projectId, String timelineId) =>
EditorTimelineProvider._(argument: (projectId, timelineId), from: this);
@override
String toString() => r'editorTimelineProvider';
}
+323
View File
@@ -0,0 +1,323 @@
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:uuid/uuid.dart';
/// Flutter presentation resources for an SDK-owned editor session.
class EditorTimelineSession extends EditorSession implements Listenable {
EditorTimelineSession({
required super.document,
required super.persistence,
super.media,
super.exportService,
super.captionFiles,
super.diagnostics,
super.transcriptionBackend,
super.transcriptionModel,
super.translationBackend,
super.translationModel,
super.vocalSeparationBackend,
super.vocalSeparationModel,
super.layoutConfiguration,
super.assetUris,
}) {
_activeSequenceId =
document.defaultSequenceId ?? document.sequences.firstOrNull?.id;
}
bool _disposed = false;
AppFailure? get error => saveError == null
? null
: AppFailure(
AppErrorCode.saveTimelineFailed,
diagnostic: saveError.toString(),
);
final _views = <SequenceId, TimelineViewController>{};
final audioGainPreview =
ValueNotifier<
({
SequenceId sequence,
ElementId clip,
Object version,
ClipAudioGain gain,
})?
>(null);
final _customSpeedClips = <SequenceId, Set<ElementId>>{};
bool isCustomSpeedEnabled(SequenceId sequence, ElementId clip) =>
_customSpeedClips[sequence]?.contains(clip) ?? false;
void setCustomSpeedEnabled(
SequenceId sequence,
ElementId clip,
bool enabled,
) {
final clips = _customSpeedClips.putIfAbsent(sequence, () => {});
final changed = enabled ? clips.add(clip) : clips.remove(clip);
if (!changed) return;
_syncSpeedGeometry(sequence);
notifyListeners();
}
void previewAudioGain(
SequenceId sequence,
ElementId clip,
ClipAudioGain gain,
) {
audioGainPreview.value = (
sequence: sequence,
clip: clip,
version: view(sequence).version.kernelVersion,
gain: gain,
);
}
void clearAudioGainPreview(ElementId clip) {
if (_disposed) return;
if (audioGainPreview.value?.clip == clip) audioGainPreview.value = null;
}
double waveformGain(ElementRecord clip) {
final timeline = audioGainPreview.value;
if (timeline != null &&
timeline.clip == clip.id &&
timeline.sequence == activeSequenceId &&
identical(
timeline.version,
view(timeline.sequence).version.kernelVersion,
)) {
return timeline.gain.amplitudeScale;
}
return ClipAudioGain.fromRecord(clip).amplitudeScale;
}
SequenceId? _activeSequenceId;
SequenceId? get activeSequenceId => _activeSequenceId;
void selectSequence(SequenceId id) {
if (_activeSequenceId == id) return;
if (!document.sequences.any((sequence) => sequence.id == id)) {
throw ArgumentError('Unknown sequence');
}
_activeSequenceId = id;
notifyListeners();
}
TimelineViewController view(
SequenceId sequenceId,
) => _views.putIfAbsent(sequenceId, () {
final owners = _resolveSpeedOwners(sequenceId);
_speedHeaderOwners[sequenceId] = owners;
_speedOnPrimary[sequenceId] = _hasPrimarySpeedOwner(sequenceId, owners);
final controller = TimelineViewController.editable(
engine: layout(sequenceId),
geometry: _viewportGeometry(sequenceId),
camera: TimelineCamera(
baseTick: 0,
pixelsPerTick: 60 / TimelineClock.ticksPerSecond,
),
createConnectionId: () => ConnectionId(const Uuid().v4()),
createElementId: () => ElementId(const Uuid().v4()),
commitEdit: <T>(T Function() action) => commit(sequenceId, action),
editOperation: <T>(
String operation,
Map<String, Object?> context,
T Function() action,
) => runEdit(operation, sequenceId, action, context: context),
onEditFailure: reportEditFailure,
onElementsSplit: (fragments) {
final clips = _customSpeedClips[sequenceId];
if (clips == null) return;
final query = persistence.timeline(sequenceId).current.query();
for (final fragment in fragments.entries) {
if (clips.contains(query.element(fragment.key).id)) {
clips.add(fragment.value);
}
}
},
canUndo: () => canUndo(sequenceId),
canRedo: () => canRedo(sequenceId),
undo: () => undo(sequenceId),
redo: () => redo(sequenceId),
resolveComponent: (identity, _) =>
resolveCaptionComponent(sequenceId, identity),
commitComponent: (identity, start, duration) =>
setCaptionComponentInterval(sequenceId, identity, start, duration),
);
_speedGeometryOwners[controller.version] = (
owners: owners,
primary: _speedOnPrimary[sequenceId] ?? false,
);
controller.contentChanges.addListener(() => _syncSpeedGeometry(sequenceId));
return controller;
});
final _speedHeaderOwners = <SequenceId, Set<ElementHandle>>{};
final _speedOnPrimary = <SequenceId, bool>{};
final _speedGeometryOwners =
Expando<({Set<ElementHandle> owners, bool primary})>();
bool _syncingSpeedGeometry = false;
bool _movingHistory = false;
@override
int primaryHeightFor(SequenceId sequence) {
final height = layoutConfiguration.primaryHeight;
if (_speedOnPrimary[sequence] != true) return height;
final topPadding = (height - layoutConfiguration.primaryClipHeight) ~/ 2;
return height +
(EditorLayoutConfiguration.speedHeaderHeight - topPadding).clamp(
0,
EditorLayoutConfiguration.speedHeaderHeight,
);
}
@override
int clipHeightFor(SequenceId sequence, ElementRecord clip) =>
super.clipHeightFor(sequence, clip) +
(isCustomSpeedEnabled(sequence, clip.id)
? EditorLayoutConfiguration.speedHeaderHeight
: 0);
TimelineViewportGeometry _viewportGeometry(SequenceId sequence) {
final height = primaryHeightFor(sequence);
final laneTop =
layoutConfiguration.primaryTop +
height -
layoutConfiguration.primaryHeight;
return TimelineViewportGeometry(
primaryTop: layoutConfiguration.primaryTop,
primaryHeight: height,
primaryLaneHeight: layoutConfiguration.primaryHeight,
primaryClipHeight: layoutConfiguration.primaryClipHeight,
clipHeaderOwners: _speedHeaderOwners[sequence] ?? const {},
clipHeaderHeight: EditorLayoutConfiguration.speedHeaderHeight,
transitionTop: laneTop,
transitionHeight: layoutConfiguration.primaryHeight,
);
}
Set<ElementHandle> _resolveSpeedOwners(SequenceId sequence) {
final query = persistence.timeline(sequence).current.query();
return Set.unmodifiable({
for (final clip in _customSpeedClips[sequence] ?? const <ElementId>{})
if (query.elementById(clip) case final handle?)
if (query.ownerOf(handle) != null &&
clipSpeedSegments(query.element(handle)) != null)
handle,
});
}
bool _hasPrimarySpeedOwner(SequenceId sequence, Set<ElementHandle> owners) {
final query = persistence.timeline(sequence).current.query();
return owners.any((owner) => query.connectionForTarget(owner) == null);
}
void _syncSpeedGeometry(SequenceId sequence, {bool force = false}) {
if (_disposed || _syncingSpeedGeometry || _movingHistory) return;
final controller = _views[sequence];
if (controller == null) return;
final owners = _resolveSpeedOwners(sequence);
final primary = _hasPrimarySpeedOwner(sequence, owners);
final dimensions = (owners: owners, primary: primary);
final retained = _speedGeometryOwners[controller.version];
if (setEquals(_speedHeaderOwners[sequence] ?? const {}, owners) &&
(_speedOnPrimary[sequence] ?? false) == primary &&
(!force ||
(retained != null &&
retained.primary == primary &&
setEquals(retained.owners, owners)))) {
_speedGeometryOwners[controller.version] = dimensions;
return;
}
_syncingSpeedGeometry = true;
try {
_speedHeaderOwners[sequence] = owners;
_speedOnPrimary[sequence] = primary;
final result = refreshLayoutGeometry(sequence);
_speedGeometryOwners[result.version] = dimensions;
controller.applyLayout(result, geometry: _viewportGeometry(sequence));
} finally {
_syncingSpeedGeometry = false;
}
}
@override
void undo(SequenceId sequence) {
_movingHistory = true;
try {
super.undo(sequence);
} finally {
_movingHistory = false;
}
_syncSpeedGeometry(sequence, force: true);
}
@override
void redo(SequenceId sequence) {
_movingHistory = true;
try {
super.redo(sequence);
} finally {
_movingHistory = false;
}
_syncSpeedGeometry(sequence, force: true);
}
@override
void didChangeProjectProperties() {
for (final view in _views.values) {
view.cancelDrag();
view.notifyListeners();
}
}
@override
void didPublishLayout(SequenceId sequence, LayoutApplyResult result) {
_views[sequence]?.applyLayout(result);
}
@override
void didInsertClip(SequenceId sequence, ElementId clip) {
_views[sequence]?.setSelection([
persistence.timeline(sequence).current.query().elementById(clip)!,
]);
}
int _viewLeases = 0;
bool _closed = false;
/// Keep presentation notifiers alive until their provider and widgets detach.
/// Closing still flushes edits and rejects further commands immediately.
VoidCallback retainViews() {
if (_disposed || _closed) {
throw AppException(AppErrorCode.timelineSessionClosed);
}
_viewLeases++;
var released = false;
return () {
if (released) return;
released = true;
_viewLeases--;
if (_closed && _viewLeases == 0) dispose();
};
}
@override
void dispose() {
if (_disposed) return;
_closed = true;
// The old provider can remain mounted for a frame after a timeline switch.
// Its widgets must be able to detach from these notifiers before disposal.
if (_viewLeases > 0) return;
_disposed = true;
super.dispose();
audioGainPreview.dispose();
for (final controller in _views.values) {
controller.dispose();
}
}
}
+183
View File
@@ -0,0 +1,183 @@
import 'dart:async';
import 'package:cutdex_sdk/timeline/model.dart';
import '../persistence/app_settings_repositories.dart';
import 'timeline_session.dart';
/// Keeps local timeline navigation out of the authored project document.
final class TimelineViewStateBinding {
static final _initialized = Expando<bool>();
TimelineViewStateBinding._(
this.projectId,
this.timelineId,
this.session,
this.repository,
);
static Future<void> prepare({
required String projectId,
required String timelineId,
required EditorTimelineSession session,
required TimelineViewSettingsRepository repository,
}) async {
if (_initialized[session] == true) return;
var saved = const TimelineViewState();
try {
saved = await repository.load(projectId, timelineId);
} catch (_) {
// Corrupt or unavailable local UI state must not block the timeline.
}
_restore(session, saved);
_initialized[session] = true;
}
static FutureOr<TimelineViewStateBinding> attach({
required String projectId,
required String timelineId,
required EditorTimelineSession session,
required TimelineViewSettingsRepository repository,
}) {
final shouldRestore = _initialized[session] != true;
if (!shouldRestore) {
return _bind(
projectId: projectId,
timelineId: timelineId,
session: session,
repository: repository,
saved: const TimelineViewState(),
shouldRestore: false,
);
}
return () async {
var saved = const TimelineViewState();
try {
saved = await repository.load(projectId, timelineId);
} catch (_) {
// Corrupt or unavailable local UI state must not block the timeline.
}
return _bind(
projectId: projectId,
timelineId: timelineId,
session: session,
repository: repository,
saved: saved,
shouldRestore: true,
);
}();
}
static TimelineViewStateBinding _bind({
required String projectId,
required String timelineId,
required EditorTimelineSession session,
required TimelineViewSettingsRepository repository,
required TimelineViewState saved,
required bool shouldRestore,
}) {
if (shouldRestore) _restore(session, saved);
final sequenceIds = session.document.sequences
.map((item) => item.id)
.toSet();
final binding = TimelineViewStateBinding._(
projectId,
timelineId,
session,
repository,
);
for (final sequenceId in sequenceIds) {
final controller = session.view(sequenceId);
void listener() => binding._schedule(sequenceId);
controller.addListener(listener);
binding._listeners[sequenceId] = listener;
}
_initialized[session] = true;
binding._activeSequenceId = session.activeSequenceId;
session.addListener(binding._sessionChanged);
return binding;
}
static void _restore(EditorTimelineSession session, TimelineViewState saved) {
final sequenceIds = session.document.sequences
.map((item) => item.id)
.toSet();
final active = saved.activeSequenceId;
if (active != null && sequenceIds.contains(active)) {
session.selectSequence(active);
}
for (final sequenceId in sequenceIds) {
final state = saved.sequences[sequenceId];
if (state != null) {
session
.view(sequenceId)
.restoreViewState(
playheadTick: state.playheadTick,
camera: state.camera,
);
}
}
}
final String projectId;
final String timelineId;
final EditorTimelineSession session;
final TimelineViewSettingsRepository repository;
final Map<SequenceId, void Function()> _listeners = {};
SequenceId? _activeSequenceId;
Timer? _timer;
Future<void> _tail = Future.value();
bool _closed = false;
void _sessionChanged() {
final next = session.activeSequenceId;
if (next == _activeSequenceId) return;
final previous = _activeSequenceId;
_activeSequenceId = next;
_timer?.cancel();
if (previous != null) _enqueue(previous);
if (next != null) _enqueue(next);
}
void _schedule(SequenceId sequenceId) {
if (_closed || sequenceId != session.activeSequenceId) return;
_timer?.cancel();
_timer = Timer(const Duration(milliseconds: 500), () {
_enqueue(sequenceId);
});
}
void _enqueue(SequenceId sequenceId) {
_tail = _tail.then((_) => _save(sequenceId));
}
Future<void> _save(SequenceId sequenceId) async {
final controller = session.view(sequenceId);
try {
await repository.save(
projectId,
timelineId,
sequenceId,
TimelineSequenceViewState(
playheadTick: controller.playheadTick,
camera: controller.camera,
),
);
} catch (_) {
// View state must never block editing or project persistence.
}
}
Future<void> close() async {
if (_closed) return;
_closed = true;
_timer?.cancel();
session.removeListener(_sessionChanged);
for (final entry in _listeners.entries) {
session.view(entry.key).removeListener(entry.value);
}
final active = session.activeSequenceId;
if (active != null) _enqueue(active);
await _tail;
}
}
+78
View File
@@ -0,0 +1,78 @@
import '../diagnostics/app_diagnostics.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../persistence/settings/view_settings_repositories.dart';
import '../settings/settings_write_queue.dart';
import 'workspace_mode.dart';
part 'view_settings.g.dart';
/// Persistent navigation preferences, shared by the application surface.
@Riverpod(keepAlive: true)
class WorkspaceViewSettings extends _$WorkspaceViewSettings {
final _writes = SettingsWriteQueue();
@override
Future<WorkspaceViewSettingsData> build() async {
try {
return await ref.watch(workspaceViewSettingsRepositoryProvider).load();
} catch (error, stackTrace) {
AppDiagnostics.failure(
'settings',
'loadWorkspaceView',
error,
stackTrace,
);
return const WorkspaceViewSettingsData();
}
}
void setMode(WorkspaceMode mode) =>
state = AsyncData(state.requireValue.copyWith(mode: mode));
void setSidebarCollapsed(bool collapsed) => state = AsyncData(
state.requireValue.copyWith(sidebarCollapsed: collapsed),
);
void setSidebarWidth(double? width) =>
state = AsyncData(state.requireValue.copyWith(sidebarWidth: width));
/// Writes snapshots in order so a slower drag save cannot replace a newer one.
Future<void> save({required String? activeProjectId}) {
final value = state.requireValue.copyWith(activeProjectId: activeProjectId);
state = AsyncData(value);
final repository = ref.read(workspaceViewSettingsRepositoryProvider);
return _writes.run(() => repository.save(value));
}
}
/// Project preferences survive timeline switches and widget reconstruction.
@Riverpod(keepAlive: true)
class ProjectViewSettings extends _$ProjectViewSettings {
final _writes = SettingsWriteQueue();
@override
Future<ProjectViewSettingsData> build(String projectId) async {
try {
return await ref
.watch(projectViewSettingsRepositoryProvider)
.load(projectId);
} catch (error, stackTrace) {
AppDiagnostics.failure('settings', 'loadProjectView', error, stackTrace);
return const ProjectViewSettingsData();
}
}
void setPropertiesOpen(bool open) =>
state = AsyncData(state.requireValue.copyWith(propertiesOpen: open));
void setTimelineHeight(double? height) =>
state = AsyncData(state.requireValue.copyWith(timelineHeight: height));
Future<void> save() {
final value = state.requireValue;
final repository = ref.read(projectViewSettingsRepositoryProvider);
return _writes.run(() => repository.save(projectId, value));
}
}
+183
View File
@@ -0,0 +1,183 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'view_settings.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Persistent navigation preferences, shared by the application surface.
@ProviderFor(WorkspaceViewSettings)
final workspaceViewSettingsProvider = WorkspaceViewSettingsProvider._();
/// Persistent navigation preferences, shared by the application surface.
final class WorkspaceViewSettingsProvider
extends
$AsyncNotifierProvider<
WorkspaceViewSettings,
WorkspaceViewSettingsData
> {
/// Persistent navigation preferences, shared by the application surface.
WorkspaceViewSettingsProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'workspaceViewSettingsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$workspaceViewSettingsHash();
@$internal
@override
WorkspaceViewSettings create() => WorkspaceViewSettings();
}
String _$workspaceViewSettingsHash() =>
r'35836b74a1bbd2718e9a381d5623255ff507c63a';
/// Persistent navigation preferences, shared by the application surface.
abstract class _$WorkspaceViewSettings
extends $AsyncNotifier<WorkspaceViewSettingsData> {
FutureOr<WorkspaceViewSettingsData> build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref
as $Ref<
AsyncValue<WorkspaceViewSettingsData>,
WorkspaceViewSettingsData
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<WorkspaceViewSettingsData>,
WorkspaceViewSettingsData
>,
AsyncValue<WorkspaceViewSettingsData>,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
/// Project preferences survive timeline switches and widget reconstruction.
@ProviderFor(ProjectViewSettings)
final projectViewSettingsProvider = ProjectViewSettingsFamily._();
/// Project preferences survive timeline switches and widget reconstruction.
final class ProjectViewSettingsProvider
extends
$AsyncNotifierProvider<ProjectViewSettings, ProjectViewSettingsData> {
/// Project preferences survive timeline switches and widget reconstruction.
ProjectViewSettingsProvider._({
required ProjectViewSettingsFamily super.from,
required String super.argument,
}) : super(
retry: null,
name: r'projectViewSettingsProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$projectViewSettingsHash();
@override
String toString() {
return r'projectViewSettingsProvider'
''
'($argument)';
}
@$internal
@override
ProjectViewSettings create() => ProjectViewSettings();
@override
bool operator ==(Object other) {
return other is ProjectViewSettingsProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$projectViewSettingsHash() =>
r'c036088de9f39789b8604c48000a63a52517c966';
/// Project preferences survive timeline switches and widget reconstruction.
final class ProjectViewSettingsFamily extends $Family
with
$ClassFamilyOverride<
ProjectViewSettings,
AsyncValue<ProjectViewSettingsData>,
ProjectViewSettingsData,
FutureOr<ProjectViewSettingsData>,
String
> {
ProjectViewSettingsFamily._()
: super(
retry: null,
name: r'projectViewSettingsProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: false,
);
/// Project preferences survive timeline switches and widget reconstruction.
ProjectViewSettingsProvider call(String projectId) =>
ProjectViewSettingsProvider._(argument: projectId, from: this);
@override
String toString() => r'projectViewSettingsProvider';
}
/// Project preferences survive timeline switches and widget reconstruction.
abstract class _$ProjectViewSettings
extends $AsyncNotifier<ProjectViewSettingsData> {
late final _$args = ref.$arg as String;
String get projectId => _$args;
FutureOr<ProjectViewSettingsData> build(String projectId);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref
as $Ref<
AsyncValue<ProjectViewSettingsData>,
ProjectViewSettingsData
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<ProjectViewSettingsData>,
ProjectViewSettingsData
>,
AsyncValue<ProjectViewSettingsData>,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args));
}
}
+2
View File
@@ -0,0 +1,2 @@
/// The user's workflow; independent of available window space.
enum WorkspaceMode { agent, cut }
+143
View File
@@ -0,0 +1,143 @@
import 'dart:async';
import '../diagnostics/app_diagnostics.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../features/projects/conversation_sidebar.dart';
import 'project_state.dart';
import 'projects.dart';
import 'view_settings.dart';
part 'workspace_navigation.g.dart';
part 'workspace_navigation.freezed.dart';
@freezed
abstract class WorkspaceNavigationState with _$WorkspaceNavigationState {
const factory WorkspaceNavigationState({
@Default(false) bool ready,
@Default(false) bool switchingProject,
String? selectedProjectId,
}) = _WorkspaceNavigationState;
}
@Riverpod(keepAlive: true)
class WorkspaceNavigation extends _$WorkspaceNavigation {
int _revision = 0;
Completer<void> _changed = Completer<void>();
Completer<void> _quiet = Completer<void>();
Timer? _debounce;
RecentProject? _queued;
@override
WorkspaceNavigationState build() {
ref.onDispose(() {
_debounce?.cancel();
if (!_changed.isCompleted) _changed.complete();
});
ref.listen(
projectsProvider.select((value) => value.value?.activeProject?.id),
(before, after) {
if (before != after && state.ready) {
unawaited(
ref
.read(workspaceViewSettingsProvider.notifier)
.save(activeProjectId: after)
.catchError((Object error, StackTrace stack) {
AppDiagnostics.failure(
'settings',
'saveWorkspaceSelection',
error,
stack,
);
}),
);
}
},
);
unawaited(Future<void>.microtask(_restore));
return const WorkspaceNavigationState();
}
Future<void> _restore() async {
try {
final settings = await ref.read(workspaceViewSettingsProvider.future);
if (!ref.mounted) return;
final workspace = await ref.read(projectsProvider.future);
if (!ref.mounted) return;
final project = workspace.recent
.where(
(item) =>
item.id == settings.activeProjectId &&
item.availability.canOpen,
)
.firstOrNull;
if (workspace.activeProject == null && project != null) {
await openProject(project);
}
if (!ref.mounted) return;
await ref.read(conversationSidebarProvider.future);
} catch (error, stack) {
AppDiagnostics.failure('project', 'restoreWorkspace', error, stack);
} finally {
if (ref.mounted) state = state.copyWith(ready: true);
}
}
Future<void> openProject(RecentProject project) async {
final workspace = ref.read(projectsProvider).value;
if (state.selectedProjectId == project.id ||
(!state.switchingProject &&
(workspace?.projectBusy == true ||
workspace?.activeProject?.id == project.id))) {
return;
}
_revision++;
_changed.complete();
_changed = Completer<void>();
_debounce?.cancel();
_quiet = Completer<void>();
_debounce = Timer(const Duration(milliseconds: 100), _quiet.complete);
_queued = project;
state = state.copyWith(selectedProjectId: project.id);
if (state.switchingProject) return;
state = state.copyWith(switchingProject: true);
try {
while (ref.mounted && _queued != null) {
final revision = _revision;
await Future.any([_quiet.future, _changed.future]);
if (!ref.mounted) return;
if (revision != _revision) continue;
final target = _queued!;
_queued = null;
if (ref.read(projectsProvider).value?.activeProject?.id == target.id) {
continue;
}
final opened = await ref
.read(projectsProvider.notifier)
.open(
target.path,
expectedId: target.id,
isCurrent: () => ref.mounted && revision == _revision,
);
if (!ref.mounted) return;
if (opened && _queued == null) {
await ref
.read(workspaceViewSettingsProvider.notifier)
.save(activeProjectId: target.id);
}
}
} finally {
if (ref.mounted) {
state = state.copyWith(
switchingProject: false,
selectedProjectId: null,
);
}
}
}
}
@@ -0,0 +1,412 @@
// 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 'workspace_navigation.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$WorkspaceNavigationState implements DiagnosticableTreeMixin {
bool get ready;
bool get switchingProject;
String? get selectedProjectId;
/// Create a copy of WorkspaceNavigationState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$WorkspaceNavigationStateCopyWith<WorkspaceNavigationState> get copyWith =>
_$WorkspaceNavigationStateCopyWithImpl<WorkspaceNavigationState>(
this as WorkspaceNavigationState,
_$identity,
);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
final _this = this as WorkspaceNavigationState;
properties
..add(DiagnosticsProperty('type', 'WorkspaceNavigationState'))
..add(DiagnosticsProperty('ready', _this.ready))
..add(DiagnosticsProperty('switchingProject', _this.switchingProject))
..add(DiagnosticsProperty('selectedProjectId', _this.selectedProjectId));
}
@override
bool operator ==(Object other) {
final _this = this as WorkspaceNavigationState;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is WorkspaceNavigationState &&
(identical(other.ready, _this.ready) ||
other.ready == _this.ready) &&
(identical(other.switchingProject, _this.switchingProject) ||
other.switchingProject == _this.switchingProject) &&
(identical(other.selectedProjectId, _this.selectedProjectId) ||
other.selectedProjectId == _this.selectedProjectId));
}
@override
int get hashCode {
final _this = this as WorkspaceNavigationState;
return Object.hash(
runtimeType,
_this.ready,
_this.switchingProject,
_this.selectedProjectId,
);
}
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
final _this = this as WorkspaceNavigationState;
return 'WorkspaceNavigationState(ready: ${_this.ready}, switchingProject: ${_this.switchingProject}, selectedProjectId: ${_this.selectedProjectId})';
}
}
/// @nodoc
abstract mixin class $WorkspaceNavigationStateCopyWith<$Res> {
factory $WorkspaceNavigationStateCopyWith(
WorkspaceNavigationState value,
$Res Function(WorkspaceNavigationState) _then,
) = _$WorkspaceNavigationStateCopyWithImpl;
@useResult
$Res call({bool ready, bool switchingProject, String? selectedProjectId});
}
/// @nodoc
class _$WorkspaceNavigationStateCopyWithImpl<$Res>
implements $WorkspaceNavigationStateCopyWith<$Res> {
_$WorkspaceNavigationStateCopyWithImpl(this._self, this._then);
final WorkspaceNavigationState _self;
final $Res Function(WorkspaceNavigationState) _then;
/// Create a copy of WorkspaceNavigationState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? ready = null,
Object? switchingProject = null,
Object? selectedProjectId = freezed,
}) {
return _then(
WorkspaceNavigationState(
ready: null == ready
? _self.ready
: ready // ignore: cast_nullable_to_non_nullable
as bool,
switchingProject: null == switchingProject
? _self.switchingProject
: switchingProject // ignore: cast_nullable_to_non_nullable
as bool,
selectedProjectId: freezed == selectedProjectId
? _self.selectedProjectId
: selectedProjectId // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
/// Adds pattern-matching-related methods to [WorkspaceNavigationState].
extension WorkspaceNavigationStatePatterns on WorkspaceNavigationState {
/// 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(_WorkspaceNavigationState value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _WorkspaceNavigationState() 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(_WorkspaceNavigationState value) $default,
) {
final _that = this;
switch (_that) {
case _WorkspaceNavigationState():
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(_WorkspaceNavigationState value)? $default,
) {
final _that = this;
switch (_that) {
case _WorkspaceNavigationState() 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(
bool ready,
bool switchingProject,
String? selectedProjectId,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _WorkspaceNavigationState() when $default != null:
return $default(
_that.ready,
_that.switchingProject,
_that.selectedProjectId,
);
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(
bool ready,
bool switchingProject,
String? selectedProjectId,
)
$default,
) {
final _that = this;
switch (_that) {
case _WorkspaceNavigationState():
return $default(
_that.ready,
_that.switchingProject,
_that.selectedProjectId,
);
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(
bool ready,
bool switchingProject,
String? selectedProjectId,
)?
$default,
) {
final _that = this;
switch (_that) {
case _WorkspaceNavigationState() when $default != null:
return $default(
_that.ready,
_that.switchingProject,
_that.selectedProjectId,
);
case _:
return null;
}
}
}
/// @nodoc
class _WorkspaceNavigationState
with DiagnosticableTreeMixin
implements WorkspaceNavigationState {
const _WorkspaceNavigationState({
this.ready = false,
this.switchingProject = false,
this.selectedProjectId,
});
@override
@JsonKey()
final bool ready;
@override
@JsonKey()
final bool switchingProject;
@override
final String? selectedProjectId;
/// Create a copy of WorkspaceNavigationState
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$WorkspaceNavigationStateCopyWith<_WorkspaceNavigationState> get copyWith =>
__$WorkspaceNavigationStateCopyWithImpl<_WorkspaceNavigationState>(
this,
_$identity,
);
@override
void debugFillProperties(DiagnosticPropertiesBuilder properties) {
properties
..add(DiagnosticsProperty('type', 'WorkspaceNavigationState'))
..add(DiagnosticsProperty('ready', ready))
..add(DiagnosticsProperty('switchingProject', switchingProject))
..add(DiagnosticsProperty('selectedProjectId', selectedProjectId));
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _WorkspaceNavigationState &&
(identical(other.ready, ready) || other.ready == ready) &&
(identical(other.switchingProject, switchingProject) ||
other.switchingProject == switchingProject) &&
(identical(other.selectedProjectId, selectedProjectId) ||
other.selectedProjectId == selectedProjectId));
}
@override
int get hashCode {
return Object.hash(runtimeType, ready, switchingProject, selectedProjectId);
}
@override
String toString({DiagnosticLevel minLevel = DiagnosticLevel.info}) {
return 'WorkspaceNavigationState(ready: $ready, switchingProject: $switchingProject, selectedProjectId: $selectedProjectId)';
}
}
/// @nodoc
abstract mixin class _$WorkspaceNavigationStateCopyWith<$Res>
implements $WorkspaceNavigationStateCopyWith<$Res> {
factory _$WorkspaceNavigationStateCopyWith(
_WorkspaceNavigationState value,
$Res Function(_WorkspaceNavigationState) _then,
) = __$WorkspaceNavigationStateCopyWithImpl;
@override
@useResult
$Res call({bool ready, bool switchingProject, String? selectedProjectId});
}
/// @nodoc
class __$WorkspaceNavigationStateCopyWithImpl<$Res>
implements _$WorkspaceNavigationStateCopyWith<$Res> {
__$WorkspaceNavigationStateCopyWithImpl(this._self, this._then);
final _WorkspaceNavigationState _self;
final $Res Function(_WorkspaceNavigationState) _then;
/// Create a copy of WorkspaceNavigationState
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? ready = null,
Object? switchingProject = null,
Object? selectedProjectId = freezed,
}) {
return _then(
_WorkspaceNavigationState(
ready: null == ready
? _self.ready
: ready // ignore: cast_nullable_to_non_nullable
as bool,
switchingProject: null == switchingProject
? _self.switchingProject
: switchingProject // ignore: cast_nullable_to_non_nullable
as bool,
selectedProjectId: freezed == selectedProjectId
? _self.selectedProjectId
: selectedProjectId // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
+65
View File
@@ -0,0 +1,65 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'workspace_navigation.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(WorkspaceNavigation)
final workspaceNavigationProvider = WorkspaceNavigationProvider._();
final class WorkspaceNavigationProvider
extends $NotifierProvider<WorkspaceNavigation, WorkspaceNavigationState> {
WorkspaceNavigationProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'workspaceNavigationProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$workspaceNavigationHash();
@$internal
@override
WorkspaceNavigation create() => WorkspaceNavigation();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(WorkspaceNavigationState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<WorkspaceNavigationState>(value),
);
}
}
String _$workspaceNavigationHash() =>
r'00811d2f43d15a47499422a2623fee80cb37dd09';
abstract class _$WorkspaceNavigation
extends $Notifier<WorkspaceNavigationState> {
WorkspaceNavigationState build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref as $Ref<WorkspaceNavigationState, WorkspaceNavigationState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<WorkspaceNavigationState, WorkspaceNavigationState>,
WorkspaceNavigationState,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
@@ -0,0 +1,40 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../features/assistant/chat_controller.dart';
import '../features/projects/conversation_sidebar.dart';
import 'project_state.dart';
import 'timeline_provider.dart';
/// Retains active editing and conversation bindings above replaceable shells.
/// ProjectWorkspace and AgentConversationRegistry remain the resource owners.
class WorkspaceSessionScope extends ConsumerWidget {
const WorkspaceSessionScope({
super.key,
required this.state,
required this.child,
});
final ProjectState state;
final Widget child;
@override
Widget build(BuildContext context, WidgetRef ref) {
final projectId = state.activeProject?.id;
final timelineId = state.timeline?.id;
if (projectId != null && timelineId != null) {
ref.watch(editorTimelineProvider(projectId, timelineId));
}
final selection = ref.watch(conversationSelectionProvider(projectId));
if (projectId != null) {
ref.watch(
chatControllerProvider(
projectId,
conversationId: selection.selectedId,
draftKey: selection.selectedId == null ? selection.draftKey : null,
),
);
}
return child;
}
}