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:
commit
27e77fff39
718 files changed
+183958
No files matched your search
@@ -0,0 +1,103 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../media/media_asset_cover.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../media/audio_asset_tile.dart';
|
||||
|
||||
/// Compact project-media preview shared by the composer and sent messages.
|
||||
class AgentAttachmentCard extends StatelessWidget {
|
||||
const AgentAttachmentCard({super.key, required this.asset, this.onRemove});
|
||||
|
||||
final AssetDocument asset;
|
||||
final VoidCallback? onRemove;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final kind = asset.metadata['kind'];
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final preview = switch (kind) {
|
||||
'image' || 'video' => SizedBox.expand(
|
||||
child: MediaAssetCover(
|
||||
asset: asset,
|
||||
fit: BoxFit.cover,
|
||||
fallback: Center(
|
||||
child: Icon(
|
||||
kind == 'image' ? Icons.image_outlined : Icons.movie_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
errorFallback: Center(
|
||||
child: Icon(
|
||||
Icons.broken_image_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
'audio' => AudioAssetTile(
|
||||
asset: asset,
|
||||
showName: false,
|
||||
aspectRatio: 132 / 96,
|
||||
),
|
||||
_ => Center(
|
||||
child: Icon(
|
||||
Icons.insert_drive_file_outlined,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
};
|
||||
return SizedBox(
|
||||
width: 132,
|
||||
height: 122,
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
child: ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: Column(
|
||||
children: [
|
||||
Expanded(child: SizedBox.expand(child: preview)),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 5,
|
||||
),
|
||||
child: Text(
|
||||
asset.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
if (onRemove != null)
|
||||
Positioned(
|
||||
top: -4,
|
||||
right: -4,
|
||||
child: IconButton.filled(
|
||||
key: Key('agent-attachment-remove-${asset.id}'),
|
||||
tooltip: MaterialLocalizations.of(context).deleteButtonTooltip,
|
||||
onPressed: onRemove,
|
||||
style: IconButton.styleFrom(
|
||||
minimumSize: const Size(20, 20),
|
||||
maximumSize: const Size(20, 20),
|
||||
padding: EdgeInsets.zero,
|
||||
backgroundColor: colors.surface,
|
||||
foregroundColor: colors.onSurface,
|
||||
),
|
||||
icon: const Icon(Icons.close, size: 13),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,84 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
import '../../workspace/media_import_feedback.dart';
|
||||
import 'agent_media_attachments.dart';
|
||||
|
||||
/// Owns attachment operations for one conversation or draft, even while hidden.
|
||||
class AgentComposerController extends ChangeNotifier {
|
||||
AgentComposerController({
|
||||
required this.canImport,
|
||||
required this.pickFiles,
|
||||
required this.importMedia,
|
||||
List<AgentMediaAttachment>? attachments,
|
||||
}) : attachments = attachments ?? [];
|
||||
|
||||
final bool Function() canImport;
|
||||
final Future<List<ExternalMediaFile>> Function() pickFiles;
|
||||
final Future<ExternalMediaSelection?> Function(List<ExternalMediaFile>)
|
||||
importMedia;
|
||||
final List<AgentMediaAttachment> attachments;
|
||||
final feedback = MediaImportFeedbackController();
|
||||
bool _busy = false;
|
||||
bool _disposed = false;
|
||||
bool get busy => _busy;
|
||||
|
||||
void attach(AssetDocument asset) {
|
||||
if (_disposed || attachments.any((item) => item.id == asset.id)) return;
|
||||
attachments.add(AgentMediaAttachment.fromAsset(asset));
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void remove(String id) {
|
||||
attachments.removeWhere((item) => item.id == id);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void clear() {
|
||||
attachments.clear();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
Future<ExternalMediaSelection?> pickAttachments() => _run(pickFiles);
|
||||
|
||||
Future<ExternalMediaSelection?> importAttachments(
|
||||
List<ExternalMediaFile> files,
|
||||
) => _run(() async => files);
|
||||
|
||||
Future<ExternalMediaSelection?> _run(
|
||||
Future<List<ExternalMediaFile>> Function() select,
|
||||
) async {
|
||||
if (_disposed || _busy || !canImport()) return null;
|
||||
_busy = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final files = await select();
|
||||
if (_disposed || files.isEmpty || !canImport()) return null;
|
||||
final result = await importMedia(files);
|
||||
// Deleting the conversation invalidates this destination. Hiding its
|
||||
// presentation does not, so completed imports still populate the draft.
|
||||
if (!_disposed) {
|
||||
for (final asset in result?.selected ?? <AssetDocument>[]) {
|
||||
attach(asset);
|
||||
}
|
||||
feedback.recordResult(result);
|
||||
}
|
||||
return result;
|
||||
} catch (_) {
|
||||
if (!_disposed) feedback.recordFailure();
|
||||
rethrow;
|
||||
} finally {
|
||||
_busy = false;
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
feedback.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/platform/file_picker.dart';
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
import '../../workspace/media_file_extensions.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import 'agent_composer_controller.dart';
|
||||
import 'agent_media_attachments.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
/// Composition survives presentation changes, including temporarily hidden chat.
|
||||
final agentComposerStoreProvider = Provider<AgentComposerStore>((ref) {
|
||||
final store = AgentComposerStore(
|
||||
createComposer: (projectId) => AgentComposerController(
|
||||
canImport: () =>
|
||||
ref.mounted &&
|
||||
projectId != null &&
|
||||
ref.read(platformCapabilitiesProvider).localFileSelection &&
|
||||
ref.read(projectsProvider).value?.activeProject?.id == projectId &&
|
||||
ref.read(projectsProvider).value?.projectBusy == false &&
|
||||
!ref.read(externalMediaImportProvider(projectId)).isLoading,
|
||||
pickFiles: () => ref
|
||||
.read(filePickerProvider)
|
||||
.pickFiles(allowedExtensions: selectableMediaFileExtensions),
|
||||
importMedia: (files) => ref
|
||||
.read(externalMediaImportProvider(projectId!).notifier)
|
||||
.importFiles(files),
|
||||
),
|
||||
);
|
||||
ref.onDispose(store.dispose);
|
||||
return store;
|
||||
});
|
||||
|
||||
final class AgentComposerStore {
|
||||
AgentComposerStore({required this.createComposer});
|
||||
final AgentComposerController Function(String?) createComposer;
|
||||
ComposerDocumentController _draft = ComposerDocumentController();
|
||||
ComposerDocumentController get draft => _draft;
|
||||
final _inputs = <(String?, String), ComposerDocumentController>{};
|
||||
final _composers = <(String?, String), AgentComposerController>{};
|
||||
|
||||
ComposerDocumentController input(String? projectId, String? conversationId) =>
|
||||
conversationId == null
|
||||
? draft
|
||||
: _inputs.putIfAbsent((
|
||||
projectId,
|
||||
conversationId,
|
||||
), ComposerDocumentController.new);
|
||||
|
||||
List<AgentMediaAttachment> attachments(String? projectId, String key) =>
|
||||
composer(projectId, key).attachments;
|
||||
|
||||
AgentComposerController composer(String? projectId, String key) =>
|
||||
_composers.putIfAbsent((projectId, key), () => createComposer(projectId));
|
||||
|
||||
void promoteDraft(String projectId, String draftKey, String conversationId) {
|
||||
final destination = (projectId, conversationId);
|
||||
_inputs.remove(destination)?.dispose();
|
||||
_inputs[destination] = _draft;
|
||||
_draft = ComposerDocumentController();
|
||||
final composer = _composers.remove((projectId, draftKey));
|
||||
if (composer != null) {
|
||||
_composers.remove(destination)?.dispose();
|
||||
_composers[destination] = composer;
|
||||
}
|
||||
}
|
||||
|
||||
void removeConversation(String projectId, String conversationId) {
|
||||
_inputs.remove((projectId, conversationId))?.dispose();
|
||||
_composers.remove((projectId, conversationId))?.dispose();
|
||||
}
|
||||
|
||||
void removeDraft(String? projectId, String draftKey) {
|
||||
_composers.remove((projectId, draftKey))?.dispose();
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
draft.dispose();
|
||||
for (final input in _inputs.values) {
|
||||
input.dispose();
|
||||
}
|
||||
_inputs.clear();
|
||||
for (final composer in _composers.values) {
|
||||
composer.dispose();
|
||||
}
|
||||
_composers.clear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,718 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../diagnostics/agent_request_diagnostics.dart';
|
||||
import '../../diagnostics/app_diagnostics.dart';
|
||||
import '../../integrations/agent/agent_prompt_policy.dart';
|
||||
import '../../integrations/agent/agent_provider.dart';
|
||||
import '../../integrations/agent/agent_runtime_factory.dart';
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import '../../integrations/editor_tools.dart';
|
||||
import 'agent_message_codec.dart';
|
||||
import 'chat_state.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
part 'agent_conversation_service.g.dart';
|
||||
part 'agent_conversation_service.freezed.dart';
|
||||
|
||||
enum AgentConversationFailure {
|
||||
configurationRead,
|
||||
notConfigured,
|
||||
contextBudget,
|
||||
authentication,
|
||||
connection,
|
||||
protocol,
|
||||
request,
|
||||
}
|
||||
|
||||
class AgentConversationException implements Exception {
|
||||
const AgentConversationException(this.failure);
|
||||
final AgentConversationFailure failure;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationMessage with _$AgentConversationMessage {
|
||||
const AgentConversationMessage._();
|
||||
|
||||
const factory AgentConversationMessage({
|
||||
required String text,
|
||||
required bool isUser,
|
||||
int? elapsedMs,
|
||||
}) = _AgentConversationMessage;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationHistory with _$AgentConversationHistory {
|
||||
const factory AgentConversationHistory(
|
||||
List<AgentConversationMessage> messages, {
|
||||
@Default(false) bool exportReplyFailed,
|
||||
@Default(false) bool recoveryRequired,
|
||||
@Default(false) bool resumeAvailable,
|
||||
}) = _AgentConversationHistory;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationPreparation
|
||||
with _$AgentConversationPreparation {
|
||||
const factory AgentConversationPreparation(
|
||||
List<AgentConversationMessage> messages, {
|
||||
required bool sessionChanged,
|
||||
}) = _AgentConversationPreparation;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class AgentConversationOutcome with _$AgentConversationOutcome {
|
||||
const AgentConversationOutcome._();
|
||||
|
||||
const factory AgentConversationOutcome({
|
||||
required String response,
|
||||
required bool completed,
|
||||
required bool failed,
|
||||
ConversationMetadata? conversation,
|
||||
RunFailure? failure,
|
||||
@Default(false) bool paused,
|
||||
@Default(false) bool recoveryRequired,
|
||||
@Default(false) bool exportReplyFailed,
|
||||
int? elapsedMs,
|
||||
}) = _AgentConversationOutcome;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentConversationRegistry agentConversationRegistry(Ref ref) {
|
||||
final registry = AgentConversationRegistry();
|
||||
ref.onDispose(registry.dispose);
|
||||
return registry;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?)
|
||||
agentConversationRuntimeResolver(Ref ref) {
|
||||
return (item) async {
|
||||
if (item == null) return ref.read(agentRuntimeProvider.future);
|
||||
final settings = await ref.read(agentSettingsProvider.future);
|
||||
return ref
|
||||
.read(agentRuntimeFactoryProvider)
|
||||
.createFor(
|
||||
settings,
|
||||
providerId: item.providerId,
|
||||
modelId: item.modelId,
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<EditorAgentBinding> Function(String, String)
|
||||
agentConversationToolsResolver(Ref ref) {
|
||||
return (projectId, timelineId) =>
|
||||
createEditorAgentBinding(ref, projectId, timelineId);
|
||||
}
|
||||
|
||||
class AgentConversationRegistry {
|
||||
final _services = <String, AgentConversationService>{};
|
||||
bool _paused = false;
|
||||
bool get hasRunning => _services.values.any((service) => service.busy);
|
||||
bool get canStart => !_paused;
|
||||
|
||||
Future<T> whilePaused<T>(Future<T> Function() action) async {
|
||||
if (_paused || hasRunning) {
|
||||
throw AppException(AppErrorCode.agentLocationBusy);
|
||||
}
|
||||
_paused = true;
|
||||
try {
|
||||
return await action();
|
||||
} finally {
|
||||
_paused = false;
|
||||
}
|
||||
}
|
||||
|
||||
String _key(String projectId, String id) => '$projectId\u0000$id';
|
||||
|
||||
AgentConversationService obtain(
|
||||
String projectId,
|
||||
String key,
|
||||
String? conversationId,
|
||||
AgentConversationService Function(void Function(String) published) create,
|
||||
) {
|
||||
final lookup = _key(projectId, conversationId ?? 'draft:$key');
|
||||
return _services.putIfAbsent(lookup, () {
|
||||
late final AgentConversationService service;
|
||||
service = create((id) => _services[_key(projectId, id)] = service);
|
||||
return service;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> cancel(String projectId, String id) async =>
|
||||
_services[_key(projectId, id)]?.cancelAndWait();
|
||||
|
||||
Future<void> cancelAll() async {
|
||||
await Future.wait([
|
||||
for (final service in _services.values.toSet()) service.cancelAndWait(),
|
||||
]);
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
for (final service in _services.values.toSet()) {
|
||||
service.dispose();
|
||||
}
|
||||
_services.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
@Riverpod(keepAlive: true)
|
||||
AgentConversationService agentConversationService(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String key,
|
||||
String? conversationId,
|
||||
) {
|
||||
return ref
|
||||
.read(agentConversationRegistryProvider)
|
||||
.obtain(
|
||||
projectId,
|
||||
key,
|
||||
conversationId,
|
||||
(published) => AgentConversationService(
|
||||
projectId: projectId,
|
||||
conversationId: conversationId,
|
||||
canStart: () => ref.read(agentConversationRegistryProvider).canStart,
|
||||
onPublished: published,
|
||||
loadRepository: () => ref.read(conversationRepositoryProvider.future),
|
||||
loadRuntime: ref.read(agentConversationRuntimeResolverProvider),
|
||||
loadTools: (timelineId) => ref.read(
|
||||
agentConversationToolsResolverProvider,
|
||||
)(projectId, timelineId),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Owns one explicit conversation identity, checkpoint recovery and Agent run.
|
||||
class AgentConversationService {
|
||||
AgentConversationService({
|
||||
required this.projectId,
|
||||
required this.conversationId,
|
||||
required this.loadRepository,
|
||||
required this.loadRuntime,
|
||||
required this.loadTools,
|
||||
this.onPublished,
|
||||
this.canStart,
|
||||
});
|
||||
|
||||
final String projectId;
|
||||
final String? conversationId;
|
||||
final Future<ConversationRepository> Function() loadRepository;
|
||||
final Future<AgentRuntime?> Function(ConversationMetadata?) loadRuntime;
|
||||
final Future<EditorAgentBinding> Function(String timelineId) loadTools;
|
||||
final void Function(String id)? onPublished;
|
||||
final bool Function()? canStart;
|
||||
final _changes = StreamController<void>.broadcast();
|
||||
Stream<void> get changes => _changes.stream;
|
||||
AgentChatActivity _activity = AgentChatActivity.replying;
|
||||
AgentChatActivity get activity => _activity;
|
||||
String _partialResponse = '';
|
||||
String get partialResponse => _partialResponse;
|
||||
bool get busy => _busy;
|
||||
|
||||
void _notify() {
|
||||
if (!_changes.isClosed) _changes.add(null);
|
||||
}
|
||||
|
||||
AgentRun? _run;
|
||||
Completer<void>? _settled;
|
||||
bool _cancelRequested = false;
|
||||
bool _disposed = false;
|
||||
bool _busy = false;
|
||||
ConversationMetadata? _created;
|
||||
bool _startingNewConversation = false;
|
||||
int _identityRevision = 0;
|
||||
ConversationMetadata? get metadata => _created;
|
||||
|
||||
void startNewConversation() {
|
||||
if (_busy) throw AppException(AppErrorCode.agentLocationBusy);
|
||||
_identityRevision++;
|
||||
_created = null;
|
||||
_startingNewConversation = true;
|
||||
_partialResponse = '';
|
||||
}
|
||||
|
||||
void _checkActive() {
|
||||
if (_disposed || _cancelRequested) throw const _PreparationCancelled();
|
||||
}
|
||||
|
||||
List<AgentConversationMessage> _messages(
|
||||
SessionSnapshot snapshot, {
|
||||
List<int?> responseDurationsMs = const [],
|
||||
}) {
|
||||
final history = snapshot.history;
|
||||
final result = snapshot.completionEvidence?['result'];
|
||||
final rejectedFinal = result is Map && result['isError'] == true;
|
||||
final visible = <AgentConversationMessage>[];
|
||||
var responseIndex = 0;
|
||||
for (var i = 0; i < history.length; i++) {
|
||||
final message = history[i];
|
||||
if (message.role == MessageRole.tool ||
|
||||
message.runtimeNotice ||
|
||||
message.text.isEmpty ||
|
||||
(message.role == MessageRole.assistant &&
|
||||
((i + 1 < history.length &&
|
||||
history[i + 1].runtimeNotice &&
|
||||
history[i + 1].text.startsWith(
|
||||
'[Runtime artifact verification,',
|
||||
)) ||
|
||||
(i == history.length - 1 && rejectedFinal)))) {
|
||||
continue;
|
||||
}
|
||||
final isUser = message.role == MessageRole.user;
|
||||
visible.add(
|
||||
AgentConversationMessage(
|
||||
text: message.text,
|
||||
isUser: isUser,
|
||||
elapsedMs: isUser || responseIndex >= responseDurationsMs.length
|
||||
? null
|
||||
: responseDurationsMs[responseIndex],
|
||||
),
|
||||
);
|
||||
if (!isUser) responseIndex++;
|
||||
}
|
||||
return visible;
|
||||
}
|
||||
|
||||
Future<AgentConversationHistory?> restore() async {
|
||||
final identityRevision = _identityRevision;
|
||||
final id =
|
||||
_created?.id ?? (_startingNewConversation ? null : conversationId);
|
||||
if (id == null) return null;
|
||||
try {
|
||||
final repository = await loadRepository();
|
||||
final item = await repository.read(projectId, id);
|
||||
if (item == null) return null;
|
||||
final snapshot = await repository.store(item).read(item.id);
|
||||
if (identityRevision != _identityRevision) return null;
|
||||
_created = item;
|
||||
return snapshot == null
|
||||
? null
|
||||
: AgentConversationHistory(
|
||||
_messages(
|
||||
snapshot,
|
||||
responseDurationsMs: item.responseDurationsMs,
|
||||
),
|
||||
exportReplyFailed: _exportReplyFailed(snapshot),
|
||||
resumeAvailable:
|
||||
!_busy &&
|
||||
(snapshot.pending.isNotEmpty ||
|
||||
snapshot.status == RunStatus.running ||
|
||||
snapshot.status == RunStatus.paused),
|
||||
recoveryRequired:
|
||||
!_busy &&
|
||||
(snapshot.status == RunStatus.waiting ||
|
||||
snapshot.pending.any(
|
||||
(call) => call.status == CallStatus.started,
|
||||
)),
|
||||
);
|
||||
} catch (_) {
|
||||
throw const AgentConversationException(AgentConversationFailure.request);
|
||||
}
|
||||
}
|
||||
|
||||
Future<AgentConversationOutcome> send(
|
||||
String text, {
|
||||
required String timelineId,
|
||||
bool summaryOnly = false,
|
||||
bool resumeOnly = false,
|
||||
required void Function(AgentConversationPreparation value) onPrepared,
|
||||
required void Function(String text) onTextDelta,
|
||||
void Function(ConversationMetadata value)? onCreated,
|
||||
}) {
|
||||
final requestId = const Uuid().v4();
|
||||
return withDiagnosticContext(
|
||||
{
|
||||
'requestId': requestId,
|
||||
'projectId': projectId,
|
||||
'timelineId': timelineId,
|
||||
},
|
||||
() => _send(
|
||||
text,
|
||||
requestId: requestId,
|
||||
timelineId: timelineId,
|
||||
summaryOnly: summaryOnly,
|
||||
resumeOnly: resumeOnly,
|
||||
onPrepared: onPrepared,
|
||||
onTextDelta: onTextDelta,
|
||||
onCreated: onCreated,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<AgentConversationOutcome> _send(
|
||||
String text, {
|
||||
required String requestId,
|
||||
required String timelineId,
|
||||
bool summaryOnly = false,
|
||||
bool resumeOnly = false,
|
||||
required void Function(AgentConversationPreparation value) onPrepared,
|
||||
required void Function(String text) onTextDelta,
|
||||
void Function(ConversationMetadata value)? onCreated,
|
||||
}) async {
|
||||
if (canStart?.call() == false) {
|
||||
throw const AgentConversationException(AgentConversationFailure.request);
|
||||
}
|
||||
if (_busy) throw AppException(AppErrorCode.agentLocationBusy);
|
||||
_busy = true;
|
||||
_activity = AgentChatActivity.replying;
|
||||
_settled = Completer<void>();
|
||||
_cancelRequested = false;
|
||||
_partialResponse = '';
|
||||
_notify();
|
||||
final elapsed = Stopwatch()..start();
|
||||
final diagnostics = AgentRequestDiagnostics(requestId: requestId);
|
||||
AgentRun? measuredRun;
|
||||
StreamSubscription<AgentEvent>? subscription;
|
||||
EditorAgentBinding? binding;
|
||||
ConversationRepository? repository;
|
||||
ConversationMetadata? item;
|
||||
try {
|
||||
binding = summaryOnly
|
||||
// Each run needs a distinct ownership token.
|
||||
// ignore: prefer_const_constructors
|
||||
? EditorAgentBinding(owner: Object(), tools: const [])
|
||||
: await loadTools(timelineId);
|
||||
_checkActive();
|
||||
if (!summaryOnly) {
|
||||
final references = AgentComposerMessage.decode(text).references;
|
||||
for (final reference in references) {
|
||||
if (reference.kind == ComposerReferenceKind.timeline &&
|
||||
reference.projectId == projectId) {
|
||||
await binding.ensureTimeline?.call(reference.id);
|
||||
_checkActive();
|
||||
}
|
||||
}
|
||||
}
|
||||
repository = await loadRepository();
|
||||
_checkActive();
|
||||
final savedId =
|
||||
_created?.id ?? (_startingNewConversation ? null : conversationId);
|
||||
item = savedId == null ? null : await repository.read(projectId, savedId);
|
||||
if ((savedId != null || summaryOnly || resumeOnly) && item == null) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.request,
|
||||
);
|
||||
}
|
||||
final AgentRuntime? runtime;
|
||||
try {
|
||||
runtime = await loadRuntime(item);
|
||||
} catch (_) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.configurationRead,
|
||||
);
|
||||
}
|
||||
_checkActive();
|
||||
if (runtime == null) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.notConfigured,
|
||||
);
|
||||
}
|
||||
final system = summaryOnly
|
||||
? _summaryOnlyInstruction
|
||||
: AgentPromptPolicy.forTimeline(projectId, timelineId);
|
||||
final runTools = summaryOnly ? <AgentTool>[] : binding.tools;
|
||||
// Check the mandatory payload before committing a new user turn.
|
||||
try {
|
||||
await runtime.contextBuilder.build(
|
||||
system: system,
|
||||
history: [AgentMessage(role: MessageRole.user, text: text)],
|
||||
tools: [
|
||||
...runTools,
|
||||
...runtime.contextBuilder.runtimeTools(
|
||||
() => SessionSnapshot(id: 'preflight'),
|
||||
runTools,
|
||||
),
|
||||
],
|
||||
cancellation: CancellationToken(),
|
||||
);
|
||||
} on ContextOverflow {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.contextBudget,
|
||||
);
|
||||
}
|
||||
_checkActive();
|
||||
item ??= await repository.begin(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
providerId: runtime.providerId ?? runtime.sessionIdentity,
|
||||
modelId: runtime.modelId ?? runtime.sessionIdentity,
|
||||
title: () {
|
||||
final prompt = AgentComposerMessage.decode(text);
|
||||
final visible = prompt.text.isNotEmpty
|
||||
? prompt.text
|
||||
: prompt.attachments.firstOrNull?.name ?? text;
|
||||
return visible.length <= 64
|
||||
? visible
|
||||
: '${visible.substring(0, 64)}…';
|
||||
}(),
|
||||
);
|
||||
_created = item;
|
||||
final store = repository.store(item);
|
||||
final manager = SessionManager(
|
||||
model: runtime.model,
|
||||
store: store,
|
||||
tools: runTools,
|
||||
contextBuilder: runtime.contextBuilder,
|
||||
completionCheck: summaryOnly ? null : binding.completionCheck,
|
||||
);
|
||||
var snapshot = await store.read(item.id);
|
||||
_checkActive();
|
||||
snapshot ??= await manager.create(id: item.id, system: system);
|
||||
_checkActive();
|
||||
if (summaryOnly &&
|
||||
(!_exportReplyFailed(snapshot) ||
|
||||
snapshot.pending.isNotEmpty ||
|
||||
snapshot.queued.isNotEmpty)) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.request,
|
||||
);
|
||||
}
|
||||
final unfinished =
|
||||
snapshot.pending.isNotEmpty ||
|
||||
snapshot.queued.isNotEmpty ||
|
||||
snapshot.status == RunStatus.running ||
|
||||
snapshot.status == RunStatus.waiting ||
|
||||
snapshot.status == RunStatus.paused;
|
||||
if (resumeOnly && !unfinished) {
|
||||
throw const AgentConversationException(
|
||||
AgentConversationFailure.request,
|
||||
);
|
||||
}
|
||||
onPrepared(
|
||||
AgentConversationPreparation(
|
||||
_messages(snapshot, responseDurationsMs: item.responseDurationsMs),
|
||||
sessionChanged: conversationId == null || _startingNewConversation,
|
||||
),
|
||||
);
|
||||
if (!resumeOnly && unfinished) {
|
||||
return AgentConversationOutcome(
|
||||
response: '',
|
||||
completed: false,
|
||||
failed: true,
|
||||
recoveryRequired: true,
|
||||
conversation: item,
|
||||
);
|
||||
}
|
||||
final run = resumeOnly
|
||||
? await manager.resume(item.id, maxTurns: snapshot.turns + 80)
|
||||
: await manager.prompt(item.id, text, system: system, maxTurns: 80);
|
||||
_run = run;
|
||||
measuredRun = run;
|
||||
diagnostics.prepared();
|
||||
_activity = run.phase == AgentRunPhase.compacting
|
||||
? AgentChatActivity.compacting
|
||||
: AgentChatActivity.replying;
|
||||
_notify();
|
||||
subscription = run.events.listen((event) {
|
||||
if (_disposed) return;
|
||||
if (event.kind == AgentEventKind.phase) {
|
||||
_activity = event.text == AgentRunPhase.compacting.name
|
||||
? AgentChatActivity.compacting
|
||||
: AgentChatActivity.replying;
|
||||
_notify();
|
||||
} else if (event.kind == AgentEventKind.toolStarted) {
|
||||
_activity =
|
||||
event.text.endsWith('_query') ||
|
||||
event.text.endsWith('_list') ||
|
||||
event.text == 'cutdex_workspaces' ||
|
||||
event.text == 'completion_check'
|
||||
? AgentChatActivity.verifying
|
||||
: AgentChatActivity.editing;
|
||||
_notify();
|
||||
}
|
||||
if (!_disposed && event.kind == AgentEventKind.textDelta) {
|
||||
_activity = AgentChatActivity.replying;
|
||||
_partialResponse += event.text;
|
||||
_notify();
|
||||
onTextDelta(event.text);
|
||||
}
|
||||
});
|
||||
if (item.pending) {
|
||||
item = await repository.publish(item);
|
||||
_created = item;
|
||||
onPublished?.call(item.id);
|
||||
onCreated?.call(item);
|
||||
}
|
||||
if (_cancelRequested || _disposed) unawaited(run.cancel());
|
||||
final result = await run.done;
|
||||
diagnostics.outcome = result.status.name;
|
||||
if (result.status == RunStatus.failed ||
|
||||
result.status == RunStatus.waiting) {
|
||||
reportDiagnostic(
|
||||
AppDiagnostics.report,
|
||||
DiagnosticEvent(
|
||||
component: 'agent',
|
||||
operation: 'run',
|
||||
error: StateError(
|
||||
'Agent run ${result.status.name}: ${result.failure?.name ?? 'request'}',
|
||||
),
|
||||
context: {'failure': result.failure?.name},
|
||||
),
|
||||
);
|
||||
}
|
||||
final completed =
|
||||
result.status == RunStatus.completed && !_cancelRequested;
|
||||
final response =
|
||||
completed && result.history.last.role == MessageRole.assistant
|
||||
? result.history.last.text
|
||||
: '';
|
||||
final responseIndex =
|
||||
_messages(result).where((message) => !message.isUser).length - 1;
|
||||
final elapsedMs = completed && response.isNotEmpty
|
||||
? elapsed.elapsedMilliseconds
|
||||
: null;
|
||||
final responseDurationsMs = [...item.responseDurationsMs];
|
||||
if (elapsedMs != null && responseIndex >= 0) {
|
||||
while (responseDurationsMs.length <= responseIndex) {
|
||||
responseDurationsMs.add(null);
|
||||
}
|
||||
responseDurationsMs[responseIndex] = elapsedMs;
|
||||
}
|
||||
item = await repository.update(
|
||||
item.copyWith(
|
||||
timelineId: timelineId,
|
||||
responseDurationsMs: responseDurationsMs,
|
||||
),
|
||||
);
|
||||
_created = item;
|
||||
_partialResponse = '';
|
||||
_notify();
|
||||
return AgentConversationOutcome(
|
||||
response: response,
|
||||
completed: completed,
|
||||
failed:
|
||||
result.status == RunStatus.failed ||
|
||||
result.status == RunStatus.waiting,
|
||||
conversation: item,
|
||||
paused: result.status == RunStatus.paused && !_cancelRequested,
|
||||
recoveryRequired: result.status == RunStatus.waiting,
|
||||
failure: result.failure,
|
||||
exportReplyFailed: _exportReplyFailed(result),
|
||||
elapsedMs: elapsedMs,
|
||||
);
|
||||
} on _PreparationCancelled {
|
||||
diagnostics.outcome = 'cancelled';
|
||||
return AgentConversationOutcome(
|
||||
response: '',
|
||||
completed: false,
|
||||
failed: false,
|
||||
conversation: item,
|
||||
);
|
||||
} on AgentConversationException catch (error, stack) {
|
||||
AppDiagnostics.failure('agent', 'send', error, stack);
|
||||
rethrow;
|
||||
} catch (error, stack) {
|
||||
AppDiagnostics.failure('agent', 'send', error, stack);
|
||||
if (repository != null && item != null && item.pending) {
|
||||
try {
|
||||
final published = await repository.publish(item);
|
||||
_created = published;
|
||||
onPublished?.call(published.id);
|
||||
onCreated?.call(published);
|
||||
} catch (_) {
|
||||
// No user message committed; startup recovery ignores this draft.
|
||||
}
|
||||
}
|
||||
throw const AgentConversationException(AgentConversationFailure.request);
|
||||
} finally {
|
||||
if (measuredRun != null) {
|
||||
diagnostics.runs.add(measuredRun.diagnostics.toJson());
|
||||
}
|
||||
final report = diagnostics.stop();
|
||||
reportDiagnostic(
|
||||
AppDiagnostics.report,
|
||||
DiagnosticEvent(
|
||||
component: 'agent',
|
||||
operation: 'requestFinished',
|
||||
level: DiagnosticSeverity.info,
|
||||
context: {'outcome': report.outcome, 'elapsedUs': report.elapsedUs},
|
||||
),
|
||||
);
|
||||
unawaited(
|
||||
AppDiagnostics.instance?.request(report, requestId) ??
|
||||
Future<void>.value(),
|
||||
);
|
||||
if (repository != null) {
|
||||
await AgentRequestDiagnostics.persist(repository.root, report);
|
||||
}
|
||||
_run = null;
|
||||
_busy = false;
|
||||
_notify();
|
||||
try {
|
||||
await subscription?.cancel();
|
||||
await binding?.release?.call();
|
||||
} finally {
|
||||
_settled?.complete();
|
||||
_settled = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> cancel() async {
|
||||
_cancelRequested = true;
|
||||
final run = _run;
|
||||
if (run != null) {
|
||||
await run.cancel();
|
||||
await _settled?.future;
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> cancelAndWait() async {
|
||||
await cancel();
|
||||
await _settled?.future;
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
unawaited(cancel());
|
||||
unawaited(_changes.close());
|
||||
}
|
||||
}
|
||||
|
||||
class _PreparationCancelled implements Exception {
|
||||
const _PreparationCancelled();
|
||||
}
|
||||
|
||||
const _summaryOnlyInstruction =
|
||||
'Summarize the already completed export and edits from successful tool results. No tools are available. Never claim a new edit or export occurred. State the saved destination and confirmed results in the user language.';
|
||||
|
||||
bool _exportReplyFailed(SessionSnapshot snapshot) {
|
||||
if (snapshot.status != RunStatus.failed ||
|
||||
snapshot.pending.isNotEmpty ||
|
||||
snapshot.queued.isNotEmpty) {
|
||||
return false;
|
||||
}
|
||||
final start = snapshot.system == _summaryOnlyInstruction
|
||||
? 0
|
||||
: snapshot.runStart;
|
||||
final history = snapshot.history.skip(start).toList();
|
||||
final tool = history.where((m) => m.role == MessageRole.tool).lastOrNull;
|
||||
if (tool == null || tool.isError) return false;
|
||||
final calls = history.expand((m) => m.calls);
|
||||
if (!calls.any((c) => c.id == tool.callId && c.name == 'project_export')) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
final result = jsonDecode(tool.text) as Map;
|
||||
final data = result['data'] as Map;
|
||||
return result['isError'] != true &&
|
||||
data['status'] == 'succeeded' &&
|
||||
(data['data'] as Map)['destination'] is String;
|
||||
} on FormatException {
|
||||
return false;
|
||||
} on TypeError {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,268 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_conversation_service.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(agentConversationRegistry)
|
||||
final agentConversationRegistryProvider = AgentConversationRegistryProvider._();
|
||||
|
||||
final class AgentConversationRegistryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentConversationRegistry,
|
||||
AgentConversationRegistry,
|
||||
AgentConversationRegistry
|
||||
>
|
||||
with $Provider<AgentConversationRegistry> {
|
||||
AgentConversationRegistryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentConversationRegistryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationRegistryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentConversationRegistry> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentConversationRegistry create(Ref ref) {
|
||||
return agentConversationRegistry(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentConversationRegistry value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentConversationRegistry>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationRegistryHash() =>
|
||||
r'3e4660057c1e9c91cb6432391f22f528a3589f40';
|
||||
|
||||
@ProviderFor(agentConversationRuntimeResolver)
|
||||
final agentConversationRuntimeResolverProvider =
|
||||
AgentConversationRuntimeResolverProvider._();
|
||||
|
||||
final class AgentConversationRuntimeResolverProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?),
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?),
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?)
|
||||
>
|
||||
with $Provider<Future<AgentRuntime?> Function(ConversationMetadata?)> {
|
||||
AgentConversationRuntimeResolverProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentConversationRuntimeResolverProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationRuntimeResolverHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<Future<AgentRuntime?> Function(ConversationMetadata?)>
|
||||
$createElement($ProviderPointer pointer) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?) create(Ref ref) {
|
||||
return agentConversationRuntimeResolver(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?) value,
|
||||
) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride:
|
||||
$SyncValueProvider<
|
||||
Future<AgentRuntime?> Function(ConversationMetadata?)
|
||||
>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationRuntimeResolverHash() =>
|
||||
r'5a74962d3d1c50771fe2a0743a71abbc8868405a';
|
||||
|
||||
@ProviderFor(agentConversationToolsResolver)
|
||||
final agentConversationToolsResolverProvider =
|
||||
AgentConversationToolsResolverProvider._();
|
||||
|
||||
final class AgentConversationToolsResolverProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
Future<EditorAgentBinding> Function(String, String),
|
||||
Future<EditorAgentBinding> Function(String, String),
|
||||
Future<EditorAgentBinding> Function(String, String)
|
||||
>
|
||||
with $Provider<Future<EditorAgentBinding> Function(String, String)> {
|
||||
AgentConversationToolsResolverProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'agentConversationToolsResolverProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationToolsResolverHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<Future<EditorAgentBinding> Function(String, String)>
|
||||
$createElement($ProviderPointer pointer) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
Future<EditorAgentBinding> Function(String, String) create(Ref ref) {
|
||||
return agentConversationToolsResolver(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(
|
||||
Future<EditorAgentBinding> Function(String, String) value,
|
||||
) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride:
|
||||
$SyncValueProvider<
|
||||
Future<EditorAgentBinding> Function(String, String)
|
||||
>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationToolsResolverHash() =>
|
||||
r'45a68e8151a75e872f48f6bc151046bf1720ae28';
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
@ProviderFor(agentConversationService)
|
||||
final agentConversationServiceProvider = AgentConversationServiceFamily._();
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
final class AgentConversationServiceProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AgentConversationService,
|
||||
AgentConversationService,
|
||||
AgentConversationService
|
||||
>
|
||||
with $Provider<AgentConversationService> {
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
AgentConversationServiceProvider._({
|
||||
required AgentConversationServiceFamily super.from,
|
||||
required (String, String, String?) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'agentConversationServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$agentConversationServiceHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'agentConversationServiceProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AgentConversationService> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AgentConversationService create(Ref ref) {
|
||||
final argument = this.argument as (String, String, String?);
|
||||
return agentConversationService(ref, argument.$1, argument.$2, argument.$3);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AgentConversationService value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AgentConversationService>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is AgentConversationServiceProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$agentConversationServiceHash() =>
|
||||
r'35f3a11cae37f2ab35527e851f468d2fb3467941';
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
final class AgentConversationServiceFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
AgentConversationService,
|
||||
(String, String, String?)
|
||||
> {
|
||||
AgentConversationServiceFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'agentConversationServiceProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: false,
|
||||
);
|
||||
|
||||
/// Not auto-disposed: switching the visible conversation must not stop a run.
|
||||
|
||||
AgentConversationServiceProvider call(
|
||||
String projectId,
|
||||
String key,
|
||||
String? conversationId,
|
||||
) => AgentConversationServiceProvider._(
|
||||
argument: (projectId, key, conversationId),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'agentConversationServiceProvider';
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'agent_media_attachments.freezed.dart';
|
||||
part 'agent_media_attachments.g.dart';
|
||||
|
||||
/// A project-media reference shown in chat and resolved through editor tools.
|
||||
@freezed
|
||||
abstract class AgentMediaAttachment with _$AgentMediaAttachment {
|
||||
const AgentMediaAttachment._();
|
||||
|
||||
const factory AgentMediaAttachment({
|
||||
required String id,
|
||||
required String name,
|
||||
required String kind,
|
||||
}) = _AgentMediaAttachment;
|
||||
|
||||
factory AgentMediaAttachment.fromAsset(AssetDocument asset) =>
|
||||
AgentMediaAttachment(
|
||||
id: asset.id,
|
||||
name: asset.name,
|
||||
kind: asset.metadata['kind'] as String? ?? 'file',
|
||||
);
|
||||
|
||||
factory AgentMediaAttachment.fromJson(Map<String, Object?> json) =>
|
||||
_$AgentMediaAttachmentFromJson(json);
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
// 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 'agent_media_attachments.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$AgentMediaAttachment {
|
||||
String get id;
|
||||
String get name;
|
||||
String get kind;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$AgentMediaAttachmentCopyWith<AgentMediaAttachment> get copyWith =>
|
||||
_$AgentMediaAttachmentCopyWithImpl<AgentMediaAttachment>(
|
||||
this as AgentMediaAttachment,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
/// Serializes this AgentMediaAttachment to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as AgentMediaAttachment;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is AgentMediaAttachment &&
|
||||
(identical(other.id, _this.id) || other.id == _this.id) &&
|
||||
(identical(other.name, _this.name) || other.name == _this.name) &&
|
||||
(identical(other.kind, _this.kind) || other.kind == _this.kind));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as AgentMediaAttachment;
|
||||
return Object.hash(runtimeType, _this.id, _this.name, _this.kind);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as AgentMediaAttachment;
|
||||
return 'AgentMediaAttachment(id: ${_this.id}, name: ${_this.name}, kind: ${_this.kind})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $AgentMediaAttachmentCopyWith<$Res> {
|
||||
factory $AgentMediaAttachmentCopyWith(
|
||||
AgentMediaAttachment value,
|
||||
$Res Function(AgentMediaAttachment) _then,
|
||||
) = _$AgentMediaAttachmentCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({String id, String name, String kind});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$AgentMediaAttachmentCopyWithImpl<$Res>
|
||||
implements $AgentMediaAttachmentCopyWith<$Res> {
|
||||
_$AgentMediaAttachmentCopyWithImpl(this._self, this._then);
|
||||
|
||||
final AgentMediaAttachment _self;
|
||||
final $Res Function(AgentMediaAttachment) _then;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? id = null, Object? name = null, Object? kind = null}) {
|
||||
return _then(
|
||||
AgentMediaAttachment(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
kind: null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [AgentMediaAttachment].
|
||||
extension AgentMediaAttachmentPatterns on AgentMediaAttachment {
|
||||
/// 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(_AgentMediaAttachment value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() 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(_AgentMediaAttachment value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment():
|
||||
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(_AgentMediaAttachment value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() 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 id, String name, String kind)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() when $default != null:
|
||||
return $default(_that.id, _that.name, _that.kind);
|
||||
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 id, String name, String kind) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment():
|
||||
return $default(_that.id, _that.name, _that.kind);
|
||||
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 id, String name, String kind)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentMediaAttachment() when $default != null:
|
||||
return $default(_that.id, _that.name, _that.kind);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _AgentMediaAttachment extends AgentMediaAttachment {
|
||||
const _AgentMediaAttachment({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.kind,
|
||||
}) : super._();
|
||||
factory _AgentMediaAttachment.fromJson(Map<String, dynamic> json) =>
|
||||
_$AgentMediaAttachmentFromJson(json);
|
||||
|
||||
@override
|
||||
final String id;
|
||||
@override
|
||||
final String name;
|
||||
@override
|
||||
final String kind;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$AgentMediaAttachmentCopyWith<_AgentMediaAttachment> get copyWith =>
|
||||
__$AgentMediaAttachmentCopyWithImpl<_AgentMediaAttachment>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$AgentMediaAttachmentToJson(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _AgentMediaAttachment &&
|
||||
(identical(other.id, id) || other.id == id) &&
|
||||
(identical(other.name, name) || other.name == name) &&
|
||||
(identical(other.kind, kind) || other.kind == kind));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, id, name, kind);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AgentMediaAttachment(id: $id, name: $name, kind: $kind)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$AgentMediaAttachmentCopyWith<$Res>
|
||||
implements $AgentMediaAttachmentCopyWith<$Res> {
|
||||
factory _$AgentMediaAttachmentCopyWith(
|
||||
_AgentMediaAttachment value,
|
||||
$Res Function(_AgentMediaAttachment) _then,
|
||||
) = __$AgentMediaAttachmentCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({String id, String name, String kind});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$AgentMediaAttachmentCopyWithImpl<$Res>
|
||||
implements _$AgentMediaAttachmentCopyWith<$Res> {
|
||||
__$AgentMediaAttachmentCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _AgentMediaAttachment _self;
|
||||
final $Res Function(_AgentMediaAttachment) _then;
|
||||
|
||||
/// Create a copy of AgentMediaAttachment
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? id = null, Object? name = null, Object? kind = null}) {
|
||||
return _then(
|
||||
_AgentMediaAttachment(
|
||||
id: null == id
|
||||
? _self.id
|
||||
: id // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
kind: null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_media_attachments.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_AgentMediaAttachment _$AgentMediaAttachmentFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _AgentMediaAttachment(
|
||||
id: json['id'] as String,
|
||||
name: json['name'] as String,
|
||||
kind: json['kind'] as String,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$AgentMediaAttachmentToJson(
|
||||
_AgentMediaAttachment instance,
|
||||
) => <String, dynamic>{
|
||||
'id': instance.id,
|
||||
'name': instance.name,
|
||||
'kind': instance.kind,
|
||||
};
|
||||
@@ -0,0 +1,79 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'agent_media_attachments.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
part 'agent_message_codec.freezed.dart';
|
||||
part 'agent_message_codec.g.dart';
|
||||
|
||||
@freezed
|
||||
abstract class AgentComposerMessage with _$AgentComposerMessage {
|
||||
const AgentComposerMessage._();
|
||||
|
||||
const factory AgentComposerMessage({
|
||||
required String text,
|
||||
required List<AgentMediaAttachment> attachments,
|
||||
required List<ComposerSegment> segments,
|
||||
}) = _AgentComposerMessage;
|
||||
|
||||
factory AgentComposerMessage.fromJson(Map<String, Object?> json) =>
|
||||
_$AgentComposerMessageFromJson(json);
|
||||
|
||||
List<ComposerReference> get references => [
|
||||
for (final segment in segments)
|
||||
if (segment case ComposerReferenceSegment(:final value)) value,
|
||||
];
|
||||
|
||||
static const _prefix = '[Cutdex composer message] ';
|
||||
static const _separator = '\n\n';
|
||||
|
||||
static String encodeDocument(
|
||||
List<ComposerSegment> segments,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
) => _encode(
|
||||
AgentComposerMessage(
|
||||
text: segments.map((segment) => segment.displayText).join().trim(),
|
||||
attachments: attachments,
|
||||
segments: segments,
|
||||
),
|
||||
);
|
||||
|
||||
static String _encode(AgentComposerMessage message) {
|
||||
if (message.attachments.isEmpty && message.references.isEmpty) {
|
||||
return message.text;
|
||||
}
|
||||
final data = jsonEncode(message.toJson());
|
||||
return '$_prefix$data$_separator'
|
||||
'These references identify project resources by stable ID, not file '
|
||||
'contents. A referenced timeline is context, not an instruction to '
|
||||
"switch the user's current timeline. Resolve each ID with media_query "
|
||||
'or the relevant project tool when needed.$_separator${message.text}';
|
||||
}
|
||||
|
||||
static AgentComposerMessage decode(String value) {
|
||||
AgentComposerMessage plain() => AgentComposerMessage(
|
||||
text: value,
|
||||
attachments: const [],
|
||||
segments: const [],
|
||||
);
|
||||
if (!value.startsWith(_prefix)) return plain();
|
||||
final end = value.indexOf(_separator, _prefix.length);
|
||||
if (end < 0) return plain();
|
||||
try {
|
||||
final data = jsonDecode(value.substring(_prefix.length, end));
|
||||
return AgentComposerMessage.fromJson(
|
||||
(data as Map).cast<String, Object?>(),
|
||||
);
|
||||
} on FormatException {
|
||||
return plain();
|
||||
} on CheckedFromJsonException {
|
||||
return plain();
|
||||
} on TypeError {
|
||||
return plain();
|
||||
} on ArgumentError {
|
||||
return plain();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
// 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 'agent_message_codec.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$AgentComposerMessage {
|
||||
String get text;
|
||||
List<AgentMediaAttachment> get attachments;
|
||||
List<ComposerSegment> get segments;
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$AgentComposerMessageCopyWith<AgentComposerMessage> get copyWith =>
|
||||
_$AgentComposerMessageCopyWithImpl<AgentComposerMessage>(
|
||||
this as AgentComposerMessage,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
/// Serializes this AgentComposerMessage to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as AgentComposerMessage;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is AgentComposerMessage &&
|
||||
(identical(other.text, _this.text) || other.text == _this.text) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.attachments,
|
||||
_this.attachments,
|
||||
) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.segments,
|
||||
_this.segments,
|
||||
));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as AgentComposerMessage;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.text,
|
||||
const DeepCollectionEquality().hash(_this.attachments),
|
||||
const DeepCollectionEquality().hash(_this.segments),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as AgentComposerMessage;
|
||||
return 'AgentComposerMessage(text: ${_this.text}, attachments: ${_this.attachments}, segments: ${_this.segments})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $AgentComposerMessageCopyWith<$Res> {
|
||||
factory $AgentComposerMessageCopyWith(
|
||||
AgentComposerMessage value,
|
||||
$Res Function(AgentComposerMessage) _then,
|
||||
) = _$AgentComposerMessageCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$AgentComposerMessageCopyWithImpl<$Res>
|
||||
implements $AgentComposerMessageCopyWith<$Res> {
|
||||
_$AgentComposerMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final AgentComposerMessage _self;
|
||||
final $Res Function(AgentComposerMessage) _then;
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? attachments = null,
|
||||
Object? segments = null,
|
||||
}) {
|
||||
return _then(
|
||||
AgentComposerMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
attachments: null == attachments
|
||||
? _self.attachments
|
||||
: attachments // ignore: cast_nullable_to_non_nullable
|
||||
as List<AgentMediaAttachment>,
|
||||
segments: null == segments
|
||||
? _self.segments
|
||||
: segments // ignore: cast_nullable_to_non_nullable
|
||||
as List<ComposerSegment>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [AgentComposerMessage].
|
||||
extension AgentComposerMessagePatterns on AgentComposerMessage {
|
||||
/// 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(_AgentComposerMessage value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() 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(_AgentComposerMessage value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage():
|
||||
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(_AgentComposerMessage value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() 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 text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() when $default != null:
|
||||
return $default(_that.text, _that.attachments, _that.segments);
|
||||
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 text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage():
|
||||
return $default(_that.text, _that.attachments, _that.segments);
|
||||
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 text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _AgentComposerMessage() when $default != null:
|
||||
return $default(_that.text, _that.attachments, _that.segments);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _AgentComposerMessage extends AgentComposerMessage {
|
||||
const _AgentComposerMessage({
|
||||
required this.text,
|
||||
required List<AgentMediaAttachment> attachments,
|
||||
required List<ComposerSegment> segments,
|
||||
}) : _attachments = attachments,
|
||||
_segments = segments,
|
||||
super._();
|
||||
factory _AgentComposerMessage.fromJson(Map<String, dynamic> json) =>
|
||||
_$AgentComposerMessageFromJson(json);
|
||||
|
||||
@override
|
||||
final String text;
|
||||
final List<AgentMediaAttachment> _attachments;
|
||||
@override
|
||||
List<AgentMediaAttachment> get attachments {
|
||||
if (_attachments is EqualUnmodifiableListView) return _attachments;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_attachments);
|
||||
}
|
||||
|
||||
final List<ComposerSegment> _segments;
|
||||
@override
|
||||
List<ComposerSegment> get segments {
|
||||
if (_segments is EqualUnmodifiableListView) return _segments;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_segments);
|
||||
}
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$AgentComposerMessageCopyWith<_AgentComposerMessage> get copyWith =>
|
||||
__$AgentComposerMessageCopyWithImpl<_AgentComposerMessage>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$AgentComposerMessageToJson(this);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _AgentComposerMessage &&
|
||||
(identical(other.text, text) || other.text == text) &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.attachments,
|
||||
_attachments,
|
||||
) &&
|
||||
const DeepCollectionEquality().equals(other.segments, _segments));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
text,
|
||||
const DeepCollectionEquality().hash(_attachments),
|
||||
const DeepCollectionEquality().hash(_segments),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'AgentComposerMessage(text: $text, attachments: $attachments, segments: $segments)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$AgentComposerMessageCopyWith<$Res>
|
||||
implements $AgentComposerMessageCopyWith<$Res> {
|
||||
factory _$AgentComposerMessageCopyWith(
|
||||
_AgentComposerMessage value,
|
||||
$Res Function(_AgentComposerMessage) _then,
|
||||
) = __$AgentComposerMessageCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
String text,
|
||||
List<AgentMediaAttachment> attachments,
|
||||
List<ComposerSegment> segments,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$AgentComposerMessageCopyWithImpl<$Res>
|
||||
implements _$AgentComposerMessageCopyWith<$Res> {
|
||||
__$AgentComposerMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _AgentComposerMessage _self;
|
||||
final $Res Function(_AgentComposerMessage) _then;
|
||||
|
||||
/// Create a copy of AgentComposerMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? attachments = null,
|
||||
Object? segments = null,
|
||||
}) {
|
||||
return _then(
|
||||
_AgentComposerMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
attachments: null == attachments
|
||||
? _self._attachments
|
||||
: attachments // ignore: cast_nullable_to_non_nullable
|
||||
as List<AgentMediaAttachment>,
|
||||
segments: null == segments
|
||||
? _self._segments
|
||||
: segments // ignore: cast_nullable_to_non_nullable
|
||||
as List<ComposerSegment>,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'agent_message_codec.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_AgentComposerMessage _$AgentComposerMessageFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => _AgentComposerMessage(
|
||||
text: json['text'] as String,
|
||||
attachments: (json['attachments'] as List<dynamic>)
|
||||
.map((e) => AgentMediaAttachment.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
segments: (json['segments'] as List<dynamic>)
|
||||
.map((e) => ComposerSegment.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$AgentComposerMessageToJson(
|
||||
_AgentComposerMessage instance,
|
||||
) => <String, dynamic>{
|
||||
'text': instance.text,
|
||||
'attachments': instance.attachments.map((e) => e.toJson()).toList(),
|
||||
'segments': instance.segments.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
const _softBreak = '\u200B';
|
||||
|
||||
String _breakLongAsciiRuns(String text) {
|
||||
final result = StringBuffer();
|
||||
int? previous;
|
||||
for (final rune in text.runes) {
|
||||
if (previous != null &&
|
||||
previous >= 0x21 &&
|
||||
previous <= 0x7e &&
|
||||
rune >= 0x21 &&
|
||||
rune <= 0x7e) {
|
||||
result.write(_softBreak);
|
||||
}
|
||||
result.writeCharCode(rune);
|
||||
previous = rune;
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
class _CopyPlainTextIntent extends Intent {
|
||||
const _CopyPlainTextIntent();
|
||||
}
|
||||
|
||||
/// Allows paths and other long ASCII runs to wrap without changing copied text.
|
||||
class BreakableSelectableText extends StatefulWidget {
|
||||
const BreakableSelectableText({
|
||||
super.key,
|
||||
required this.text,
|
||||
required this.style,
|
||||
});
|
||||
|
||||
final String text;
|
||||
final TextStyle style;
|
||||
|
||||
@override
|
||||
State<BreakableSelectableText> createState() =>
|
||||
_BreakableSelectableTextState();
|
||||
}
|
||||
|
||||
class _BreakableSelectableTextState extends State<BreakableSelectableText> {
|
||||
TextSelection _selection = const TextSelection.collapsed(offset: -1);
|
||||
|
||||
void _copySelection(String displayText, TextSelection selection) {
|
||||
if (!selection.isValid || selection.isCollapsed) return;
|
||||
final text = selection.textInside(displayText).replaceAll(_softBreak, '');
|
||||
Clipboard.setData(ClipboardData(text: text));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final displayText = _breakLongAsciiRuns(widget.text);
|
||||
return Shortcuts(
|
||||
shortcuts: const {
|
||||
SingleActivator(LogicalKeyboardKey.keyC, meta: true):
|
||||
_CopyPlainTextIntent(),
|
||||
SingleActivator(LogicalKeyboardKey.keyC, control: true):
|
||||
_CopyPlainTextIntent(),
|
||||
},
|
||||
child: Actions(
|
||||
actions: {
|
||||
_CopyPlainTextIntent: CallbackAction<_CopyPlainTextIntent>(
|
||||
onInvoke: (_) {
|
||||
_copySelection(displayText, _selection);
|
||||
return null;
|
||||
},
|
||||
),
|
||||
},
|
||||
child: SelectableText(
|
||||
displayText,
|
||||
style: widget.style,
|
||||
textAlign: TextAlign.start,
|
||||
semanticsLabel: widget.text,
|
||||
onSelectionChanged: (selection, _) => _selection = selection,
|
||||
contextMenuBuilder: (context, editable) =>
|
||||
AdaptiveTextSelectionToolbar.buttonItems(
|
||||
anchors: editable.contextMenuAnchors,
|
||||
buttonItems: [
|
||||
for (final button in editable.contextMenuButtonItems)
|
||||
if (button.type == ContextMenuButtonType.copy)
|
||||
button.copyWith(
|
||||
onPressed: () {
|
||||
_copySelection(
|
||||
displayText,
|
||||
editable.textEditingValue.selection,
|
||||
);
|
||||
editable.hideToolbar();
|
||||
},
|
||||
)
|
||||
else
|
||||
button,
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_agent/cutdex_agent.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../integrations/agent/agent_settings.dart';
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import 'agent_conversation_service.dart';
|
||||
import 'chat_state.dart';
|
||||
|
||||
part 'chat_controller.g.dart';
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
@riverpod
|
||||
class ChatController extends _$ChatController {
|
||||
late AgentConversationService _conversation;
|
||||
AgentConversationService? _activeConversation;
|
||||
int _sendRevision = 0;
|
||||
|
||||
@override
|
||||
ChatState build(
|
||||
String projectId, {
|
||||
String? conversationId,
|
||||
String? draftKey,
|
||||
}) {
|
||||
_conversation = ref.watch(
|
||||
agentConversationServiceProvider(
|
||||
projectId,
|
||||
draftKey ?? conversationId ?? 'new',
|
||||
conversationId,
|
||||
),
|
||||
);
|
||||
final subscription = _conversation.changes.listen((_) {
|
||||
if (!ref.mounted) return;
|
||||
state = state.copyWith(
|
||||
busy: _conversation.busy,
|
||||
partialResponse: _conversation.partialResponse,
|
||||
activity: _conversation.activity,
|
||||
);
|
||||
if (!_conversation.busy && _activeConversation == null) {
|
||||
unawaited(_restore(force: true));
|
||||
}
|
||||
});
|
||||
ref.onDispose(subscription.cancel);
|
||||
unawaited(Future<void>.microtask(_restore));
|
||||
return ChatState(
|
||||
busy: _conversation.busy,
|
||||
partialResponse: _conversation.partialResponse,
|
||||
activity: _conversation.activity,
|
||||
);
|
||||
}
|
||||
|
||||
List<ChatMessage> _messages(List<AgentConversationMessage> messages) => [
|
||||
for (final message in messages)
|
||||
ChatMessage(
|
||||
text: message.text,
|
||||
isUser: message.isUser,
|
||||
elapsedMs: message.elapsedMs,
|
||||
),
|
||||
];
|
||||
|
||||
Future<void> _restore({bool force = false}) async {
|
||||
if ((_sendRevision != 0 && !force) || !ref.mounted) return;
|
||||
final revision = _sendRevision;
|
||||
try {
|
||||
final history = await _conversation.restore();
|
||||
if (!ref.mounted || revision != _sendRevision) return;
|
||||
state = state.copyWith(
|
||||
messages: history == null
|
||||
? state.messages
|
||||
: _messages(history.messages),
|
||||
conversation: _conversation.metadata,
|
||||
error: history?.exportReplyFailed == true
|
||||
? AgentChatError.exportReplyFailed
|
||||
: history?.recoveryRequired == true
|
||||
? AgentChatError.recoveryRequired
|
||||
: history?.resumeAvailable == true
|
||||
? AgentChatError.interrupted
|
||||
: null,
|
||||
);
|
||||
} on AgentConversationException catch (error) {
|
||||
if (ref.mounted && revision == _sendRevision) {
|
||||
state = state.copyWith(
|
||||
error: error.failure == AgentConversationFailure.configurationRead
|
||||
? AgentChatError.configurationReadFailed
|
||||
: AgentChatError.sessionRestoreFailed,
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (ref.mounted && revision == _sendRevision) {
|
||||
state = state.copyWith(error: AgentChatError.sessionRestoreFailed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> selectModel(String providerId, String modelId) async {
|
||||
if (state.busy) return;
|
||||
final previous = state.conversation;
|
||||
await ref
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.selectModel(providerId, modelId);
|
||||
if (!ref.mounted) return;
|
||||
if ((previous != null &&
|
||||
(previous.providerId != providerId ||
|
||||
previous.modelId != modelId)) ||
|
||||
(previous == null && conversationId != null)) {
|
||||
_sendRevision++;
|
||||
_conversation.startNewConversation();
|
||||
state = const ChatState();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> send(
|
||||
String input, {
|
||||
required String timelineId,
|
||||
bool summaryOnly = false,
|
||||
bool resumeOnly = false,
|
||||
void Function(ConversationMetadata value)? onCreated,
|
||||
void Function(ConversationMetadata value)? onUpdated,
|
||||
}) async {
|
||||
final text = input.trim();
|
||||
if (text.isEmpty || state.busy) return;
|
||||
_sendRevision++;
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
...state.messages,
|
||||
if (!resumeOnly) ChatMessage(text: text, isUser: true),
|
||||
],
|
||||
partialResponse: '',
|
||||
busy: true,
|
||||
stopping: false,
|
||||
error: null,
|
||||
);
|
||||
final conversation = _conversation;
|
||||
_activeConversation = conversation;
|
||||
var streamed = '';
|
||||
try {
|
||||
final outcome = await conversation.send(
|
||||
text,
|
||||
timelineId: timelineId,
|
||||
summaryOnly: summaryOnly,
|
||||
resumeOnly: resumeOnly,
|
||||
onCreated: (item) {
|
||||
if (ref.mounted) state = state.copyWith(conversation: item);
|
||||
onCreated?.call(item);
|
||||
},
|
||||
onPrepared: (preparation) {
|
||||
if (!ref.mounted || !preparation.sessionChanged) return;
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
..._messages(preparation.messages),
|
||||
if (!resumeOnly) ChatMessage(text: text, isUser: true),
|
||||
],
|
||||
);
|
||||
},
|
||||
onTextDelta: (delta) {
|
||||
streamed += delta;
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(
|
||||
partialResponse: state.partialResponse + delta,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
if (outcome.conversation case final item?) {
|
||||
if (ref.mounted) state = state.copyWith(conversation: item);
|
||||
onUpdated?.call(item);
|
||||
}
|
||||
if (outcome.recoveryRequired) {
|
||||
final history = await conversation.restore();
|
||||
if (ref.mounted && history != null) {
|
||||
state = state.copyWith(messages: _messages(history.messages));
|
||||
}
|
||||
}
|
||||
if (!ref.mounted) return;
|
||||
final response = outcome.completed && outcome.response.isNotEmpty
|
||||
? outcome.response
|
||||
: streamed;
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
...state.messages,
|
||||
if (response.isNotEmpty)
|
||||
ChatMessage(
|
||||
text: response,
|
||||
interrupted: !outcome.completed,
|
||||
elapsedMs: outcome.elapsedMs,
|
||||
),
|
||||
],
|
||||
partialResponse: '',
|
||||
error: outcome.exportReplyFailed
|
||||
? AgentChatError.exportReplyFailed
|
||||
: outcome.recoveryRequired
|
||||
? AgentChatError.recoveryRequired
|
||||
: outcome.paused
|
||||
? AgentChatError.turnLimit
|
||||
: outcome.failed
|
||||
? switch (outcome.failure) {
|
||||
RunFailure.contextBudget => AgentChatError.contextBudget,
|
||||
RunFailure.authentication => AgentChatError.authentication,
|
||||
RunFailure.connection => AgentChatError.connection,
|
||||
RunFailure.protocol => AgentChatError.protocol,
|
||||
_ => AgentChatError.replyFailed,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
} on AgentConversationException catch (error) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(
|
||||
messages: [
|
||||
...state.messages,
|
||||
if (streamed.isNotEmpty)
|
||||
ChatMessage(text: streamed, interrupted: true),
|
||||
],
|
||||
partialResponse: '',
|
||||
error: switch (error.failure) {
|
||||
AgentConversationFailure.configurationRead =>
|
||||
AgentChatError.configurationReadFailed,
|
||||
AgentConversationFailure.notConfigured =>
|
||||
AgentChatError.configurationRequired,
|
||||
AgentConversationFailure.contextBudget =>
|
||||
AgentChatError.contextBudget,
|
||||
AgentConversationFailure.authentication =>
|
||||
AgentChatError.authentication,
|
||||
AgentConversationFailure.connection => AgentChatError.connection,
|
||||
AgentConversationFailure.protocol => AgentChatError.protocol,
|
||||
AgentConversationFailure.request => AgentChatError.requestFailed,
|
||||
},
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(
|
||||
partialResponse: '',
|
||||
error: AgentChatError.requestFailed,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (identical(_activeConversation, conversation)) {
|
||||
_activeConversation = null;
|
||||
}
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(busy: false, stopping: false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> stop() async {
|
||||
if (!state.busy) return;
|
||||
state = state.copyWith(stopping: true);
|
||||
final conversation = _activeConversation ?? _conversation;
|
||||
await conversation.cancel();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'chat_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
@ProviderFor(ChatController)
|
||||
final chatControllerProvider = ChatControllerFamily._();
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
final class ChatControllerProvider
|
||||
extends $NotifierProvider<ChatController, ChatState> {
|
||||
/// Presentation state for one project conversation.
|
||||
ChatControllerProvider._({
|
||||
required ChatControllerFamily super.from,
|
||||
required (String, {String? conversationId, String? draftKey})
|
||||
super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'chatControllerProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$chatControllerHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'chatControllerProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ChatController create() => ChatController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ChatState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ChatState>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is ChatControllerProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$chatControllerHash() => r'b10209ff2924c59cc7c70c57db289a73837aa257';
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
final class ChatControllerFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
ChatController,
|
||||
ChatState,
|
||||
ChatState,
|
||||
ChatState,
|
||||
(String, {String? conversationId, String? draftKey})
|
||||
> {
|
||||
ChatControllerFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'chatControllerProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
ChatControllerProvider call(
|
||||
String projectId, {
|
||||
String? conversationId,
|
||||
String? draftKey,
|
||||
}) => ChatControllerProvider._(
|
||||
argument: (projectId, conversationId: conversationId, draftKey: draftKey),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'chatControllerProvider';
|
||||
}
|
||||
|
||||
/// Presentation state for one project conversation.
|
||||
|
||||
abstract class _$ChatController extends $Notifier<ChatState> {
|
||||
late final _$args =
|
||||
ref.$arg as (String, {String? conversationId, String? draftKey});
|
||||
String get projectId => _$args.$1;
|
||||
String? get conversationId => _$args.conversationId;
|
||||
String? get draftKey => _$args.draftKey;
|
||||
|
||||
ChatState build(String projectId, {String? conversationId, String? draftKey});
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<ChatState, ChatState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<ChatState, ChatState>,
|
||||
ChatState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(
|
||||
ref,
|
||||
() => build(
|
||||
_$args.$1,
|
||||
conversationId: _$args.conversationId,
|
||||
draftKey: _$args.draftKey,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
|
||||
part 'chat_state.freezed.dart';
|
||||
|
||||
enum AgentChatActivity { replying, compacting, editing, verifying }
|
||||
|
||||
enum AgentChatError {
|
||||
configurationReadFailed,
|
||||
configurationRequired,
|
||||
sessionRestoreFailed,
|
||||
contextBudget,
|
||||
authentication,
|
||||
connection,
|
||||
protocol,
|
||||
replyFailed,
|
||||
turnLimit,
|
||||
recoveryRequired,
|
||||
interrupted,
|
||||
exportReplyFailed,
|
||||
requestFailed,
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ChatMessage with _$ChatMessage {
|
||||
const factory ChatMessage({
|
||||
required String text,
|
||||
@Default(false) bool isUser,
|
||||
@Default(false) bool interrupted,
|
||||
int? elapsedMs,
|
||||
}) = _ChatMessage;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ChatState with _$ChatState {
|
||||
const factory ChatState({
|
||||
@Default([]) List<ChatMessage> messages,
|
||||
@Default('') String partialResponse,
|
||||
@Default(AgentChatActivity.replying) AgentChatActivity activity,
|
||||
@Default(false) bool busy,
|
||||
@Default(false) bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
}) = _ChatState;
|
||||
}
|
||||
@@ -0,0 +1,935 @@
|
||||
// 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 'chat_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ChatMessage {
|
||||
String get text;
|
||||
bool get isUser;
|
||||
bool get interrupted;
|
||||
int? get elapsedMs;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ChatMessageCopyWith<ChatMessage> get copyWith =>
|
||||
_$ChatMessageCopyWithImpl<ChatMessage>(this as ChatMessage, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ChatMessage;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ChatMessage &&
|
||||
(identical(other.text, _this.text) || other.text == _this.text) &&
|
||||
(identical(other.isUser, _this.isUser) ||
|
||||
other.isUser == _this.isUser) &&
|
||||
(identical(other.interrupted, _this.interrupted) ||
|
||||
other.interrupted == _this.interrupted) &&
|
||||
(identical(other.elapsedMs, _this.elapsedMs) ||
|
||||
other.elapsedMs == _this.elapsedMs));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ChatMessage;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.text,
|
||||
_this.isUser,
|
||||
_this.interrupted,
|
||||
_this.elapsedMs,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ChatMessage;
|
||||
return 'ChatMessage(text: ${_this.text}, isUser: ${_this.isUser}, interrupted: ${_this.interrupted}, elapsedMs: ${_this.elapsedMs})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ChatMessageCopyWith<$Res> {
|
||||
factory $ChatMessageCopyWith(
|
||||
ChatMessage value,
|
||||
$Res Function(ChatMessage) _then,
|
||||
) = _$ChatMessageCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({String text, bool isUser, bool interrupted, int? elapsedMs});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ChatMessageCopyWithImpl<$Res> implements $ChatMessageCopyWith<$Res> {
|
||||
_$ChatMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ChatMessage _self;
|
||||
final $Res Function(ChatMessage) _then;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? isUser = null,
|
||||
Object? interrupted = null,
|
||||
Object? elapsedMs = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
ChatMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
isUser: null == isUser
|
||||
? _self.isUser
|
||||
: isUser // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
interrupted: null == interrupted
|
||||
? _self.interrupted
|
||||
: interrupted // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
elapsedMs: freezed == elapsedMs
|
||||
? _self.elapsedMs
|
||||
: elapsedMs // ignore: cast_nullable_to_non_nullable
|
||||
as int?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ChatMessage].
|
||||
extension ChatMessagePatterns on ChatMessage {
|
||||
/// 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(_ChatMessage value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() 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(_ChatMessage value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage():
|
||||
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(_ChatMessage value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() 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 text,
|
||||
bool isUser,
|
||||
bool interrupted,
|
||||
int? elapsedMs,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() when $default != null:
|
||||
return $default(
|
||||
_that.text,
|
||||
_that.isUser,
|
||||
_that.interrupted,
|
||||
_that.elapsedMs,
|
||||
);
|
||||
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 text, bool isUser, bool interrupted, int? elapsedMs)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage():
|
||||
return $default(
|
||||
_that.text,
|
||||
_that.isUser,
|
||||
_that.interrupted,
|
||||
_that.elapsedMs,
|
||||
);
|
||||
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 text,
|
||||
bool isUser,
|
||||
bool interrupted,
|
||||
int? elapsedMs,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatMessage() when $default != null:
|
||||
return $default(
|
||||
_that.text,
|
||||
_that.isUser,
|
||||
_that.interrupted,
|
||||
_that.elapsedMs,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ChatMessage implements ChatMessage {
|
||||
const _ChatMessage({
|
||||
required this.text,
|
||||
this.isUser = false,
|
||||
this.interrupted = false,
|
||||
this.elapsedMs,
|
||||
});
|
||||
|
||||
@override
|
||||
final String text;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool isUser;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool interrupted;
|
||||
@override
|
||||
final int? elapsedMs;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ChatMessageCopyWith<_ChatMessage> get copyWith =>
|
||||
__$ChatMessageCopyWithImpl<_ChatMessage>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ChatMessage &&
|
||||
(identical(other.text, text) || other.text == text) &&
|
||||
(identical(other.isUser, isUser) || other.isUser == isUser) &&
|
||||
(identical(other.interrupted, interrupted) ||
|
||||
other.interrupted == interrupted) &&
|
||||
(identical(other.elapsedMs, elapsedMs) ||
|
||||
other.elapsedMs == elapsedMs));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, text, isUser, interrupted, elapsedMs);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ChatMessage(text: $text, isUser: $isUser, interrupted: $interrupted, elapsedMs: $elapsedMs)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ChatMessageCopyWith<$Res>
|
||||
implements $ChatMessageCopyWith<$Res> {
|
||||
factory _$ChatMessageCopyWith(
|
||||
_ChatMessage value,
|
||||
$Res Function(_ChatMessage) _then,
|
||||
) = __$ChatMessageCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({String text, bool isUser, bool interrupted, int? elapsedMs});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ChatMessageCopyWithImpl<$Res> implements _$ChatMessageCopyWith<$Res> {
|
||||
__$ChatMessageCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ChatMessage _self;
|
||||
final $Res Function(_ChatMessage) _then;
|
||||
|
||||
/// Create a copy of ChatMessage
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? text = null,
|
||||
Object? isUser = null,
|
||||
Object? interrupted = null,
|
||||
Object? elapsedMs = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_ChatMessage(
|
||||
text: null == text
|
||||
? _self.text
|
||||
: text // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
isUser: null == isUser
|
||||
? _self.isUser
|
||||
: isUser // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
interrupted: null == interrupted
|
||||
? _self.interrupted
|
||||
: interrupted // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
elapsedMs: freezed == elapsedMs
|
||||
? _self.elapsedMs
|
||||
: elapsedMs // ignore: cast_nullable_to_non_nullable
|
||||
as int?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ChatState {
|
||||
List<ChatMessage> get messages;
|
||||
String get partialResponse;
|
||||
AgentChatActivity get activity;
|
||||
bool get busy;
|
||||
bool get stopping;
|
||||
AgentChatError? get error;
|
||||
ConversationMetadata? get conversation;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$ChatStateCopyWith<ChatState> get copyWith =>
|
||||
_$ChatStateCopyWithImpl<ChatState>(this as ChatState, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as ChatState;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is ChatState &&
|
||||
const DeepCollectionEquality().equals(
|
||||
other.messages,
|
||||
_this.messages,
|
||||
) &&
|
||||
(identical(other.partialResponse, _this.partialResponse) ||
|
||||
other.partialResponse == _this.partialResponse) &&
|
||||
(identical(other.activity, _this.activity) ||
|
||||
other.activity == _this.activity) &&
|
||||
(identical(other.busy, _this.busy) || other.busy == _this.busy) &&
|
||||
(identical(other.stopping, _this.stopping) ||
|
||||
other.stopping == _this.stopping) &&
|
||||
(identical(other.error, _this.error) ||
|
||||
other.error == _this.error) &&
|
||||
(identical(other.conversation, _this.conversation) ||
|
||||
other.conversation == _this.conversation));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as ChatState;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_this.messages),
|
||||
_this.partialResponse,
|
||||
_this.activity,
|
||||
_this.busy,
|
||||
_this.stopping,
|
||||
_this.error,
|
||||
_this.conversation,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as ChatState;
|
||||
return 'ChatState(messages: ${_this.messages}, partialResponse: ${_this.partialResponse}, activity: ${_this.activity}, busy: ${_this.busy}, stopping: ${_this.stopping}, error: ${_this.error}, conversation: ${_this.conversation})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $ChatStateCopyWith<$Res> {
|
||||
factory $ChatStateCopyWith(ChatState value, $Res Function(ChatState) _then) =
|
||||
_$ChatStateCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
});
|
||||
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$ChatStateCopyWithImpl<$Res> implements $ChatStateCopyWith<$Res> {
|
||||
_$ChatStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final ChatState _self;
|
||||
final $Res Function(ChatState) _then;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? messages = null,
|
||||
Object? partialResponse = null,
|
||||
Object? activity = null,
|
||||
Object? busy = null,
|
||||
Object? stopping = null,
|
||||
Object? error = freezed,
|
||||
Object? conversation = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
ChatState(
|
||||
messages: null == messages
|
||||
? _self.messages
|
||||
: messages // ignore: cast_nullable_to_non_nullable
|
||||
as List<ChatMessage>,
|
||||
partialResponse: null == partialResponse
|
||||
? _self.partialResponse
|
||||
: partialResponse // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
activity: null == activity
|
||||
? _self.activity
|
||||
: activity // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatActivity,
|
||||
busy: null == busy
|
||||
? _self.busy
|
||||
: busy // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
stopping: null == stopping
|
||||
? _self.stopping
|
||||
: stopping // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
error: freezed == error
|
||||
? _self.error
|
||||
: error // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatError?,
|
||||
conversation: freezed == conversation
|
||||
? _self.conversation
|
||||
: conversation // ignore: cast_nullable_to_non_nullable
|
||||
as ConversationMetadata?,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation {
|
||||
if (_self.conversation == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) {
|
||||
return _then(_self.copyWith(conversation: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [ChatState].
|
||||
extension ChatStatePatterns on ChatState {
|
||||
/// 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(_ChatState value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() 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(_ChatState value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState():
|
||||
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(_ChatState value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() 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<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() when $default != null:
|
||||
return $default(
|
||||
_that.messages,
|
||||
_that.partialResponse,
|
||||
_that.activity,
|
||||
_that.busy,
|
||||
_that.stopping,
|
||||
_that.error,
|
||||
_that.conversation,
|
||||
);
|
||||
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<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState():
|
||||
return $default(
|
||||
_that.messages,
|
||||
_that.partialResponse,
|
||||
_that.activity,
|
||||
_that.busy,
|
||||
_that.stopping,
|
||||
_that.error,
|
||||
_that.conversation,
|
||||
);
|
||||
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<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ChatState() when $default != null:
|
||||
return $default(
|
||||
_that.messages,
|
||||
_that.partialResponse,
|
||||
_that.activity,
|
||||
_that.busy,
|
||||
_that.stopping,
|
||||
_that.error,
|
||||
_that.conversation,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ChatState implements ChatState {
|
||||
const _ChatState({
|
||||
List<ChatMessage> messages = const [],
|
||||
this.partialResponse = '',
|
||||
this.activity = AgentChatActivity.replying,
|
||||
this.busy = false,
|
||||
this.stopping = false,
|
||||
this.error,
|
||||
this.conversation,
|
||||
}) : _messages = messages;
|
||||
|
||||
final List<ChatMessage> _messages;
|
||||
@override
|
||||
@JsonKey()
|
||||
List<ChatMessage> get messages {
|
||||
if (_messages is EqualUnmodifiableListView) return _messages;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_messages);
|
||||
}
|
||||
|
||||
@override
|
||||
@JsonKey()
|
||||
final String partialResponse;
|
||||
@override
|
||||
@JsonKey()
|
||||
final AgentChatActivity activity;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool busy;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool stopping;
|
||||
@override
|
||||
final AgentChatError? error;
|
||||
@override
|
||||
final ConversationMetadata? conversation;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ChatStateCopyWith<_ChatState> get copyWith =>
|
||||
__$ChatStateCopyWithImpl<_ChatState>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ChatState &&
|
||||
const DeepCollectionEquality().equals(other.messages, _messages) &&
|
||||
(identical(other.partialResponse, partialResponse) ||
|
||||
other.partialResponse == partialResponse) &&
|
||||
(identical(other.activity, activity) ||
|
||||
other.activity == activity) &&
|
||||
(identical(other.busy, busy) || other.busy == busy) &&
|
||||
(identical(other.stopping, stopping) ||
|
||||
other.stopping == stopping) &&
|
||||
(identical(other.error, error) || other.error == error) &&
|
||||
(identical(other.conversation, conversation) ||
|
||||
other.conversation == conversation));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
const DeepCollectionEquality().hash(_messages),
|
||||
partialResponse,
|
||||
activity,
|
||||
busy,
|
||||
stopping,
|
||||
error,
|
||||
conversation,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'ChatState(messages: $messages, partialResponse: $partialResponse, activity: $activity, busy: $busy, stopping: $stopping, error: $error, conversation: $conversation)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ChatStateCopyWith<$Res>
|
||||
implements $ChatStateCopyWith<$Res> {
|
||||
factory _$ChatStateCopyWith(
|
||||
_ChatState value,
|
||||
$Res Function(_ChatState) _then,
|
||||
) = __$ChatStateCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
List<ChatMessage> messages,
|
||||
String partialResponse,
|
||||
AgentChatActivity activity,
|
||||
bool busy,
|
||||
bool stopping,
|
||||
AgentChatError? error,
|
||||
ConversationMetadata? conversation,
|
||||
});
|
||||
|
||||
@override
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ChatStateCopyWithImpl<$Res> implements _$ChatStateCopyWith<$Res> {
|
||||
__$ChatStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ChatState _self;
|
||||
final $Res Function(_ChatState) _then;
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? messages = null,
|
||||
Object? partialResponse = null,
|
||||
Object? activity = null,
|
||||
Object? busy = null,
|
||||
Object? stopping = null,
|
||||
Object? error = freezed,
|
||||
Object? conversation = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_ChatState(
|
||||
messages: null == messages
|
||||
? _self._messages
|
||||
: messages // ignore: cast_nullable_to_non_nullable
|
||||
as List<ChatMessage>,
|
||||
partialResponse: null == partialResponse
|
||||
? _self.partialResponse
|
||||
: partialResponse // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
activity: null == activity
|
||||
? _self.activity
|
||||
: activity // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatActivity,
|
||||
busy: null == busy
|
||||
? _self.busy
|
||||
: busy // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
stopping: null == stopping
|
||||
? _self.stopping
|
||||
: stopping // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
error: freezed == error
|
||||
? _self.error
|
||||
: error // ignore: cast_nullable_to_non_nullable
|
||||
as AgentChatError?,
|
||||
conversation: freezed == conversation
|
||||
? _self.conversation
|
||||
: conversation // ignore: cast_nullable_to_non_nullable
|
||||
as ConversationMetadata?,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of ChatState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$ConversationMetadataCopyWith<$Res>? get conversation {
|
||||
if (_self.conversation == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $ConversationMetadataCopyWith<$Res>(_self.conversation!, (value) {
|
||||
return _then(_self.copyWith(conversation: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,346 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
part 'composer_document.freezed.dart';
|
||||
part 'composer_document.g.dart';
|
||||
|
||||
enum ComposerReferenceKind { media, timeline }
|
||||
|
||||
@freezed
|
||||
abstract class ComposerReference with _$ComposerReference {
|
||||
const ComposerReference._();
|
||||
|
||||
const factory ComposerReference({
|
||||
required ComposerReferenceKind kind,
|
||||
required String projectId,
|
||||
required String id,
|
||||
required String label,
|
||||
}) = _ComposerReference;
|
||||
|
||||
String get display => '@$label';
|
||||
|
||||
factory ComposerReference.fromJson(Map<String, Object?> json) =>
|
||||
_$ComposerReferenceFromJson(json);
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ComposerMark with _$ComposerMark {
|
||||
const ComposerMark._();
|
||||
|
||||
const factory ComposerMark({
|
||||
required int start,
|
||||
required int end,
|
||||
required ComposerReference reference,
|
||||
@Default(true) bool valid,
|
||||
}) = _ComposerMark;
|
||||
|
||||
ComposerMark shift(int delta) =>
|
||||
copyWith(start: start + delta, end: end + delta);
|
||||
|
||||
ComposerMark withValidity(bool value) => copyWith(valid: value);
|
||||
}
|
||||
|
||||
@freezed
|
||||
sealed class ComposerSegment with _$ComposerSegment {
|
||||
const ComposerSegment._();
|
||||
const factory ComposerSegment.text(String value) = ComposerText;
|
||||
const factory ComposerSegment.reference(ComposerReference value) =
|
||||
ComposerReferenceSegment;
|
||||
|
||||
factory ComposerSegment.fromJson(Map<String, Object?> json) =>
|
||||
_$ComposerSegmentFromJson(json);
|
||||
|
||||
String get displayText => switch (this) {
|
||||
ComposerText(:final value) => value,
|
||||
ComposerReferenceSegment(:final value) => value.label,
|
||||
};
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class _ComposerSnapshot with _$ComposerSnapshot {
|
||||
const factory _ComposerSnapshot(
|
||||
TextEditingValue value,
|
||||
List<ComposerMark> marks,
|
||||
) = _ComposerHistorySnapshot;
|
||||
}
|
||||
|
||||
/// Keeps Flutter's text offsets and stable resource references in one draft.
|
||||
class ComposerDocumentController extends TextEditingController {
|
||||
ComposerDocumentController({super.text}) {
|
||||
_history.add(_ComposerSnapshot(value, const []));
|
||||
}
|
||||
|
||||
List<ComposerMark> _marks = [];
|
||||
final List<_ComposerSnapshot> _history = [];
|
||||
int _historyIndex = 0;
|
||||
bool _applying = false;
|
||||
|
||||
List<ComposerMark> get marks => List.unmodifiable(_marks);
|
||||
bool get hasInvalidReferences => _marks.any((mark) => !mark.valid);
|
||||
|
||||
void _record() {
|
||||
if (_historyIndex + 1 < _history.length) {
|
||||
_history.removeRange(_historyIndex + 1, _history.length);
|
||||
}
|
||||
_history.add(_ComposerSnapshot(value, List.unmodifiable(_marks)));
|
||||
_historyIndex = _history.length - 1;
|
||||
}
|
||||
|
||||
void _apply(
|
||||
TextEditingValue next,
|
||||
List<ComposerMark> marks, {
|
||||
bool record = true,
|
||||
}) {
|
||||
_applying = true;
|
||||
_marks = List.of(marks);
|
||||
super.value = next;
|
||||
_applying = false;
|
||||
if (record) _record();
|
||||
}
|
||||
|
||||
@override
|
||||
set value(TextEditingValue next) {
|
||||
if (_applying) {
|
||||
super.value = next;
|
||||
return;
|
||||
}
|
||||
final old = super.value;
|
||||
if (old.text == next.text) {
|
||||
final selection = next.selection;
|
||||
if (selection.isCollapsed) {
|
||||
for (final mark in _marks) {
|
||||
if (selection.baseOffset > mark.start &&
|
||||
selection.baseOffset < mark.end) {
|
||||
final left = selection.baseOffset - mark.start;
|
||||
final right = mark.end - selection.baseOffset;
|
||||
final previous = old.selection;
|
||||
final boundary = previous.isValid && previous.isCollapsed
|
||||
? previous.extentOffset == mark.end &&
|
||||
selection.baseOffset == mark.end - 1
|
||||
? mark.start
|
||||
: previous.extentOffset == mark.start &&
|
||||
selection.baseOffset == mark.start + 1
|
||||
? mark.end
|
||||
: null
|
||||
: null;
|
||||
super.value = next.copyWith(
|
||||
selection: TextSelection.collapsed(
|
||||
offset: boundary ?? (left < right ? mark.start : mark.end),
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else if (selection.isValid) {
|
||||
var start = selection.start;
|
||||
var end = selection.end;
|
||||
for (final mark in _marks) {
|
||||
if (start < mark.end && end > mark.start) {
|
||||
if (start > mark.start) start = mark.start;
|
||||
if (end < mark.end) end = mark.end;
|
||||
}
|
||||
}
|
||||
if (start != selection.start || end != selection.end) {
|
||||
super.value = next.copyWith(
|
||||
selection: TextSelection(baseOffset: start, extentOffset: end),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
super.value = next;
|
||||
return;
|
||||
}
|
||||
|
||||
var prefix = 0;
|
||||
while (prefix < old.text.length &&
|
||||
prefix < next.text.length &&
|
||||
old.text.codeUnitAt(prefix) == next.text.codeUnitAt(prefix)) {
|
||||
prefix++;
|
||||
}
|
||||
var suffix = 0;
|
||||
while (suffix < old.text.length - prefix &&
|
||||
suffix < next.text.length - prefix &&
|
||||
old.text.codeUnitAt(old.text.length - suffix - 1) ==
|
||||
next.text.codeUnitAt(next.text.length - suffix - 1)) {
|
||||
suffix++;
|
||||
}
|
||||
var start = prefix;
|
||||
var end = old.text.length - suffix;
|
||||
final inserted = next.text.substring(prefix, next.text.length - suffix);
|
||||
final insertion = start == end;
|
||||
var touchedMark = false;
|
||||
if (insertion) {
|
||||
for (final mark in _marks) {
|
||||
if (start > mark.start && start < mark.end) {
|
||||
touchedMark = true;
|
||||
start = mark.end;
|
||||
end = mark.end;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for (final mark in _marks) {
|
||||
if (start < mark.end && end > mark.start) {
|
||||
touchedMark = true;
|
||||
if (mark.start < start) start = mark.start;
|
||||
if (mark.end > end) end = mark.end;
|
||||
}
|
||||
}
|
||||
}
|
||||
final changed = old.text.replaceRange(start, end, inserted);
|
||||
final delta = inserted.length - (end - start);
|
||||
final marks = [
|
||||
for (final mark in _marks)
|
||||
if (mark.end <= start)
|
||||
mark
|
||||
else if (mark.start >= end)
|
||||
mark.shift(delta),
|
||||
];
|
||||
_apply(
|
||||
next.copyWith(
|
||||
text: changed,
|
||||
selection: touchedMark
|
||||
? TextSelection.collapsed(offset: start + inserted.length)
|
||||
: next.selection,
|
||||
composing: touchedMark ? TextRange.empty : next.composing,
|
||||
),
|
||||
marks,
|
||||
);
|
||||
}
|
||||
|
||||
void insertReference(int start, int end, ComposerReference reference) {
|
||||
final current = value;
|
||||
if (start < 0 || end < start || end > current.text.length) return;
|
||||
final display = reference.display;
|
||||
final nextCharacter = end < current.text.length
|
||||
? current.text.substring(end, end + 1)
|
||||
: '';
|
||||
final hasFollowingWhitespace = RegExp(r'^\s$').hasMatch(nextCharacter);
|
||||
final inserted = '$display${hasFollowingWhitespace ? '' : ' '}';
|
||||
final delta = inserted.length - (end - start);
|
||||
final marks = [
|
||||
for (final mark in _marks)
|
||||
if (mark.end <= start)
|
||||
mark
|
||||
else if (mark.start >= end)
|
||||
mark.shift(delta),
|
||||
ComposerMark(
|
||||
start: start,
|
||||
end: start + display.length,
|
||||
reference: reference,
|
||||
),
|
||||
]..sort((a, b) => a.start.compareTo(b.start));
|
||||
_apply(
|
||||
current.copyWith(
|
||||
text: current.text.replaceRange(start, end, inserted),
|
||||
selection: TextSelection.collapsed(
|
||||
offset:
|
||||
start +
|
||||
inserted.length +
|
||||
(nextCharacter == ' ' || nextCharacter == '\t' ? 1 : 0),
|
||||
),
|
||||
composing: TextRange.empty,
|
||||
),
|
||||
marks,
|
||||
);
|
||||
}
|
||||
|
||||
void updateValidity(bool Function(ComposerReference reference) isValid) {
|
||||
final updated = [
|
||||
for (final mark in _marks) mark.withValidity(isValid(mark.reference)),
|
||||
];
|
||||
if (updated.asMap().entries.every(
|
||||
(entry) => entry.value.valid == _marks[entry.key].valid,
|
||||
)) {
|
||||
return;
|
||||
}
|
||||
_marks = updated;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
List<ComposerSegment> get segments {
|
||||
final result = <ComposerSegment>[];
|
||||
var offset = 0;
|
||||
for (final mark in _marks) {
|
||||
if (mark.start > offset) {
|
||||
result.add(ComposerSegment.text(text.substring(offset, mark.start)));
|
||||
}
|
||||
result.add(ComposerSegment.reference(mark.reference));
|
||||
offset = mark.end;
|
||||
}
|
||||
if (offset < text.length) {
|
||||
result.add(ComposerSegment.text(text.substring(offset)));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
void clearDocument() => _apply(const TextEditingValue(), const []);
|
||||
|
||||
void undoDocument() {
|
||||
if (_historyIndex == 0) return;
|
||||
_historyIndex--;
|
||||
final snapshot = _history[_historyIndex];
|
||||
_apply(snapshot.value, snapshot.marks, record: false);
|
||||
}
|
||||
|
||||
void redoDocument() {
|
||||
if (_historyIndex >= _history.length - 1) return;
|
||||
_historyIndex++;
|
||||
final snapshot = _history[_historyIndex];
|
||||
_apply(snapshot.value, snapshot.marks, record: false);
|
||||
}
|
||||
|
||||
@override
|
||||
TextSpan buildTextSpan({
|
||||
required BuildContext context,
|
||||
TextStyle? style,
|
||||
required bool withComposing,
|
||||
}) {
|
||||
if (_marks.isEmpty) {
|
||||
return super.buildTextSpan(
|
||||
context: context,
|
||||
style: style,
|
||||
withComposing: withComposing,
|
||||
);
|
||||
}
|
||||
final theme = Theme.of(context);
|
||||
final children = <InlineSpan>[];
|
||||
var offset = 0;
|
||||
for (final mark in _marks) {
|
||||
if (mark.start > offset) {
|
||||
children.add(TextSpan(text: text.substring(offset, mark.start)));
|
||||
}
|
||||
final color = mark.valid
|
||||
? AppTheme.composerReferenceColor(context)
|
||||
: theme.colorScheme.error;
|
||||
children.add(
|
||||
WidgetSpan(
|
||||
alignment: PlaceholderAlignment.middle,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 4),
|
||||
child: Icon(
|
||||
mark.reference.kind == ComposerReferenceKind.timeline
|
||||
? Icons.view_timeline_outlined
|
||||
: Icons.attach_file,
|
||||
size: 14,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
children.add(
|
||||
TextSpan(
|
||||
text: text.substring(mark.start + 1, mark.end),
|
||||
style: TextStyle(color: color, fontWeight: FontWeight.w600),
|
||||
),
|
||||
);
|
||||
offset = mark.end;
|
||||
}
|
||||
if (offset < text.length) {
|
||||
children.add(TextSpan(text: text.substring(offset)));
|
||||
}
|
||||
return TextSpan(style: style, children: children);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,50 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'composer_document.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
_ComposerReference _$ComposerReferenceFromJson(Map<String, dynamic> json) =>
|
||||
_ComposerReference(
|
||||
kind: $enumDecode(_$ComposerReferenceKindEnumMap, json['kind']),
|
||||
projectId: json['projectId'] as String,
|
||||
id: json['id'] as String,
|
||||
label: json['label'] as String,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ComposerReferenceToJson(_ComposerReference instance) =>
|
||||
<String, dynamic>{
|
||||
'kind': _$ComposerReferenceKindEnumMap[instance.kind]!,
|
||||
'projectId': instance.projectId,
|
||||
'id': instance.id,
|
||||
'label': instance.label,
|
||||
};
|
||||
|
||||
const _$ComposerReferenceKindEnumMap = {
|
||||
ComposerReferenceKind.media: 'media',
|
||||
ComposerReferenceKind.timeline: 'timeline',
|
||||
};
|
||||
|
||||
ComposerText _$ComposerTextFromJson(Map<String, dynamic> json) => ComposerText(
|
||||
json['value'] as String,
|
||||
$type: json['runtimeType'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ComposerTextToJson(ComposerText instance) =>
|
||||
<String, dynamic>{'value': instance.value, 'runtimeType': instance.$type};
|
||||
|
||||
ComposerReferenceSegment _$ComposerReferenceSegmentFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => ComposerReferenceSegment(
|
||||
ComposerReference.fromJson(json['value'] as Map<String, dynamic>),
|
||||
$type: json['runtimeType'] as String?,
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$ComposerReferenceSegmentToJson(
|
||||
ComposerReferenceSegment instance,
|
||||
) => <String, dynamic>{
|
||||
'value': instance.value.toJson(),
|
||||
'runtimeType': instance.$type,
|
||||
};
|
||||
@@ -0,0 +1,214 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../shared/layout/composer_layout.dart';
|
||||
import '../../shared/theme/composer_style.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
|
||||
class ComposerProjectSelector extends StatefulWidget {
|
||||
const ComposerProjectSelector({
|
||||
super.key,
|
||||
required this.projects,
|
||||
required this.selected,
|
||||
required this.busy,
|
||||
required this.onSelect,
|
||||
required this.onCreate,
|
||||
required this.backgroundColor,
|
||||
});
|
||||
|
||||
final List<RecentProject> projects;
|
||||
final RecentProject? selected;
|
||||
final bool busy;
|
||||
final ValueChanged<RecentProject> onSelect;
|
||||
final VoidCallback? onCreate;
|
||||
final Color backgroundColor;
|
||||
|
||||
@override
|
||||
State<ComposerProjectSelector> createState() =>
|
||||
_ComposerProjectSelectorState();
|
||||
}
|
||||
|
||||
class _ComposerProjectSelectorState extends State<ComposerProjectSelector> {
|
||||
final _menu = MenuController();
|
||||
final _search = TextEditingController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_search.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Widget _item({
|
||||
required Key key,
|
||||
required String label,
|
||||
required IconData icon,
|
||||
bool? selected,
|
||||
bool secondary = false,
|
||||
VoidCallback? onPressed,
|
||||
}) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
return MenuItemButton(
|
||||
key: key,
|
||||
onPressed: onPressed,
|
||||
style: AppComposerStyle.projectMenuItem(context, secondary: secondary),
|
||||
child: Semantics(
|
||||
selected: selected,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
color: onPressed == null
|
||||
? Theme.of(context).disabledColor
|
||||
: colors.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: ComposerLayout.menuIconGap),
|
||||
Expanded(
|
||||
child: Text(label, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
if (selected == true) ...[
|
||||
const SizedBox(width: ComposerLayout.menuIconGap),
|
||||
Icon(
|
||||
Icons.check,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _separator() => const Padding(
|
||||
padding: AppComposerStyle.menuSeparatorPadding,
|
||||
child: Divider(
|
||||
height: 1,
|
||||
thickness: AppComposerStyle.menuSeparatorThickness,
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final query = _search.text.trim().toLowerCase();
|
||||
final projects = widget.projects
|
||||
.where((project) => project.name.toLowerCase().contains(query))
|
||||
.toList();
|
||||
return Material(
|
||||
key: const Key('composer-project-bar'),
|
||||
color: widget.backgroundColor,
|
||||
borderRadius: const BorderRadius.vertical(
|
||||
top: Radius.circular(ComposerLayout.utilityRadius),
|
||||
),
|
||||
child: Padding(
|
||||
padding: AppComposerStyle.utilityPadding,
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: MenuAnchor(
|
||||
controller: _menu,
|
||||
consumeOutsideTap: false,
|
||||
onClose: () => setState(_search.clear),
|
||||
style: AppComposerStyle.projectMenu(context),
|
||||
menuChildren: [
|
||||
SizedBox(
|
||||
width: ComposerLayout.menuContentWidth,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
SizedBox(
|
||||
height: ComposerLayout.menuRowHeight,
|
||||
child: TextField(
|
||||
key: const Key('composer-project-search'),
|
||||
controller: _search,
|
||||
autofocus: true,
|
||||
style: AppTheme.composerTextStyle(context),
|
||||
onChanged: (_) => setState(() {}),
|
||||
decoration: AppComposerStyle.projectSearchDecoration(
|
||||
context,
|
||||
hintText: context.l10n.searchProjects,
|
||||
),
|
||||
),
|
||||
),
|
||||
_separator(),
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
maxHeight: ComposerLayout.menuListMaxHeight,
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (projects.isEmpty)
|
||||
Padding(
|
||||
padding: AppComposerStyle.menuEmptyPadding,
|
||||
child: Text(
|
||||
query.isEmpty
|
||||
? context.l10n.projectsNone
|
||||
: context.l10n.noMatchingProjects,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
for (final project in projects)
|
||||
_item(
|
||||
key: ValueKey('composer-project-${project.id}'),
|
||||
label: project.name,
|
||||
icon: Icons.folder_outlined,
|
||||
selected: project.id == widget.selected?.id,
|
||||
onPressed:
|
||||
widget.busy || !project.availability.canOpen
|
||||
? null
|
||||
: () {
|
||||
_menu.close();
|
||||
widget.onSelect(project);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
_separator(),
|
||||
_item(
|
||||
key: const Key('composer-new-project'),
|
||||
secondary: true,
|
||||
label: context.l10n.newProject,
|
||||
icon: Icons.add,
|
||||
onPressed: widget.busy || widget.onCreate == null
|
||||
? null
|
||||
: () {
|
||||
_menu.close();
|
||||
widget.onCreate!();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
builder: (context, controller, _) => TextButton.icon(
|
||||
key: const Key('composer-project-trigger'),
|
||||
onPressed: widget.busy
|
||||
? null
|
||||
: () => controller.isOpen
|
||||
? controller.close()
|
||||
: controller.open(),
|
||||
style: AppComposerStyle.projectTrigger(context),
|
||||
icon: const Icon(
|
||||
Icons.folder_outlined,
|
||||
size: ComposerLayout.menuIconSize,
|
||||
),
|
||||
label: Text(
|
||||
widget.selected?.name ?? context.l10n.selectProject,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import '../../workspace/project_state.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
/// Checks draft references against the project currently open in the composer.
|
||||
final class ComposerReferenceValidator {
|
||||
const ComposerReferenceValidator({
|
||||
required this.workspace,
|
||||
required this.projectId,
|
||||
});
|
||||
|
||||
final ProjectState? workspace;
|
||||
final String? projectId;
|
||||
|
||||
bool isValid(ComposerReference reference) {
|
||||
if (projectId != reference.projectId ||
|
||||
workspace?.activeProject?.id != reference.projectId) {
|
||||
return false;
|
||||
}
|
||||
return switch (reference.kind) {
|
||||
ComposerReferenceKind.media => workspace!.assets.any(
|
||||
(asset) => asset.id == reference.id,
|
||||
),
|
||||
ComposerReferenceKind.timeline => workspace!.timelines.any(
|
||||
(timeline) => timeline.id == reference.id,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
void validate(ComposerDocumentController document) {
|
||||
document.updateValidity(isValid);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import 'composer_document.dart';
|
||||
import 'composer_suggestions.dart';
|
||||
|
||||
part 'composer_suggestion_surface.freezed.dart';
|
||||
|
||||
/// Owns suggestion focus, keyboard navigation, selection and the anchored menu.
|
||||
/// The caller supplies the composer body and the action used when Enter sends.
|
||||
class ComposerSuggestionSurface extends StatefulWidget {
|
||||
const ComposerSuggestionSurface({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.width,
|
||||
required this.projectId,
|
||||
required this.assets,
|
||||
required this.timelines,
|
||||
required this.onSend,
|
||||
required this.builder,
|
||||
});
|
||||
|
||||
final ComposerDocumentController controller;
|
||||
final double width;
|
||||
final String? projectId;
|
||||
final Iterable<AssetDocument> assets;
|
||||
final Iterable<TimelineSummary> timelines;
|
||||
final VoidCallback onSend;
|
||||
final Widget Function(BuildContext context, FocusNode inputFocus) builder;
|
||||
|
||||
@override
|
||||
State<ComposerSuggestionSurface> createState() =>
|
||||
_ComposerSuggestionSurfaceState();
|
||||
}
|
||||
|
||||
class _ComposerSuggestionSurfaceState extends State<ComposerSuggestionSurface> {
|
||||
final _focus = FocusNode();
|
||||
final _link = LayerLink();
|
||||
final _portal = OverlayPortalController();
|
||||
final _anchorKey = GlobalKey();
|
||||
final _tapGroup = Object();
|
||||
final _menuScrollController = ScrollController(keepScrollOffset: false);
|
||||
ComposerTriggerQuery? _trigger;
|
||||
int _selected = 0;
|
||||
ComposerTriggerQuery? _suppressedQuery;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.controller.addListener(_onDocumentChanged);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ComposerSuggestionSurface oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
oldWidget.controller.removeListener(_onDocumentChanged);
|
||||
widget.controller.addListener(_onDocumentChanged);
|
||||
_onDocumentChanged();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.controller.removeListener(_onDocumentChanged);
|
||||
_menuScrollController.dispose();
|
||||
_focus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _onDocumentChanged() {
|
||||
final candidate = findComposerTrigger(
|
||||
widget.controller.value,
|
||||
widget.controller.marks,
|
||||
);
|
||||
final suppressed = _suppressedQuery;
|
||||
final stillSuppressed =
|
||||
candidate != null &&
|
||||
suppressed != null &&
|
||||
candidate.start == suppressed.start &&
|
||||
candidate.trigger == suppressed.trigger &&
|
||||
candidate.query == suppressed.query;
|
||||
if (!stillSuppressed) _suppressedQuery = null;
|
||||
final next = stillSuppressed ? null : candidate;
|
||||
if (next?.start == _trigger?.start &&
|
||||
next?.query == _trigger?.query &&
|
||||
next?.trigger == _trigger?.trigger) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_trigger = next;
|
||||
_selected = 0;
|
||||
});
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
if (_menuScrollController.hasClients) _menuScrollController.jumpTo(0);
|
||||
if (_trigger == null) {
|
||||
if (_portal.isShowing) _portal.hide();
|
||||
} else if (!_portal.isShowing) {
|
||||
_portal.show();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _dismiss({bool suppress = false}) {
|
||||
if (suppress) _suppressedQuery = _trigger;
|
||||
setState(() => _trigger = null);
|
||||
if (_portal.isShowing) _portal.hide();
|
||||
}
|
||||
|
||||
List<ComposerOption> _options(ComposerTriggerQuery query) =>
|
||||
filterComposerOptions(
|
||||
ComposerOptionCatalog.forTrigger(
|
||||
query.trigger,
|
||||
l10n: AppLocalizations.of(context)!,
|
||||
projectId: widget.projectId,
|
||||
assets: widget.assets,
|
||||
timelines: widget.timelines,
|
||||
),
|
||||
query.query,
|
||||
);
|
||||
|
||||
void _select(ComposerOption option) {
|
||||
final query = _trigger;
|
||||
if (query == null) return;
|
||||
_dismiss();
|
||||
switch (option) {
|
||||
case ComposerReferenceOption(:final reference):
|
||||
widget.controller.insertReference(query.start, query.end, reference);
|
||||
case ComposerTextOption(:final text):
|
||||
widget.controller.value = widget.controller.value.copyWith(
|
||||
text: widget.controller.text.replaceRange(
|
||||
query.start,
|
||||
query.end,
|
||||
text,
|
||||
),
|
||||
selection: TextSelection.collapsed(offset: query.start + text.length),
|
||||
);
|
||||
case ComposerPickerOption(:final onInvoke):
|
||||
case ComposerInvokeOption(:final onInvoke):
|
||||
onInvoke();
|
||||
}
|
||||
_focus.requestFocus();
|
||||
}
|
||||
|
||||
void _selectCurrent() {
|
||||
final query = _trigger;
|
||||
if (query == null) return;
|
||||
final options = _options(query);
|
||||
if (options.isNotEmpty) {
|
||||
_select(options[_selected.clamp(0, options.length - 1)]);
|
||||
}
|
||||
}
|
||||
|
||||
void _move(int delta) {
|
||||
final query = _trigger;
|
||||
if (query == null) return;
|
||||
final options = _options(query);
|
||||
final count = options.length;
|
||||
if (count > 0) {
|
||||
setState(() => _selected = (_selected + delta + count) % count);
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted || !_menuScrollController.hasClients) return;
|
||||
final currentQuery = _trigger;
|
||||
if (currentQuery == null) return;
|
||||
final rows = _rows(_options(currentQuery));
|
||||
var top = AppMenuMetrics.gutter;
|
||||
for (final row in rows) {
|
||||
if (row case _SuggestionOption(optionIndex: final index)
|
||||
when index == _selected) {
|
||||
final position = _menuScrollController.position;
|
||||
final bottom = top + row.height;
|
||||
final visibleTop = position.pixels;
|
||||
final visibleBottom = visibleTop + position.viewportDimension;
|
||||
final target = top < visibleTop
|
||||
? top - 4
|
||||
: bottom > visibleBottom
|
||||
? bottom - position.viewportDimension + 4
|
||||
: null;
|
||||
if (target != null) {
|
||||
_menuScrollController.animateTo(
|
||||
target.clamp(
|
||||
position.minScrollExtent,
|
||||
position.maxScrollExtent,
|
||||
),
|
||||
duration: const Duration(milliseconds: 120),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
top += row.height;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<_SuggestionRow> _rows(List<ComposerOption> options) {
|
||||
final rows = <_SuggestionRow>[];
|
||||
for (final group in ComposerOptionGroup.values) {
|
||||
final grouped = options.indexed.where((entry) => entry.$2.group == group);
|
||||
if (grouped.isEmpty) continue;
|
||||
rows.add(_SuggestionRow.header(group, rows.isEmpty ? 28 : 36));
|
||||
for (final (index, option) in grouped) {
|
||||
rows.add(_SuggestionRow.option(option, index));
|
||||
}
|
||||
}
|
||||
for (final (index, option) in options.indexed) {
|
||||
if (option.group == null) {
|
||||
rows.add(_SuggestionRow.option(option, index));
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
Widget _menu(BuildContext context) {
|
||||
final query = _trigger;
|
||||
if (query == null) return const SizedBox.shrink();
|
||||
final options = _options(query);
|
||||
final rows = _rows(options);
|
||||
final anchor = _anchorKey.currentContext?.findRenderObject();
|
||||
final availableAbove = anchor is RenderBox
|
||||
? anchor.localToGlobal(Offset.zero).dy - 16
|
||||
: MediaQuery.sizeOf(context).height / 2;
|
||||
final placeBelow = availableAbove < 100;
|
||||
final maxHeight = placeBelow
|
||||
? (MediaQuery.sizeOf(context).height - availableAbove - 120).clamp(
|
||||
72.0,
|
||||
320.0,
|
||||
)
|
||||
: availableAbove.clamp(72.0, 320.0);
|
||||
final theme = Theme.of(context);
|
||||
return Stack(
|
||||
children: [
|
||||
CompositedTransformFollower(
|
||||
link: _link,
|
||||
showWhenUnlinked: false,
|
||||
targetAnchor: placeBelow ? Alignment.bottomLeft : Alignment.topLeft,
|
||||
followerAnchor: placeBelow ? Alignment.topLeft : Alignment.bottomLeft,
|
||||
offset: Offset(0, placeBelow ? 4 : -4),
|
||||
child: TapRegion(
|
||||
groupId: _tapGroup,
|
||||
child: Material(
|
||||
color: AppTheme.popoverBackground(context),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(AppMenuMetrics.radius),
|
||||
side: BorderSide(
|
||||
color: theme.colorScheme.outlineVariant,
|
||||
width: AppMenuMetrics.borderWidth,
|
||||
),
|
||||
),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: SizedBox(
|
||||
key: const Key('agent-composer-suggestions'),
|
||||
width: widget.width,
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: maxHeight),
|
||||
child: options.isEmpty
|
||||
? Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Text(
|
||||
AppLocalizations.of(context)!.noAvailableOptions,
|
||||
),
|
||||
)
|
||||
: ListView.builder(
|
||||
key: const Key('agent-composer-suggestion-list'),
|
||||
controller: _menuScrollController,
|
||||
shrinkWrap: true,
|
||||
padding: const EdgeInsets.all(AppMenuMetrics.gutter),
|
||||
itemCount: rows.length,
|
||||
itemBuilder: (context, index) {
|
||||
final row = rows[index];
|
||||
if (row case _SuggestionHeader(:final group)) {
|
||||
final labels = AppLocalizations.of(context)!;
|
||||
return Container(
|
||||
key: Key(
|
||||
'agent-suggestion-group-${group.name}',
|
||||
),
|
||||
height: row.height,
|
||||
alignment: Alignment.centerLeft,
|
||||
padding: EdgeInsets.fromLTRB(
|
||||
10,
|
||||
index == 0 ? 4 : 12,
|
||||
10,
|
||||
5,
|
||||
),
|
||||
child: Text(
|
||||
switch (group) {
|
||||
ComposerOptionGroup.media =>
|
||||
labels.materials,
|
||||
ComposerOptionGroup.timeline =>
|
||||
labels.timelines,
|
||||
},
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
final _SuggestionOption(:option, :optionIndex) =
|
||||
row as _SuggestionOption;
|
||||
final selected = optionIndex == _selected;
|
||||
return InkWell(
|
||||
key: Key(
|
||||
'agent-suggestion-${option is ComposerReferenceOption ? option.reference.kind.name : option.trigger}-${option is ComposerReferenceOption ? option.reference.id : index}',
|
||||
),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppMenuMetrics.itemRadius,
|
||||
),
|
||||
onTap: () => _select(option),
|
||||
child: Container(
|
||||
height: 40,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: selected
|
||||
? theme.colorScheme.onSurface.withValues(
|
||||
alpha: .1,
|
||||
)
|
||||
: null,
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppMenuMetrics.itemRadius,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(option.icon, size: 15),
|
||||
const SizedBox(
|
||||
width: AppMenuMetrics.iconGap,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
option.title,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
if (option.group == null &&
|
||||
option.subtitle.isNotEmpty) ...[
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
option.subtitle,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final content = widget.builder(context, _focus);
|
||||
return OverlayPortal(
|
||||
controller: _portal,
|
||||
overlayChildBuilder: _menu,
|
||||
child: TapRegion(
|
||||
groupId: _tapGroup,
|
||||
onTapOutside: (_) {
|
||||
if (_trigger != null) _dismiss(suppress: true);
|
||||
},
|
||||
child: CompositedTransformTarget(
|
||||
key: _anchorKey,
|
||||
link: _link,
|
||||
child: ValueListenableBuilder<TextEditingValue>(
|
||||
valueListenable: widget.controller,
|
||||
child: content,
|
||||
builder: (context, value, child) {
|
||||
final composing =
|
||||
value.composing.isValid && !value.composing.isCollapsed;
|
||||
final enter = composing
|
||||
? const DoNothingAndStopPropagationIntent()
|
||||
: _trigger != null
|
||||
? const _SelectSuggestionIntent()
|
||||
: const _SendComposerIntent();
|
||||
return Shortcuts(
|
||||
shortcuts: {
|
||||
const SingleActivator(LogicalKeyboardKey.enter): enter,
|
||||
const SingleActivator(LogicalKeyboardKey.numpadEnter): enter,
|
||||
if (_trigger != null) ...{
|
||||
const SingleActivator(LogicalKeyboardKey.arrowDown):
|
||||
const _MoveSuggestionIntent(1),
|
||||
const SingleActivator(LogicalKeyboardKey.arrowUp):
|
||||
const _MoveSuggestionIntent(-1),
|
||||
const SingleActivator(LogicalKeyboardKey.escape):
|
||||
const _DismissSuggestionIntent(),
|
||||
},
|
||||
const SingleActivator(LogicalKeyboardKey.keyZ, meta: true):
|
||||
const _UndoComposerIntent(),
|
||||
const SingleActivator(
|
||||
LogicalKeyboardKey.keyZ,
|
||||
meta: true,
|
||||
shift: true,
|
||||
): const _RedoComposerIntent(),
|
||||
},
|
||||
child: Actions(
|
||||
actions: {
|
||||
_SendComposerIntent: CallbackAction<_SendComposerIntent>(
|
||||
onInvoke: (_) {
|
||||
widget.onSend();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_SelectSuggestionIntent:
|
||||
CallbackAction<_SelectSuggestionIntent>(
|
||||
onInvoke: (_) {
|
||||
_selectCurrent();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_MoveSuggestionIntent:
|
||||
CallbackAction<_MoveSuggestionIntent>(
|
||||
onInvoke: (intent) {
|
||||
_move(intent.delta);
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_DismissSuggestionIntent:
|
||||
CallbackAction<_DismissSuggestionIntent>(
|
||||
onInvoke: (_) {
|
||||
_dismiss(suppress: true);
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_UndoComposerIntent: CallbackAction<_UndoComposerIntent>(
|
||||
onInvoke: (_) {
|
||||
widget.controller.undoDocument();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
_RedoComposerIntent: CallbackAction<_RedoComposerIntent>(
|
||||
onInvoke: (_) {
|
||||
widget.controller.redoDocument();
|
||||
return null;
|
||||
},
|
||||
),
|
||||
},
|
||||
child: child!,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SendComposerIntent extends Intent {
|
||||
const _SendComposerIntent();
|
||||
}
|
||||
|
||||
class _SelectSuggestionIntent extends Intent {
|
||||
const _SelectSuggestionIntent();
|
||||
}
|
||||
|
||||
class _MoveSuggestionIntent extends Intent {
|
||||
const _MoveSuggestionIntent(this.delta);
|
||||
final int delta;
|
||||
}
|
||||
|
||||
class _DismissSuggestionIntent extends Intent {
|
||||
const _DismissSuggestionIntent();
|
||||
}
|
||||
|
||||
class _UndoComposerIntent extends Intent {
|
||||
const _UndoComposerIntent();
|
||||
}
|
||||
|
||||
class _RedoComposerIntent extends Intent {
|
||||
const _RedoComposerIntent();
|
||||
}
|
||||
|
||||
@freezed
|
||||
sealed class _SuggestionRow with _$SuggestionRow {
|
||||
const _SuggestionRow._();
|
||||
const factory _SuggestionRow.header(
|
||||
ComposerOptionGroup group,
|
||||
double height,
|
||||
) = _SuggestionHeader;
|
||||
const factory _SuggestionRow.option(ComposerOption option, int optionIndex) =
|
||||
_SuggestionOption;
|
||||
double get height => switch (this) {
|
||||
_SuggestionHeader(:final height) => height,
|
||||
_SuggestionOption() => 40,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
// 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 'composer_suggestion_surface.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$SuggestionRow {
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is _SuggestionRow);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_SuggestionRow()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$SuggestionRowCopyWith<$Res> {
|
||||
_$SuggestionRowCopyWith(_SuggestionRow _, $Res Function(_SuggestionRow) __);
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [_SuggestionRow].
|
||||
extension _SuggestionRowPatterns on _SuggestionRow {
|
||||
/// 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(_SuggestionHeader value)? header,
|
||||
TResult Function(_SuggestionOption value)? option,
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_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(_SuggestionHeader value) header,
|
||||
required TResult Function(_SuggestionOption value) option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader():
|
||||
return header(_that);
|
||||
case _SuggestionOption():
|
||||
return option(_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(_SuggestionHeader value)? header,
|
||||
TResult? Function(_SuggestionOption value)? option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_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(ComposerOptionGroup group, double height)? header,
|
||||
TResult Function(ComposerOption option, int optionIndex)? option,
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that.group, _that.height);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_that.option, _that.optionIndex);
|
||||
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(ComposerOptionGroup group, double height) header,
|
||||
required TResult Function(ComposerOption option, int optionIndex) option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader():
|
||||
return header(_that.group, _that.height);
|
||||
case _SuggestionOption():
|
||||
return option(_that.option, _that.optionIndex);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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(ComposerOptionGroup group, double height)? header,
|
||||
TResult? Function(ComposerOption option, int optionIndex)? option,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SuggestionHeader() when header != null:
|
||||
return header(_that.group, _that.height);
|
||||
case _SuggestionOption() when option != null:
|
||||
return option(_that.option, _that.optionIndex);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _SuggestionHeader extends _SuggestionRow {
|
||||
const _SuggestionHeader(this.group, this.height) : super._();
|
||||
|
||||
final ComposerOptionGroup group;
|
||||
final double height;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$SuggestionHeaderCopyWith<_SuggestionHeader> get copyWith =>
|
||||
__$SuggestionHeaderCopyWithImpl<_SuggestionHeader>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _SuggestionHeader &&
|
||||
(identical(other.group, group) || other.group == group) &&
|
||||
(identical(other.height, height) || other.height == height));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, group, height);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_SuggestionRow.header(group: $group, height: $height)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$SuggestionHeaderCopyWith<$Res>
|
||||
implements _$SuggestionRowCopyWith<$Res> {
|
||||
factory _$SuggestionHeaderCopyWith(
|
||||
_SuggestionHeader value,
|
||||
$Res Function(_SuggestionHeader) _then,
|
||||
) = __$SuggestionHeaderCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({ComposerOptionGroup group, double height});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$SuggestionHeaderCopyWithImpl<$Res>
|
||||
implements _$SuggestionHeaderCopyWith<$Res> {
|
||||
__$SuggestionHeaderCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _SuggestionHeader _self;
|
||||
final $Res Function(_SuggestionHeader) _then;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? group = null, Object? height = null}) {
|
||||
return _then(
|
||||
_SuggestionHeader(
|
||||
null == group
|
||||
? _self.group
|
||||
: group // ignore: cast_nullable_to_non_nullable
|
||||
as ComposerOptionGroup,
|
||||
null == height
|
||||
? _self.height
|
||||
: height // ignore: cast_nullable_to_non_nullable
|
||||
as double,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _SuggestionOption extends _SuggestionRow {
|
||||
const _SuggestionOption(this.option, this.optionIndex) : super._();
|
||||
|
||||
final ComposerOption option;
|
||||
final int optionIndex;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$SuggestionOptionCopyWith<_SuggestionOption> get copyWith =>
|
||||
__$SuggestionOptionCopyWithImpl<_SuggestionOption>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _SuggestionOption &&
|
||||
(identical(other.option, option) || other.option == option) &&
|
||||
(identical(other.optionIndex, optionIndex) ||
|
||||
other.optionIndex == optionIndex));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, option, optionIndex);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_SuggestionRow.option(option: $option, optionIndex: $optionIndex)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$SuggestionOptionCopyWith<$Res>
|
||||
implements _$SuggestionRowCopyWith<$Res> {
|
||||
factory _$SuggestionOptionCopyWith(
|
||||
_SuggestionOption value,
|
||||
$Res Function(_SuggestionOption) _then,
|
||||
) = __$SuggestionOptionCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({ComposerOption option, int optionIndex});
|
||||
|
||||
$ComposerOptionCopyWith<$Res> get option;
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$SuggestionOptionCopyWithImpl<$Res>
|
||||
implements _$SuggestionOptionCopyWith<$Res> {
|
||||
__$SuggestionOptionCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _SuggestionOption _self;
|
||||
final $Res Function(_SuggestionOption) _then;
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? option = null, Object? optionIndex = null}) {
|
||||
return _then(
|
||||
_SuggestionOption(
|
||||
null == option
|
||||
? _self.option
|
||||
: option // ignore: cast_nullable_to_non_nullable
|
||||
as ComposerOption,
|
||||
null == optionIndex
|
||||
? _self.optionIndex
|
||||
: optionIndex // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Create a copy of _SuggestionRow
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$ComposerOptionCopyWith<$Res> get option {
|
||||
return $ComposerOptionCopyWith<$Res>(_self.option, (value) {
|
||||
return _then(_self.copyWith(option: value));
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/app_localizations.dart';
|
||||
import 'composer_document.dart';
|
||||
|
||||
part 'composer_suggestions.freezed.dart';
|
||||
|
||||
enum ComposerOptionGroup { media, timeline }
|
||||
|
||||
@freezed
|
||||
sealed class ComposerOption with _$ComposerOption {
|
||||
const factory ComposerOption.reference({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required ComposerReference reference,
|
||||
}) = ComposerReferenceOption;
|
||||
const factory ComposerOption.text({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required String text,
|
||||
}) = ComposerTextOption;
|
||||
const factory ComposerOption.invoke({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required VoidCallback onInvoke,
|
||||
}) = ComposerInvokeOption;
|
||||
const factory ComposerOption.openPicker({
|
||||
required String trigger,
|
||||
required String title,
|
||||
required String subtitle,
|
||||
required IconData icon,
|
||||
ComposerOptionGroup? group,
|
||||
required VoidCallback onInvoke,
|
||||
}) = ComposerPickerOption;
|
||||
}
|
||||
|
||||
/// System-owned entries. More triggers and actions register here later.
|
||||
abstract final class ComposerOptionCatalog {
|
||||
static List<ComposerOption> forTrigger(
|
||||
String trigger, {
|
||||
required AppLocalizations l10n,
|
||||
required String? projectId,
|
||||
required Iterable<AssetDocument> assets,
|
||||
required Iterable<TimelineSummary> timelines,
|
||||
}) {
|
||||
if (trigger != '@' || projectId == null) return const [];
|
||||
return [
|
||||
for (final asset in assets)
|
||||
ComposerOption.reference(
|
||||
trigger: '@',
|
||||
title: asset.name,
|
||||
subtitle: l10n.materials,
|
||||
icon: switch (asset.metadata['kind']) {
|
||||
'video' => Icons.movie_outlined,
|
||||
'audio' => Icons.audiotrack_outlined,
|
||||
'image' => Icons.image_outlined,
|
||||
_ => Icons.insert_drive_file_outlined,
|
||||
},
|
||||
group: ComposerOptionGroup.media,
|
||||
reference: ComposerReference(
|
||||
kind: ComposerReferenceKind.media,
|
||||
projectId: projectId,
|
||||
id: asset.id,
|
||||
label: asset.name,
|
||||
),
|
||||
),
|
||||
for (final timeline in timelines)
|
||||
ComposerOption.reference(
|
||||
trigger: '@',
|
||||
title: timeline.name,
|
||||
subtitle: l10n.timelines,
|
||||
icon: Icons.view_timeline_outlined,
|
||||
group: ComposerOptionGroup.timeline,
|
||||
reference: ComposerReference(
|
||||
kind: ComposerReferenceKind.timeline,
|
||||
projectId: projectId,
|
||||
id: timeline.id,
|
||||
label: timeline.name,
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ComposerTriggerQuery with _$ComposerTriggerQuery {
|
||||
const factory ComposerTriggerQuery({
|
||||
required String trigger,
|
||||
required int start,
|
||||
required int end,
|
||||
required String query,
|
||||
}) = _ComposerTriggerQuery;
|
||||
}
|
||||
|
||||
ComposerTriggerQuery? findComposerTrigger(
|
||||
TextEditingValue value,
|
||||
Iterable<ComposerMark> marks,
|
||||
) {
|
||||
if (!value.selection.isValid || !value.selection.isCollapsed) return null;
|
||||
if (value.composing.isValid && !value.composing.isCollapsed) return null;
|
||||
final caret = value.selection.extentOffset;
|
||||
if (caret <= 0 || caret > value.text.length) return null;
|
||||
for (final mark in marks) {
|
||||
if (caret > mark.start && caret <= mark.end) return null;
|
||||
}
|
||||
final lineStart = value.text.lastIndexOf('\n', caret - 1) + 1;
|
||||
for (var i = caret - 1; i >= lineStart; i--) {
|
||||
final char = value.text[i];
|
||||
if (char != '@' && char != '/' && char != r'$') continue;
|
||||
if (i > 0 &&
|
||||
!RegExp(r'[\s(\[{,;:!?,。!?;:、(“\u3400-\u9fff]')
|
||||
.hasMatch(value.text[i - 1])) {
|
||||
continue;
|
||||
}
|
||||
if (caret - i > 128) return null;
|
||||
if (marks.any((mark) => i >= mark.start && i < mark.end)) return null;
|
||||
final query = value.text.substring(i + 1, caret);
|
||||
if (char == '/' && (query.contains('/') || query.contains('\\'))) {
|
||||
return null;
|
||||
}
|
||||
return ComposerTriggerQuery(
|
||||
trigger: char,
|
||||
start: i,
|
||||
end: caret,
|
||||
query: query,
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
List<ComposerOption> filterComposerOptions(
|
||||
Iterable<ComposerOption> options,
|
||||
String query,
|
||||
) {
|
||||
final normalized = query.trim().toLowerCase();
|
||||
if (normalized.isEmpty) return options.toList();
|
||||
return options
|
||||
.where((option) => option.title.toLowerCase().contains(normalized))
|
||||
.toList();
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,64 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
|
||||
import '../projects/conversation_sidebar.dart';
|
||||
import 'agent_chat_panel.dart';
|
||||
import 'agent_composer_store.dart';
|
||||
import 'composer_project_selector.dart';
|
||||
|
||||
/// Shared conversation presentation, independent of the navigation sidebar.
|
||||
class WorkspaceAgentSurface extends ConsumerWidget {
|
||||
const WorkspaceAgentSurface({
|
||||
super.key,
|
||||
required this.state,
|
||||
required this.onSelectProject,
|
||||
required this.onCreateProject,
|
||||
});
|
||||
|
||||
final ProjectState state;
|
||||
final ValueChanged<RecentProject>? onSelectProject;
|
||||
final VoidCallback? onCreateProject;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selection = ref.watch(
|
||||
conversationSelectionProvider(state.activeProject?.id),
|
||||
);
|
||||
final conversations = ref.read(conversationSidebarProvider.notifier);
|
||||
final composers = ref.watch(agentComposerStoreProvider);
|
||||
final projectId = state.activeProject?.id;
|
||||
final conversationId = selection.selectedId;
|
||||
return AgentChatPanel(
|
||||
key: ValueKey((projectId, conversationId ?? selection.draftKey)),
|
||||
inputController: composers.input(projectId, conversationId),
|
||||
composer: composers.composer(
|
||||
projectId,
|
||||
conversationId ?? selection.draftKey,
|
||||
),
|
||||
projectSelector: ComposerProjectSelector(
|
||||
backgroundColor: AppTheme.composerUtilityBackground(context),
|
||||
projects: state.recent,
|
||||
selected: state.activeProject,
|
||||
busy: state.projectBusy,
|
||||
onSelect: (project) => onSelectProject?.call(project),
|
||||
onCreate: onCreateProject,
|
||||
),
|
||||
composerColor: AppSurfaces.of(context).composerBackground,
|
||||
projectId: projectId,
|
||||
timelineId: state.timeline?.id,
|
||||
conversationId: conversationId,
|
||||
draftKey: conversationId == null ? selection.draftKey : null,
|
||||
onConversationCreated: (item) => unawaited(
|
||||
conversations.updateListing(item, selectIfDraftKey: selection.draftKey),
|
||||
),
|
||||
onConversationUpdated: (item) =>
|
||||
unawaited(conversations.updateListing(item)),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
import '../../workspace/background_task_registry.dart';
|
||||
import '../../workspace/background_task_state.dart';
|
||||
import '../../integrations/runtime/processing_resource_state.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../media/background_tasks_dialog.dart';
|
||||
|
||||
class BackgroundTasksButton extends ConsumerWidget {
|
||||
const BackgroundTasksButton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final registry = ref.watch(backgroundTaskRegistryProvider);
|
||||
final resources = ref
|
||||
.watch(processingResourceRepositoryProvider)
|
||||
.asData
|
||||
?.value;
|
||||
final tasks = ref.watch(backgroundTasksProvider(registry: registry));
|
||||
final downloads = resources == null
|
||||
? null
|
||||
: ref.watch(processingResourcesProvider(resources));
|
||||
bool hasRunningTasks() =>
|
||||
tasks.runningCount > 0 ||
|
||||
downloads?.subtitleDownloading == true ||
|
||||
(downloads?.installs.any(
|
||||
(install) => install.state == ProcessingResourceState.downloading,
|
||||
) ??
|
||||
false);
|
||||
Widget button(VoidCallback toggle) => IconButton(
|
||||
key: const ValueKey('background-tasks-button'),
|
||||
tooltip: context.l10n.backgroundTasks,
|
||||
onPressed: toggle,
|
||||
icon: Badge(
|
||||
isLabelVisible: hasRunningTasks(),
|
||||
child: const Icon(Icons.task_alt_outlined, size: AppIconSize.header),
|
||||
),
|
||||
);
|
||||
return AppPopover(
|
||||
width: 384,
|
||||
builder: (_, toggle) => button(toggle),
|
||||
child: BackgroundTasksContent(registry: registry, repository: resources),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/platform/device_experience.dart';
|
||||
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
import '../../shared/layout/workspace_layout_metrics.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import '../../workspace/view_settings.dart';
|
||||
import '../media/media_browser_page.dart';
|
||||
import '../media/media_panel.dart';
|
||||
import '../preview/preview_panel.dart';
|
||||
import '../properties/properties_editor_page.dart';
|
||||
import '../properties/properties_panel.dart';
|
||||
import '../timeline/timeline_panel.dart';
|
||||
import 'editor_presentation_controller.dart';
|
||||
import 'layouts/bounded_editor_layout.dart';
|
||||
import 'layouts/expanded_editor_layout.dart';
|
||||
|
||||
/// The single editing surface shown beside the project/timeline navigation.
|
||||
class EditorWorkspace extends ConsumerStatefulWidget {
|
||||
const EditorWorkspace({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
required this.projectName,
|
||||
required this.integratedTitlebar,
|
||||
required this.headerLeading,
|
||||
this.showProjectName = true,
|
||||
this.experience = DeviceExperience.desktop,
|
||||
});
|
||||
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
final String projectName;
|
||||
final bool integratedTitlebar;
|
||||
final Widget headerLeading;
|
||||
final bool showProjectName;
|
||||
final DeviceExperience experience;
|
||||
|
||||
@override
|
||||
ConsumerState<EditorWorkspace> createState() => _EditorWorkspaceState();
|
||||
}
|
||||
|
||||
class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
|
||||
final _previewKey = GlobalKey();
|
||||
EditorPresentationController get _presentation =>
|
||||
ref.read(editorPresentationProvider(widget.projectId));
|
||||
ProjectViewSettingsData get _viewSettings =>
|
||||
ref.read(projectViewSettingsProvider(widget.projectId)).value ??
|
||||
const ProjectViewSettingsData();
|
||||
ProjectViewSettings get _viewController =>
|
||||
ref.read(projectViewSettingsProvider(widget.projectId).notifier);
|
||||
bool get _propertiesOpen => _viewSettings.propertiesOpen;
|
||||
double? get _timelineHeight => _viewSettings.timelineHeight;
|
||||
|
||||
void _saveViewSettings() {
|
||||
if (!ref.read(projectViewSettingsProvider(widget.projectId)).hasValue) {
|
||||
return;
|
||||
}
|
||||
unawaited(_viewController.save());
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final viewSettings = ref.watch(
|
||||
projectViewSettingsProvider(widget.projectId),
|
||||
);
|
||||
final preview = KeyedSubtree(
|
||||
key: _previewKey,
|
||||
child: EditorPreviewPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
);
|
||||
final timeline = EditorTimelinePanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
);
|
||||
final properties = EditorPropertiesPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
);
|
||||
final media = MediaPanel(projectId: widget.projectId);
|
||||
return ListenableBuilder(
|
||||
listenable: ref.watch(editorPresentationProvider(widget.projectId)),
|
||||
builder: (context, _) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final desktop = widget.experience == DeviceExperience.desktop;
|
||||
final sideWidth =
|
||||
(_presentation.mediaOpen
|
||||
? WorkspaceLayoutMetrics.mediaPanelWidth + 1
|
||||
: 0) +
|
||||
(_propertiesOpen
|
||||
? WorkspaceLayoutMetrics.propertiesPanelWidth + 1
|
||||
: 0);
|
||||
final dockPanels =
|
||||
desktop &&
|
||||
constraints.maxWidth >=
|
||||
WorkspaceLayoutMetrics.previewMinimumWidth + sideWidth;
|
||||
final desktopTool = sideWidth == 0
|
||||
? null
|
||||
: _presentation.desktopTool(propertiesOpen: _propertiesOpen);
|
||||
final headerHeight = desktop ? AppControlSize.panelHeader : 48.0;
|
||||
final mediaOpen = desktop
|
||||
? dockPanels
|
||||
? _presentation.mediaOpen
|
||||
: desktopTool == EditorTool.media
|
||||
: _presentation.activeTool == EditorTool.media;
|
||||
final propertiesOpen = desktop
|
||||
? dockPanels
|
||||
? _propertiesOpen
|
||||
: desktopTool == EditorTool.properties
|
||||
: _presentation.activeTool == EditorTool.properties;
|
||||
Widget dockedEditing({required bool showTools}) =>
|
||||
ExpandedEditorLayout(
|
||||
preview: preview,
|
||||
properties: properties,
|
||||
media: media,
|
||||
showMedia: showTools && _presentation.mediaOpen,
|
||||
showProperties: showTools && _propertiesOpen,
|
||||
timelineHeight: _timelineHeight,
|
||||
onTimelineHeightChanged: (height) {
|
||||
if (viewSettings.hasValue) {
|
||||
_viewController.setTimelineHeight(height);
|
||||
}
|
||||
},
|
||||
onTimelineHeightChangeEnd: _saveViewSettings,
|
||||
timeline: timeline,
|
||||
);
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
Material(
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: SizedBox(
|
||||
key: const Key('editor-content-header'),
|
||||
height: headerHeight,
|
||||
child: WindowHeaderPadding(
|
||||
child: Row(
|
||||
children: [
|
||||
widget.headerLeading,
|
||||
Expanded(
|
||||
child: widget.showProjectName
|
||||
? Row(
|
||||
children: [
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: Text(
|
||||
widget.projectName,
|
||||
key: const Key(
|
||||
'workspace-project-title',
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.titleSmall,
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
fit: FlexFit.loose,
|
||||
child: _TimelineSaveStatus(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
: const SizedBox.shrink(),
|
||||
),
|
||||
HeaderControlRegion(
|
||||
child: SizedBox.square(
|
||||
dimension: desktop
|
||||
? AppControlSize.headerButton
|
||||
: 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-media-button'),
|
||||
tooltip: context.l10n.materials,
|
||||
isSelected: mediaOpen,
|
||||
onPressed: () {
|
||||
if (desktop) {
|
||||
if (!dockPanels &&
|
||||
desktopTool != EditorTool.media &&
|
||||
_presentation.mediaOpen) {
|
||||
_presentation.preferDesktopTool(
|
||||
EditorTool.media,
|
||||
);
|
||||
} else {
|
||||
_presentation.toggleMedia();
|
||||
}
|
||||
} else {
|
||||
_presentation.toggleTool(
|
||||
EditorTool.media,
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.perm_media_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.tiny),
|
||||
HeaderControlRegion(
|
||||
child: SizedBox.square(
|
||||
dimension: desktop
|
||||
? AppControlSize.headerButton
|
||||
: 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-properties-button'),
|
||||
tooltip: propertiesOpen
|
||||
? context.l10n.collapseProperties
|
||||
: context.l10n.expandProperties,
|
||||
isSelected: propertiesOpen,
|
||||
onPressed: !viewSettings.hasValue
|
||||
? null
|
||||
: () {
|
||||
if (desktop) {
|
||||
if (dockPanels ||
|
||||
desktopTool ==
|
||||
EditorTool.properties ||
|
||||
!_propertiesOpen) {
|
||||
_viewController.setPropertiesOpen(
|
||||
!_propertiesOpen,
|
||||
);
|
||||
_saveViewSettings();
|
||||
}
|
||||
_presentation.preferDesktopTool(
|
||||
EditorTool.properties,
|
||||
);
|
||||
} else {
|
||||
_presentation.toggleTool(
|
||||
EditorTool.properties,
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(
|
||||
Icons.tune,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.compact),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: dockPanels
|
||||
? dockedEditing(showTools: true)
|
||||
: BoundedEditorLayout(
|
||||
experience: widget.experience,
|
||||
editing: desktop
|
||||
? dockedEditing(showTools: false)
|
||||
: TouchEditingLayout(
|
||||
preview: preview,
|
||||
timeline: timeline,
|
||||
),
|
||||
tool: desktop
|
||||
? desktopTool
|
||||
: _presentation.activeTool,
|
||||
media: switch (widget.experience) {
|
||||
DeviceExperience.desktop => media,
|
||||
DeviceExperience.tablet => MediaBrowserDrawer(
|
||||
projectId: widget.projectId,
|
||||
),
|
||||
DeviceExperience.phone => MediaBrowserPage(
|
||||
projectId: widget.projectId,
|
||||
),
|
||||
},
|
||||
properties: switch (widget.experience) {
|
||||
DeviceExperience.desktop => properties,
|
||||
DeviceExperience.tablet => PropertiesToolPanel(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
DeviceExperience.phone => PropertiesEditorPage(
|
||||
projectId: widget.projectId,
|
||||
timelineId: widget.timelineId,
|
||||
),
|
||||
},
|
||||
onCloseTool: () {
|
||||
if (!desktop) {
|
||||
_presentation.closeTool();
|
||||
} else if (desktopTool == EditorTool.media) {
|
||||
_presentation.toggleMedia();
|
||||
} else {
|
||||
_viewController.setPropertiesOpen(false);
|
||||
_saveViewSettings();
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Positioned(
|
||||
key: const Key('editing-top-divider'),
|
||||
top: headerHeight,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: 1,
|
||||
child: const Divider(height: 1),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TimelineSaveStatus extends ConsumerWidget {
|
||||
const _TimelineSaveStatus({
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
});
|
||||
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final session = ref
|
||||
.watch(editorTimelineProvider(projectId, timelineId))
|
||||
.asData
|
||||
?.value;
|
||||
if (session == null) return const SizedBox.shrink();
|
||||
return ListenableBuilder(
|
||||
listenable: session,
|
||||
builder: (context, _) => Padding(
|
||||
padding: const EdgeInsets.only(left: AppSpacing.small),
|
||||
child: Text(
|
||||
session.error != null
|
||||
? context.l10n.unsaved
|
||||
: session.saving
|
||||
? context.l10n.saving
|
||||
: session.dirty
|
||||
? context.l10n.pendingSave
|
||||
: context.l10n.saved,
|
||||
key: const Key('timeline-save-status'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(fontSize: 10),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
enum EditorTool { media, properties }
|
||||
|
||||
final editorPresentationProvider =
|
||||
Provider.family<EditorPresentationController, String>((ref, projectId) {
|
||||
final controller = EditorPresentationController();
|
||||
ref.onDispose(controller.dispose);
|
||||
return controller;
|
||||
});
|
||||
|
||||
/// Presentation choices survive shell changes without changing project data.
|
||||
class EditorPresentationController extends ChangeNotifier {
|
||||
bool _mediaOpen = false;
|
||||
EditorTool? _activeTool;
|
||||
EditorTool _preferredDesktopTool = EditorTool.properties;
|
||||
|
||||
bool get mediaOpen => _mediaOpen;
|
||||
EditorTool? get activeTool => _activeTool;
|
||||
EditorTool desktopTool({required bool propertiesOpen}) =>
|
||||
_preferredDesktopTool == EditorTool.media && _mediaOpen
|
||||
? EditorTool.media
|
||||
: propertiesOpen
|
||||
? EditorTool.properties
|
||||
: EditorTool.media;
|
||||
|
||||
void preferDesktopTool(EditorTool tool) {
|
||||
_preferredDesktopTool = tool;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void toggleMedia() {
|
||||
_mediaOpen = !_mediaOpen;
|
||||
if (_mediaOpen) _preferredDesktopTool = EditorTool.media;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void toggleTool(EditorTool tool) {
|
||||
_activeTool = _activeTool == tool ? null : tool;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void closeTool() {
|
||||
_activeTool = null;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../integrations/platform/device_experience.dart';
|
||||
import '../../../l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../editor_presentation_controller.dart';
|
||||
|
||||
/// Space changes the tool bounds; device experience determines its interactions.
|
||||
class BoundedEditorLayout extends StatelessWidget {
|
||||
const BoundedEditorLayout({
|
||||
super.key,
|
||||
required this.experience,
|
||||
required this.editing,
|
||||
required this.tool,
|
||||
required this.media,
|
||||
required this.properties,
|
||||
required this.onCloseTool,
|
||||
});
|
||||
|
||||
final DeviceExperience experience;
|
||||
final Widget editing;
|
||||
final EditorTool? tool;
|
||||
final Widget media;
|
||||
final Widget properties;
|
||||
final VoidCallback onCloseTool;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final page = experience == DeviceExperience.phone;
|
||||
final desktop = experience == DeviceExperience.desktop;
|
||||
Widget toolSurface() => Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: desktop ? AppControlSize.panelHeader : 48,
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox.square(
|
||||
dimension: desktop ? AppControlSize.headerButton : 48,
|
||||
child: IconButton(
|
||||
key: const Key('editor-tool-close'),
|
||||
tooltip: MaterialLocalizations.of(context)
|
||||
.closeButtonTooltip,
|
||||
onPressed: onCloseTool,
|
||||
icon: Icon(page ? Icons.arrow_back : Icons.close),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
tool == EditorTool.media
|
||||
? context.l10n.materials
|
||||
: context.l10n.expandProperties,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(child: tool == EditorTool.media ? media : properties),
|
||||
],
|
||||
);
|
||||
return PopScope<Object?>(
|
||||
canPop: desktop || tool == null,
|
||||
onPopInvokedWithResult: (didPop, result) {
|
||||
if (didPop || desktop || tool == null) return;
|
||||
final scaffold = Scaffold.maybeOf(context);
|
||||
if (scaffold?.isDrawerOpen ?? false) {
|
||||
scaffold!.closeDrawer();
|
||||
} else {
|
||||
onCloseTool();
|
||||
}
|
||||
},
|
||||
child: Stack(
|
||||
key: Key('${experience.name}-editor-tools'),
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
ExcludeFocus(
|
||||
excluding: page && tool != null,
|
||||
child: IgnorePointer(
|
||||
ignoring: page && tool != null,
|
||||
child: TickerMode(
|
||||
enabled: !page || tool == null,
|
||||
child: editing,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (tool != null)
|
||||
Positioned(
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
right: 0,
|
||||
width: page
|
||||
? constraints.maxWidth
|
||||
: math.min(320, constraints.maxWidth),
|
||||
child: Material(
|
||||
key: const Key('editor-tool-surface'),
|
||||
elevation: page ? 0 : 8,
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: toolSurface(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// A shared preview/timeline arrangement for touch experiences.
|
||||
class TouchEditingLayout extends StatelessWidget {
|
||||
const TouchEditingLayout({
|
||||
super.key,
|
||||
required this.preview,
|
||||
required this.timeline,
|
||||
});
|
||||
final Widget preview;
|
||||
final Widget timeline;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final short = constraints.maxHeight < 340 && constraints.maxWidth >= 600;
|
||||
return short
|
||||
? Row(
|
||||
children: [
|
||||
Expanded(child: preview),
|
||||
const VerticalDivider(width: 1),
|
||||
Expanded(child: timeline),
|
||||
],
|
||||
)
|
||||
: Column(
|
||||
children: [
|
||||
Expanded(flex: 3, child: preview),
|
||||
const Divider(height: 1),
|
||||
Expanded(flex: 2, child: timeline),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:flutter/gestures.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../shared/layout/workspace_layout_metrics.dart';
|
||||
|
||||
class ExpandedEditorLayout extends StatefulWidget {
|
||||
const ExpandedEditorLayout({
|
||||
super.key,
|
||||
required this.preview,
|
||||
required this.properties,
|
||||
required this.media,
|
||||
required this.showMedia,
|
||||
required this.showProperties,
|
||||
required this.timelineHeight,
|
||||
required this.onTimelineHeightChanged,
|
||||
required this.onTimelineHeightChangeEnd,
|
||||
required this.timeline,
|
||||
});
|
||||
|
||||
final Widget preview;
|
||||
final Widget properties;
|
||||
final Widget media;
|
||||
final bool showMedia;
|
||||
final bool showProperties;
|
||||
final double? timelineHeight;
|
||||
final ValueChanged<double> onTimelineHeightChanged;
|
||||
final VoidCallback onTimelineHeightChangeEnd;
|
||||
final Widget timeline;
|
||||
|
||||
@override
|
||||
State<ExpandedEditorLayout> createState() => _ExpandedEditorLayoutState();
|
||||
}
|
||||
|
||||
class _ExpandedEditorLayoutState extends State<ExpandedEditorLayout> {
|
||||
double? _timelineDragStartY;
|
||||
double _timelineDragStartHeight = 0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final maximum = math.max(
|
||||
0.0,
|
||||
constraints.maxHeight - WorkspaceLayoutMetrics.timelineMinimumHeight,
|
||||
);
|
||||
final minimum = math.min(
|
||||
WorkspaceLayoutMetrics.timelineMinimumHeight,
|
||||
maximum,
|
||||
);
|
||||
final timelineHeight =
|
||||
(widget.timelineHeight ??
|
||||
constraints.maxHeight *
|
||||
WorkspaceLayoutMetrics.timelineDefaultHeightFraction)
|
||||
.clamp(minimum, maximum)
|
||||
.toDouble();
|
||||
final mediaWidth = widget.showMedia
|
||||
? WorkspaceLayoutMetrics.mediaPanelWidth
|
||||
: 0.0;
|
||||
final propertiesWidth = widget.showProperties
|
||||
? WorkspaceLayoutMetrics.propertiesPanelWidth
|
||||
: 0.0;
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (widget.showMedia) ...[
|
||||
SizedBox(
|
||||
key: const Key('editor-media-region'),
|
||||
width: mediaWidth,
|
||||
child: widget.media,
|
||||
),
|
||||
const VerticalDivider(width: 1),
|
||||
],
|
||||
Expanded(child: widget.preview),
|
||||
if (widget.showProperties) ...[
|
||||
const VerticalDivider(width: 1),
|
||||
SizedBox(
|
||||
key: const Key('editor-properties-region'),
|
||||
width: propertiesWidth,
|
||||
child: widget.properties,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 1),
|
||||
SizedBox(height: timelineHeight, child: widget.timeline),
|
||||
],
|
||||
),
|
||||
Positioned(
|
||||
key: const Key('editor-timeline-divider'),
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: timelineHeight - 4,
|
||||
height: 8,
|
||||
child: MouseRegion(
|
||||
cursor: SystemMouseCursors.resizeRow,
|
||||
child: GestureDetector(
|
||||
key: const Key('editor-timeline-resize'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
dragStartBehavior: DragStartBehavior.down,
|
||||
onVerticalDragStart: (details) {
|
||||
_timelineDragStartY = details.globalPosition.dy;
|
||||
_timelineDragStartHeight = timelineHeight;
|
||||
},
|
||||
onVerticalDragUpdate: (details) {
|
||||
final start = _timelineDragStartY;
|
||||
if (start == null) return;
|
||||
widget.onTimelineHeightChanged(
|
||||
(_timelineDragStartHeight +
|
||||
start -
|
||||
details.globalPosition.dy)
|
||||
.clamp(minimum, maximum)
|
||||
.toDouble(),
|
||||
);
|
||||
},
|
||||
onVerticalDragEnd: (_) {
|
||||
_timelineDragStartY = null;
|
||||
widget.onTimelineHeightChangeEnd();
|
||||
},
|
||||
onVerticalDragCancel: () {
|
||||
_timelineDragStartY = null;
|
||||
widget.onTimelineHeightChangeEnd();
|
||||
},
|
||||
child: const Center(
|
||||
child: SizedBox(
|
||||
height: 1,
|
||||
width: double.infinity,
|
||||
child: Divider(height: 1),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:cutdex_sdk/timeline_ui.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/runtime/media_presentations.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
class AudioAssetTile extends StatelessWidget {
|
||||
const AudioAssetTile({
|
||||
super.key,
|
||||
required this.asset,
|
||||
this.showName = true,
|
||||
this.aspectRatio = 16 / 9,
|
||||
});
|
||||
final AssetDocument asset;
|
||||
final bool showName;
|
||||
final double aspectRatio;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
AspectRatio(
|
||||
key: ValueKey('audio-cover-${asset.id}'),
|
||||
aspectRatio: aspectRatio,
|
||||
child: ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: _AudioWaveformCover(asset),
|
||||
),
|
||||
),
|
||||
if (showName) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Tooltip(
|
||||
message: asset.name,
|
||||
child: Text(
|
||||
asset.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AudioWaveformCover extends ConsumerWidget {
|
||||
const _AudioWaveformCover(this.asset);
|
||||
final AssetDocument asset;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final waveform = ref.watch(mediaWaveformProvider(asset)).value;
|
||||
final theme = Theme.of(context);
|
||||
if (waveform == null) {
|
||||
return Center(
|
||||
child: Icon(
|
||||
Icons.audio_file_outlined,
|
||||
size: AppIconSize.emptyState,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
);
|
||||
}
|
||||
return CustomPaint(
|
||||
key: ValueKey('audio-waveform-${asset.id}'),
|
||||
painter: _AudioCoverPainter(
|
||||
waveform,
|
||||
theme.extension<TimelineThemeData>()?.audioAccentColor ??
|
||||
theme.colorScheme.primary,
|
||||
MediaQuery.devicePixelRatioOf(context),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AudioCoverPainter extends CustomPainter {
|
||||
const _AudioCoverPainter(this.waveform, this.color, this.devicePixelRatio);
|
||||
final TimelineWaveform waveform;
|
||||
final Color color;
|
||||
final double devicePixelRatio;
|
||||
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
if (size.isEmpty) return;
|
||||
final columns = math.max(1, (size.width / 2).floor());
|
||||
final start = waveform.sourceStartSeconds * TimelineClock.ticksPerSecond;
|
||||
final duration =
|
||||
waveform.frameCount /
|
||||
waveform.sampleRate *
|
||||
TimelineClock.ticksPerSecond;
|
||||
final paint = Paint()
|
||||
..color = color
|
||||
..style = PaintingStyle.fill
|
||||
..isAntiAlias = false;
|
||||
final strokePixels = math.max(1, devicePixelRatio.round());
|
||||
final bottomPixels = math.max(1, (size.height * devicePixelRatio).floor());
|
||||
for (var column = 0; column < columns; column++) {
|
||||
final envelope = waveform.envelope(
|
||||
(start + duration * column / columns).round(),
|
||||
(start + duration * (column + 1) / columns).round(),
|
||||
);
|
||||
final peak = math.max(envelope.minimum.abs(), envelope.maximum.abs());
|
||||
final height = math.min(size.height, math.max(1.0, peak * size.height));
|
||||
final x = (column + 0.5) * size.width / columns;
|
||||
final leftPixels = (x * devicePixelRatio - strokePixels / 2).round();
|
||||
final topPixels = ((size.height - height) * devicePixelRatio)
|
||||
.round()
|
||||
.clamp(0, bottomPixels - 1);
|
||||
canvas.drawRect(
|
||||
Rect.fromLTWH(
|
||||
leftPixels / devicePixelRatio,
|
||||
topPixels / devicePixelRatio,
|
||||
strokePixels / devicePixelRatio,
|
||||
(bottomPixels - topPixels) / devicePixelRatio,
|
||||
),
|
||||
paint,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(_AudioCoverPainter oldDelegate) =>
|
||||
oldDelegate.waveform != waveform ||
|
||||
oldDelegate.color != color ||
|
||||
oldDelegate.devicePixelRatio != devicePixelRatio;
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
import 'package:cutdex/diagnostics/app_diagnostics.dart';
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_configuration.dart';
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'processing_targets.dart';
|
||||
|
||||
part 'background_removal_controller.g.dart';
|
||||
part 'background_removal_controller.freezed.dart';
|
||||
|
||||
enum BackgroundRemovalFailure { download, start, rejected }
|
||||
|
||||
@freezed
|
||||
sealed class BackgroundRemovalState with _$BackgroundRemovalState {
|
||||
const factory BackgroundRemovalState.idle() = RemovalIdle;
|
||||
const factory BackgroundRemovalState.downloading() = RemovalDownloading;
|
||||
const factory BackgroundRemovalState.starting() = RemovalStarting;
|
||||
const factory BackgroundRemovalState.started() = RemovalStarted;
|
||||
const factory BackgroundRemovalState.cancelled() = RemovalCancelled;
|
||||
const factory BackgroundRemovalState.failed(
|
||||
BackgroundRemovalFailure failure, {
|
||||
String? message,
|
||||
}) = RemovalFailed;
|
||||
}
|
||||
|
||||
@riverpod
|
||||
class BackgroundRemovalController extends _$BackgroundRemovalController {
|
||||
bool _cancelled = false;
|
||||
ProcessingResourceRepository? _repository;
|
||||
|
||||
@override
|
||||
BackgroundRemovalState build(
|
||||
EditorTimelineSession session,
|
||||
BackgroundRemovalClipTarget target,
|
||||
) {
|
||||
ref.onDispose(() {
|
||||
_cancelled = true;
|
||||
});
|
||||
return const BackgroundRemovalState.idle();
|
||||
}
|
||||
|
||||
Future<void> start(
|
||||
ProcessingResourceRepository repository, {
|
||||
bool download = false,
|
||||
}) async {
|
||||
if (state is RemovalDownloading || state is RemovalStarting) return;
|
||||
final lease = ref.keepAlive();
|
||||
final release = session.retainViews();
|
||||
_repository = repository;
|
||||
_cancelled = false;
|
||||
var installed = !download;
|
||||
state = download
|
||||
? const BackgroundRemovalState.downloading()
|
||||
: const BackgroundRemovalState.starting();
|
||||
try {
|
||||
if (download) {
|
||||
await repository.ensureAvailable(
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
);
|
||||
installed = true;
|
||||
}
|
||||
if (_cancelled || !ref.mounted || !session.acceptsEdits) return;
|
||||
state = const BackgroundRemovalState.starting();
|
||||
final processing = ProcessingConfiguration.configured(
|
||||
diagnostics: AppDiagnostics.report,
|
||||
resourcesRoot: repository.root.parent.path,
|
||||
);
|
||||
final model = processing?.backgroundRemovalModel;
|
||||
if (processing == null || model == null) {
|
||||
throw AppException(AppErrorCode.startBackgroundRemovalFailed);
|
||||
}
|
||||
session.backgroundRemovals.configure(
|
||||
backend: processing.backend.execute,
|
||||
model: model,
|
||||
);
|
||||
await session.backgroundRemovals.start(
|
||||
sequence: target.sequence,
|
||||
clipId: target.clipId,
|
||||
mediaId: target.mediaId,
|
||||
name: target.name,
|
||||
backend: processing.backend.execute,
|
||||
model: model,
|
||||
);
|
||||
if (ref.mounted) state = const BackgroundRemovalState.started();
|
||||
} on ProcessingResourceCancelledException {
|
||||
if (ref.mounted) state = const BackgroundRemovalState.cancelled();
|
||||
} on CommandRejected catch (error) {
|
||||
if (ref.mounted) {
|
||||
state = BackgroundRemovalState.failed(
|
||||
BackgroundRemovalFailure.rejected,
|
||||
message: error.message,
|
||||
);
|
||||
}
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = BackgroundRemovalState.failed(
|
||||
installed
|
||||
? BackgroundRemovalFailure.start
|
||||
: BackgroundRemovalFailure.download,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
if (ref.mounted &&
|
||||
(state is RemovalDownloading || state is RemovalStarting)) {
|
||||
state = const BackgroundRemovalState.cancelled();
|
||||
}
|
||||
_repository = null;
|
||||
release();
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
|
||||
void cancel(ProcessingResourceRepository repository) {
|
||||
_cancelled = true;
|
||||
(_repository ?? repository).cancel(ProcessingCapability.backgroundRemoval);
|
||||
}
|
||||
|
||||
void togglePause(ProcessingResourceRepository repository) {
|
||||
if (repository.downloadPausedFor(ProcessingCapability.backgroundRemoval)) {
|
||||
repository.resumeDownload(ProcessingCapability.backgroundRemoval);
|
||||
} else {
|
||||
repository.pauseDownload(ProcessingCapability.backgroundRemoval);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'background_removal_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$BackgroundRemovalState {
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is BackgroundRemovalState);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class $BackgroundRemovalStateCopyWith<$Res> {
|
||||
$BackgroundRemovalStateCopyWith(
|
||||
BackgroundRemovalState _,
|
||||
$Res Function(BackgroundRemovalState) __,
|
||||
);
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [BackgroundRemovalState].
|
||||
extension BackgroundRemovalStatePatterns on BackgroundRemovalState {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>({
|
||||
TResult Function(RemovalIdle value)? idle,
|
||||
TResult Function(RemovalDownloading value)? downloading,
|
||||
TResult Function(RemovalStarting value)? starting,
|
||||
TResult Function(RemovalStarted value)? started,
|
||||
TResult Function(RemovalCancelled value)? cancelled,
|
||||
TResult Function(RemovalFailed value)? failed,
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case RemovalIdle() when idle != null:
|
||||
return idle(_that);
|
||||
case RemovalDownloading() when downloading != null:
|
||||
return downloading(_that);
|
||||
case RemovalStarting() when starting != null:
|
||||
return starting(_that);
|
||||
case RemovalStarted() when started != null:
|
||||
return started(_that);
|
||||
case RemovalCancelled() when cancelled != null:
|
||||
return cancelled(_that);
|
||||
case RemovalFailed() when failed != null:
|
||||
return failed(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>({
|
||||
required TResult Function(RemovalIdle value) idle,
|
||||
required TResult Function(RemovalDownloading value) downloading,
|
||||
required TResult Function(RemovalStarting value) starting,
|
||||
required TResult Function(RemovalStarted value) started,
|
||||
required TResult Function(RemovalCancelled value) cancelled,
|
||||
required TResult Function(RemovalFailed value) failed,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case RemovalIdle():
|
||||
return idle(_that);
|
||||
case RemovalDownloading():
|
||||
return downloading(_that);
|
||||
case RemovalStarting():
|
||||
return starting(_that);
|
||||
case RemovalStarted():
|
||||
return started(_that);
|
||||
case RemovalCancelled():
|
||||
return cancelled(_that);
|
||||
case RemovalFailed():
|
||||
return failed(_that);
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>({
|
||||
TResult? Function(RemovalIdle value)? idle,
|
||||
TResult? Function(RemovalDownloading value)? downloading,
|
||||
TResult? Function(RemovalStarting value)? starting,
|
||||
TResult? Function(RemovalStarted value)? started,
|
||||
TResult? Function(RemovalCancelled value)? cancelled,
|
||||
TResult? Function(RemovalFailed value)? failed,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case RemovalIdle() when idle != null:
|
||||
return idle(_that);
|
||||
case RemovalDownloading() when downloading != null:
|
||||
return downloading(_that);
|
||||
case RemovalStarting() when starting != null:
|
||||
return starting(_that);
|
||||
case RemovalStarted() when started != null:
|
||||
return started(_that);
|
||||
case RemovalCancelled() when cancelled != null:
|
||||
return cancelled(_that);
|
||||
case RemovalFailed() when failed != null:
|
||||
return failed(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>({
|
||||
TResult Function()? idle,
|
||||
TResult Function()? downloading,
|
||||
TResult Function()? starting,
|
||||
TResult Function()? started,
|
||||
TResult Function()? cancelled,
|
||||
TResult Function(BackgroundRemovalFailure failure, String? message)? failed,
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case RemovalIdle() when idle != null:
|
||||
return idle();
|
||||
case RemovalDownloading() when downloading != null:
|
||||
return downloading();
|
||||
case RemovalStarting() when starting != null:
|
||||
return starting();
|
||||
case RemovalStarted() when started != null:
|
||||
return started();
|
||||
case RemovalCancelled() when cancelled != null:
|
||||
return cancelled();
|
||||
case RemovalFailed() when failed != null:
|
||||
return failed(_that.failure, _that.message);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>({
|
||||
required TResult Function() idle,
|
||||
required TResult Function() downloading,
|
||||
required TResult Function() starting,
|
||||
required TResult Function() started,
|
||||
required TResult Function() cancelled,
|
||||
required TResult Function(BackgroundRemovalFailure failure, String? message)
|
||||
failed,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case RemovalIdle():
|
||||
return idle();
|
||||
case RemovalDownloading():
|
||||
return downloading();
|
||||
case RemovalStarting():
|
||||
return starting();
|
||||
case RemovalStarted():
|
||||
return started();
|
||||
case RemovalCancelled():
|
||||
return cancelled();
|
||||
case RemovalFailed():
|
||||
return failed(_that.failure, _that.message);
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>({
|
||||
TResult? Function()? idle,
|
||||
TResult? Function()? downloading,
|
||||
TResult? Function()? starting,
|
||||
TResult? Function()? started,
|
||||
TResult? Function()? cancelled,
|
||||
TResult? Function(BackgroundRemovalFailure failure, String? message)?
|
||||
failed,
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case RemovalIdle() when idle != null:
|
||||
return idle();
|
||||
case RemovalDownloading() when downloading != null:
|
||||
return downloading();
|
||||
case RemovalStarting() when starting != null:
|
||||
return starting();
|
||||
case RemovalStarted() when started != null:
|
||||
return started();
|
||||
case RemovalCancelled() when cancelled != null:
|
||||
return cancelled();
|
||||
case RemovalFailed() when failed != null:
|
||||
return failed(_that.failure, _that.message);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class RemovalIdle implements BackgroundRemovalState {
|
||||
const RemovalIdle();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is RemovalIdle);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState.idle()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class RemovalDownloading implements BackgroundRemovalState {
|
||||
const RemovalDownloading();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is RemovalDownloading);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState.downloading()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class RemovalStarting implements BackgroundRemovalState {
|
||||
const RemovalStarting();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is RemovalStarting);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState.starting()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class RemovalStarted implements BackgroundRemovalState {
|
||||
const RemovalStarted();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is RemovalStarted);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState.started()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class RemovalCancelled implements BackgroundRemovalState {
|
||||
const RemovalCancelled();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType && other is RemovalCancelled);
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => runtimeType.hashCode;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState.cancelled()';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class RemovalFailed implements BackgroundRemovalState {
|
||||
const RemovalFailed(this.failure, {this.message});
|
||||
|
||||
final BackgroundRemovalFailure failure;
|
||||
final String? message;
|
||||
|
||||
/// Create a copy of BackgroundRemovalState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$RemovalFailedCopyWith<RemovalFailed> get copyWith =>
|
||||
_$RemovalFailedCopyWithImpl<RemovalFailed>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is RemovalFailed &&
|
||||
(identical(other.failure, failure) || other.failure == failure) &&
|
||||
(identical(other.message, message) || other.message == message));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, failure, message);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalState.failed(failure: $failure, message: $message)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $RemovalFailedCopyWith<$Res>
|
||||
implements $BackgroundRemovalStateCopyWith<$Res> {
|
||||
factory $RemovalFailedCopyWith(
|
||||
RemovalFailed value,
|
||||
$Res Function(RemovalFailed) _then,
|
||||
) = _$RemovalFailedCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({BackgroundRemovalFailure failure, String? message});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$RemovalFailedCopyWithImpl<$Res>
|
||||
implements $RemovalFailedCopyWith<$Res> {
|
||||
_$RemovalFailedCopyWithImpl(this._self, this._then);
|
||||
|
||||
final RemovalFailed _self;
|
||||
final $Res Function(RemovalFailed) _then;
|
||||
|
||||
/// Create a copy of BackgroundRemovalState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? failure = null, Object? message = freezed}) {
|
||||
return _then(
|
||||
RemovalFailed(
|
||||
null == failure
|
||||
? _self.failure
|
||||
: failure // ignore: cast_nullable_to_non_nullable
|
||||
as BackgroundRemovalFailure,
|
||||
message: freezed == message
|
||||
? _self.message
|
||||
: message // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'background_removal_controller.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BackgroundRemovalController)
|
||||
final backgroundRemovalControllerProvider =
|
||||
BackgroundRemovalControllerFamily._();
|
||||
|
||||
final class BackgroundRemovalControllerProvider
|
||||
extends
|
||||
$NotifierProvider<BackgroundRemovalController, BackgroundRemovalState> {
|
||||
BackgroundRemovalControllerProvider._({
|
||||
required BackgroundRemovalControllerFamily super.from,
|
||||
required (EditorTimelineSession, BackgroundRemovalClipTarget)
|
||||
super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'backgroundRemovalControllerProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$backgroundRemovalControllerHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'backgroundRemovalControllerProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BackgroundRemovalController create() => BackgroundRemovalController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(BackgroundRemovalState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<BackgroundRemovalState>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is BackgroundRemovalControllerProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$backgroundRemovalControllerHash() =>
|
||||
r'429add9c699b92fdba9c553810f17f4a6859f4e6';
|
||||
|
||||
final class BackgroundRemovalControllerFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
BackgroundRemovalController,
|
||||
BackgroundRemovalState,
|
||||
BackgroundRemovalState,
|
||||
BackgroundRemovalState,
|
||||
(EditorTimelineSession, BackgroundRemovalClipTarget)
|
||||
> {
|
||||
BackgroundRemovalControllerFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'backgroundRemovalControllerProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
BackgroundRemovalControllerProvider call(
|
||||
EditorTimelineSession session,
|
||||
BackgroundRemovalClipTarget target,
|
||||
) => BackgroundRemovalControllerProvider._(
|
||||
argument: (session, target),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'backgroundRemovalControllerProvider';
|
||||
}
|
||||
|
||||
abstract class _$BackgroundRemovalController
|
||||
extends $Notifier<BackgroundRemovalState> {
|
||||
late final _$args =
|
||||
ref.$arg as (EditorTimelineSession, BackgroundRemovalClipTarget);
|
||||
EditorTimelineSession get session => _$args.$1;
|
||||
BackgroundRemovalClipTarget get target => _$args.$2;
|
||||
|
||||
BackgroundRemovalState build(
|
||||
EditorTimelineSession session,
|
||||
BackgroundRemovalClipTarget target,
|
||||
);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref as $Ref<BackgroundRemovalState, BackgroundRemovalState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<BackgroundRemovalState, BackgroundRemovalState>,
|
||||
BackgroundRemovalState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_configuration.dart';
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
import '../../integrations/runtime/processing_resource_state.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/widgets/confirm_resource_download_cancel.dart';
|
||||
import '../../shared/widgets/processing_resource_download_dialog.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
import 'processing_targets.dart';
|
||||
import 'background_removal_controller.dart';
|
||||
export 'processing_targets.dart';
|
||||
|
||||
class BackgroundRemovalDialog extends ConsumerStatefulWidget {
|
||||
const BackgroundRemovalDialog({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.target,
|
||||
});
|
||||
|
||||
final EditorTimelineSession session;
|
||||
final BackgroundRemovalClipTarget target;
|
||||
|
||||
@override
|
||||
ConsumerState<BackgroundRemovalDialog> createState() =>
|
||||
_BackgroundRemovalDialogState();
|
||||
}
|
||||
|
||||
class _BackgroundRemovalDialogState
|
||||
extends ConsumerState<BackgroundRemovalDialog> {
|
||||
late final VoidCallback _release;
|
||||
bool _closing = false;
|
||||
BackgroundRemovalControllerProvider get _provider =>
|
||||
backgroundRemovalControllerProvider(widget.session, widget.target);
|
||||
BackgroundRemovalState get _state => ref.read(_provider);
|
||||
bool get _installing => _state is RemovalDownloading;
|
||||
bool get _starting => _state is RemovalStarting;
|
||||
String? get _error => switch (_state) {
|
||||
RemovalFailed(:final failure, :final message) => switch (failure) {
|
||||
BackgroundRemovalFailure.download =>
|
||||
context.l10n.processingResourceDownloadFailed,
|
||||
BackgroundRemovalFailure.start =>
|
||||
context.l10n.startBackgroundRemovalFailed,
|
||||
BackgroundRemovalFailure.rejected => message,
|
||||
},
|
||||
_ => null,
|
||||
};
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_release = widget.session.retainViews();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_release();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _start(ProcessingResourceRepository repository) =>
|
||||
ref.read(_provider.notifier).start(repository);
|
||||
Future<void> _downloadAndStart(ProcessingResourceRepository repository) =>
|
||||
ref.read(_provider.notifier).start(repository, download: true);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(_provider);
|
||||
ref.listen(_provider, (previous, next) {
|
||||
if (next is! RemovalStarted || _closing) return;
|
||||
_closing = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||
final message = context.l10n.backgroundRemovalTaskStarted;
|
||||
Navigator.of(context).pop();
|
||||
messenger?.showSnackBar(SnackBar(content: Text(message)));
|
||||
});
|
||||
});
|
||||
return ref
|
||||
.watch(processingResourceRepositoryProvider)
|
||||
.when(
|
||||
loading: () => const DelayedLoadingIndicator(
|
||||
child: AppDialog(
|
||||
title: '',
|
||||
width: 520,
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
),
|
||||
error: (_, _) => AppDialog(
|
||||
title: context.l10n.removeBackground,
|
||||
width: 520,
|
||||
child: Text(context.l10n.loadResourceLocationFailed),
|
||||
),
|
||||
data: (repository) => Consumer(
|
||||
builder: (context, ref, _) {
|
||||
final resources = ref.watch(
|
||||
processingResourcesProvider(repository),
|
||||
);
|
||||
final install =
|
||||
resources.installs
|
||||
.where(
|
||||
(item) =>
|
||||
item.package.capability ==
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
)
|
||||
.firstOrNull ??
|
||||
repository.installFor(ProcessingCapability.backgroundRemoval);
|
||||
final installed =
|
||||
install.state == ProcessingResourceState.installed ||
|
||||
ProcessingConfiguration.configured(
|
||||
resourcesRoot: repository.root.parent.path,
|
||||
)?.backgroundRemovalModel !=
|
||||
null;
|
||||
final downloading =
|
||||
install.state == ProcessingResourceState.downloading;
|
||||
if (!installed) {
|
||||
return ProcessingResourceDownloadDialog(
|
||||
title: context.l10n.backgroundRemovalDownloadTask,
|
||||
description: context.l10n.backgroundRemovalResourceRequired,
|
||||
resourceName: context.l10n.backgroundRemovalResourceName,
|
||||
downloadSize: context.l10n.subtitleResourcesDownloadSize(
|
||||
formatResourceBytes(install.package.bytes),
|
||||
),
|
||||
downloading: downloading,
|
||||
paused: resources.paused.contains(
|
||||
ProcessingCapability.backgroundRemoval,
|
||||
),
|
||||
downloadedBytes: install.downloadedBytes,
|
||||
totalBytes: install.package.bytes,
|
||||
bytesPerSecond:
|
||||
resources.rates[ProcessingCapability.backgroundRemoval] ??
|
||||
0,
|
||||
error: _error,
|
||||
downloadButtonKey: const Key(
|
||||
'download-background-removal-resource',
|
||||
),
|
||||
pauseButtonKey: const Key(
|
||||
'pause-background-removal-resource',
|
||||
),
|
||||
backgroundButtonKey: const Key(
|
||||
'background-background-removal-resource',
|
||||
),
|
||||
onCancel: () async {
|
||||
if (downloading &&
|
||||
!await confirmResourceDownloadCancellation(context)) {
|
||||
return;
|
||||
}
|
||||
if (!mounted || !context.mounted) return;
|
||||
if (downloading) {
|
||||
ref.read(_provider.notifier).cancel(repository);
|
||||
}
|
||||
Navigator.of(context).pop();
|
||||
},
|
||||
onDownload: () {
|
||||
if (!_installing && !downloading) {
|
||||
_downloadAndStart(repository);
|
||||
}
|
||||
},
|
||||
onTogglePause: () =>
|
||||
ref.read(_provider.notifier).togglePause(repository),
|
||||
onBackground: () => Navigator.of(context).pop(),
|
||||
);
|
||||
}
|
||||
return AppDialog(
|
||||
title: context.l10n.removeBackground,
|
||||
width: 520,
|
||||
description: context.l10n.backgroundRemovalDestructiveHint,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(context.l10n.close),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed:
|
||||
_installing || _starting || !widget.session.acceptsEdits
|
||||
? null
|
||||
: () => _start(repository),
|
||||
child: Text(context.l10n.startBackgroundRemoval),
|
||||
),
|
||||
],
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (_error case final error?) ...[
|
||||
const SizedBox(height: AppSpacing.compact),
|
||||
Text(error),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,862 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'subtitle_download.dart';
|
||||
import 'subtitle_task_actions.dart';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/widgets/confirm_resource_download_cancel.dart';
|
||||
import '../../workspace/background_task_registry.dart';
|
||||
import '../../workspace/background_task_state.dart';
|
||||
import '../../integrations/runtime/processing_resource_state.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'transcription_dialog.dart';
|
||||
|
||||
class BackgroundTasksDialog extends StatelessWidget {
|
||||
const BackgroundTasksDialog({super.key, required this.session});
|
||||
final EditorTimelineSession session;
|
||||
@override
|
||||
Widget build(BuildContext context) => AppDialog(
|
||||
title: context.l10n.backgroundTasks,
|
||||
width: 560,
|
||||
height: 520,
|
||||
child: BackgroundTasksContent(session: session),
|
||||
);
|
||||
}
|
||||
|
||||
class BackgroundTasksContent extends ConsumerWidget {
|
||||
const BackgroundTasksContent({
|
||||
super.key,
|
||||
this.session,
|
||||
this.registry,
|
||||
this.repository,
|
||||
}) : assert(session != null || registry != null);
|
||||
final EditorTimelineSession? session;
|
||||
final BackgroundTaskRegistry? registry;
|
||||
final ProcessingResourceRepository? repository;
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final snapshot = ref.watch(
|
||||
backgroundTasksProvider(registry: registry, session: session),
|
||||
);
|
||||
final resources = repository == null
|
||||
? null
|
||||
: ref.watch(processingResourcesProvider(repository!));
|
||||
final subtitleEntries = snapshot.subtitles;
|
||||
final removalEntries = snapshot.removals;
|
||||
final subtitleDownloading = resources?.subtitleDownloading == true;
|
||||
final resourceDownloads =
|
||||
resources?.installs
|
||||
.where(
|
||||
(install) =>
|
||||
(install.state == ProcessingResourceState.downloading &&
|
||||
!(subtitleDownloading &&
|
||||
ProcessingResourceRepository.subtitleCapabilities
|
||||
.contains(install.package.capability))) ||
|
||||
install.state == ProcessingResourceState.failed,
|
||||
)
|
||||
.toList() ??
|
||||
<ProcessingResourceInstall>[];
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (subtitleEntries.isEmpty &&
|
||||
!subtitleDownloading &&
|
||||
resourceDownloads.isEmpty &&
|
||||
removalEntries.isEmpty)
|
||||
SizedBox(
|
||||
key: const Key('background-tasks-empty-state'),
|
||||
height: AppMenuMetrics.rowHeight,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppMenuMetrics.iconGap,
|
||||
),
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.centerStart,
|
||||
child: Text(
|
||||
context.l10n.noBackgroundTasks,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
fontSize: AppMenuMetrics.fontSize,
|
||||
height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
Flexible(
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (subtitleDownloading)
|
||||
_ResourceDownloadCard(
|
||||
repository: repository!,
|
||||
subtitleBundle: true,
|
||||
),
|
||||
for (final (index, install) in resourceDownloads.indexed) ...[
|
||||
if (index > 0 || subtitleDownloading)
|
||||
const SizedBox(height: 2),
|
||||
_ResourceDownloadCard(
|
||||
repository: repository!,
|
||||
install: install,
|
||||
),
|
||||
],
|
||||
for (final (index, entry) in removalEntries.indexed) ...[
|
||||
if (index > 0 ||
|
||||
resourceDownloads.isNotEmpty ||
|
||||
subtitleDownloading)
|
||||
const SizedBox(height: 2),
|
||||
_BackgroundRemovalTaskCard(
|
||||
key: ValueKey(entry.task.id),
|
||||
entry: entry,
|
||||
),
|
||||
],
|
||||
for (final (index, entry)
|
||||
in subtitleEntries.reversed.indexed) ...[
|
||||
if (index > 0 ||
|
||||
resourceDownloads.isNotEmpty ||
|
||||
removalEntries.isNotEmpty ||
|
||||
subtitleDownloading)
|
||||
const SizedBox(height: 2),
|
||||
_SubtitleTaskCard(
|
||||
key: ValueKey(entry.job.recognition.id),
|
||||
entry: entry,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty
|
||||
? owner.timelineName
|
||||
: '${owner.projectName} · ${owner.timelineName}';
|
||||
|
||||
Future<void> _showTaskDetails(
|
||||
BuildContext context, {
|
||||
required WidgetBuilder builder,
|
||||
EditorTimelineSession? session,
|
||||
}) async {
|
||||
final release = session?.retainViews();
|
||||
try {
|
||||
await showAppDialog<void>(
|
||||
context: context,
|
||||
builder: (context) => AppDialog(
|
||||
title: context.l10n.backgroundTaskDetails,
|
||||
width: 560,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(context.l10n.close),
|
||||
),
|
||||
],
|
||||
child: builder(context),
|
||||
),
|
||||
);
|
||||
} finally {
|
||||
release?.call();
|
||||
}
|
||||
}
|
||||
|
||||
class _SubtitleTaskDetails extends ConsumerWidget {
|
||||
const _SubtitleTaskDetails(this.initial);
|
||||
final SubtitleTaskEntry initial;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final latest = ref.watch(
|
||||
backgroundTasksProvider(session: initial.owner.session).select(
|
||||
(snapshot) => snapshot.subtitles
|
||||
.where((entry) => entry.job.id == initial.job.id)
|
||||
.firstOrNull,
|
||||
),
|
||||
);
|
||||
if (latest == null) return Text(context.l10n.noBackgroundTasks);
|
||||
return _SubtitleTaskCard(
|
||||
entry: latest.copyWith(owner: initial.owner),
|
||||
details: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _RemovalTaskDetails extends ConsumerWidget {
|
||||
const _RemovalTaskDetails(this.initial);
|
||||
final RemovalTaskEntry initial;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final latest = ref.watch(
|
||||
backgroundTasksProvider(session: initial.owner.session).select(
|
||||
(snapshot) => snapshot.removals
|
||||
.where((entry) => entry.task.id == initial.task.id)
|
||||
.firstOrNull,
|
||||
),
|
||||
);
|
||||
if (latest == null) return Text(context.l10n.noBackgroundTasks);
|
||||
return _BackgroundRemovalTaskCard(
|
||||
entry: latest.copyWith(owner: initial.owner),
|
||||
details: true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TaskSummary extends StatelessWidget {
|
||||
const _TaskSummary({
|
||||
required this.name,
|
||||
required this.status,
|
||||
required this.onTap,
|
||||
this.active = false,
|
||||
this.progress,
|
||||
this.progressDetails,
|
||||
this.action,
|
||||
});
|
||||
final String name, status;
|
||||
final VoidCallback onTap;
|
||||
final bool active;
|
||||
final double? progress;
|
||||
final Widget? progressDetails;
|
||||
final Widget? action;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Material(
|
||||
type: MaterialType.transparency,
|
||||
borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius),
|
||||
clipBehavior: Clip.antiAlias,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius),
|
||||
hoverColor: AppSidebarColors.of(context).hover,
|
||||
highlightColor: Colors.transparent,
|
||||
splashColor: Colors.transparent,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(name, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
const SizedBox(height: 4),
|
||||
if (progressDetails case final details?)
|
||||
details
|
||||
else ...[
|
||||
Text(
|
||||
'$status${active && progress != null ? " · ${(progress! * 100).floor()}%" : ""}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
if (active) ...[
|
||||
const SizedBox(height: 6),
|
||||
LinearProgressIndicator(value: progress),
|
||||
],
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
?action,
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _BackgroundRemovalTaskCard extends StatelessWidget {
|
||||
const _BackgroundRemovalTaskCard({
|
||||
super.key,
|
||||
required this.entry,
|
||||
this.details = false,
|
||||
});
|
||||
|
||||
final RemovalTaskEntry entry;
|
||||
final bool details;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final total = entry.total;
|
||||
final completed = entry.completed;
|
||||
final progressValue = total == null || total <= 0 || completed == null
|
||||
? null
|
||||
: completed / total;
|
||||
final active = !entry.terminal;
|
||||
final status = switch (entry.status) {
|
||||
BackgroundRemovalStatus.queued => context.l10n.preparingMedia,
|
||||
BackgroundRemovalStatus.running => context.l10n.removeBackground,
|
||||
BackgroundRemovalStatus.applying =>
|
||||
context.l10n.backgroundRemovalApplying,
|
||||
BackgroundRemovalStatus.succeeded =>
|
||||
context.l10n.backgroundRemovalComplete,
|
||||
BackgroundRemovalStatus.failed => context.l10n.backgroundRemovalFailed,
|
||||
BackgroundRemovalStatus.cancelling => context.l10n.cancelling,
|
||||
BackgroundRemovalStatus.cancelled => context.l10n.cancelled,
|
||||
BackgroundRemovalStatus.interrupted => context.l10n.interruptedTask,
|
||||
};
|
||||
if (!details) {
|
||||
return _TaskSummary(
|
||||
name: entry.name,
|
||||
status: status,
|
||||
active: active,
|
||||
progress: progressValue,
|
||||
action: active
|
||||
? TextButton(
|
||||
onPressed: entry.status == BackgroundRemovalStatus.cancelling
|
||||
? null
|
||||
: () => entry.owner.session.backgroundRemovals.cancel(
|
||||
entry.task.id,
|
||||
),
|
||||
child: Text(context.l10n.cancel),
|
||||
)
|
||||
: null,
|
||||
onTap: () => _showTaskDetails(
|
||||
context,
|
||||
session: entry.owner.session,
|
||||
builder: (_) => _RemovalTaskDetails(entry),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(entry.name, style: Theme.of(context).textTheme.titleSmall),
|
||||
Text(
|
||||
_ownerName(entry.owner),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(status),
|
||||
if (entry.error case final error?)
|
||||
Text(
|
||||
context.l10n.errorMessage(error),
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
if (active) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
LinearProgressIndicator(value: progressValue),
|
||||
if (progressValue != null)
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Text('${(progressValue * 100).floor()}%'),
|
||||
),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: TextButton(
|
||||
onPressed: entry.status == BackgroundRemovalStatus.cancelling
|
||||
? null
|
||||
: () => entry.owner.session.backgroundRemovals.cancel(
|
||||
entry.task.id,
|
||||
),
|
||||
child: Text(context.l10n.cancel),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ResourceDownloadCard extends ConsumerWidget {
|
||||
const _ResourceDownloadCard({
|
||||
required this.repository,
|
||||
this.install,
|
||||
this.subtitleBundle = false,
|
||||
this.details = false,
|
||||
}) : assert(subtitleBundle || install != null);
|
||||
|
||||
final ProcessingResourceRepository repository;
|
||||
final ProcessingResourceInstall? install;
|
||||
final bool subtitleBundle;
|
||||
final bool details;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final snapshot = ref.watch(processingResourcesProvider(repository));
|
||||
final install = this.install == null
|
||||
? null
|
||||
: snapshot.installs
|
||||
.where((item) => item.package.id == this.install!.package.id)
|
||||
.firstOrNull ??
|
||||
this.install;
|
||||
final downloading = subtitleBundle
|
||||
? snapshot.subtitleDownloading
|
||||
: install!.state == ProcessingResourceState.downloading;
|
||||
final paused =
|
||||
downloading &&
|
||||
(subtitleBundle
|
||||
? snapshot.subtitlePaused
|
||||
: snapshot.paused.contains(install!.package.capability));
|
||||
final label = paused
|
||||
? context.l10n.downloadPaused
|
||||
: subtitleBundle
|
||||
? downloading
|
||||
? context.l10n.downloadingResource
|
||||
: context.l10n.backgroundTaskCompleted
|
||||
: switch (install!.state) {
|
||||
ProcessingResourceState.downloading =>
|
||||
context.l10n.downloadingResource,
|
||||
ProcessingResourceState.installed =>
|
||||
context.l10n.backgroundTaskCompleted,
|
||||
ProcessingResourceState.notInstalled => context.l10n.cancelled,
|
||||
ProcessingResourceState.failed => context.l10n.backgroundTaskFailed,
|
||||
};
|
||||
final name = subtitleBundle
|
||||
? context.l10n.subtitleResourceDownloadTask
|
||||
: install!.package.capability == ProcessingCapability.backgroundRemoval
|
||||
? context.l10n.backgroundRemovalDownloadTask
|
||||
: install.package.name;
|
||||
final downloadedBytes = subtitleBundle
|
||||
? snapshot.subtitleDownloadedBytes
|
||||
: install!.downloadedBytes;
|
||||
final totalBytes = subtitleBundle
|
||||
? snapshot.subtitleTotalBytes
|
||||
: install!.package.bytes;
|
||||
Future<void> cancel() async {
|
||||
if (!await confirmResourceDownloadCancellation(context)) return;
|
||||
if (subtitleBundle) {
|
||||
if (repository.subtitleDownloading) {
|
||||
repository.cancelSubtitleResources();
|
||||
}
|
||||
} else if (repository.installFor(install!.package.capability).state ==
|
||||
ProcessingResourceState.downloading) {
|
||||
repository.cancel(install.package.capability);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> retry() async {
|
||||
try {
|
||||
await repository.ensureAvailable(install!.package.capability);
|
||||
} catch (_) {
|
||||
// Repository publishes the error in task details.
|
||||
}
|
||||
}
|
||||
|
||||
void togglePause() {
|
||||
if (subtitleBundle) {
|
||||
if (paused) {
|
||||
repository.resumeSubtitleResources();
|
||||
} else {
|
||||
repository.pauseSubtitleResources();
|
||||
}
|
||||
} else if (paused) {
|
||||
repository.resumeDownload(install!.package.capability);
|
||||
} else {
|
||||
repository.pauseDownload(install!.package.capability);
|
||||
}
|
||||
}
|
||||
|
||||
if (!details) {
|
||||
return _TaskSummary(
|
||||
name: name,
|
||||
status: label,
|
||||
active: downloading,
|
||||
progressDetails: downloading
|
||||
? ResourceDownloadProgress(
|
||||
downloadedBytes: downloadedBytes,
|
||||
totalBytes: totalBytes,
|
||||
bytesPerSecond: subtitleBundle
|
||||
? snapshot.subtitleBytesPerSecond
|
||||
: snapshot.rates[install!.package.capability] ?? 0,
|
||||
status: paused ? label : '',
|
||||
paused: paused,
|
||||
)
|
||||
: null,
|
||||
action: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (downloading)
|
||||
TextButton(
|
||||
key: const Key('background-download-pause-button'),
|
||||
onPressed: togglePause,
|
||||
child: Text(
|
||||
paused
|
||||
? context.l10n.resumeDownload
|
||||
: context.l10n.pauseDownload,
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: downloading ? cancel : retry,
|
||||
child: Text(
|
||||
downloading ? context.l10n.cancel : context.l10n.retryTask,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: () {
|
||||
final download = ref.read(subtitleDownloadProvider);
|
||||
final activeDownload =
|
||||
subtitleBundle &&
|
||||
download.running &&
|
||||
download.request?.session.acceptsEdits == true
|
||||
? download.request
|
||||
: null;
|
||||
if (activeDownload != null) {
|
||||
showAppDialog<void>(
|
||||
context: context,
|
||||
builder: (_) => TranscriptionDialog.forCurrentTask(
|
||||
session: activeDownload.session,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
_showTaskDetails(
|
||||
context,
|
||||
builder: (_) => _ResourceDownloadCard(
|
||||
repository: repository,
|
||||
install: subtitleBundle
|
||||
? null
|
||||
: repository.installFor(install!.package.capability),
|
||||
subtitleBundle: subtitleBundle,
|
||||
details: true,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(name, style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
if (!downloading) Text(label),
|
||||
if (install?.error != null)
|
||||
Text(context.l10n.failureMessage(install!.error!)),
|
||||
if (downloading) ...[
|
||||
ResourceDownloadProgress(
|
||||
downloadedBytes: downloadedBytes,
|
||||
totalBytes: totalBytes,
|
||||
bytesPerSecond: subtitleBundle
|
||||
? snapshot.subtitleBytesPerSecond
|
||||
: snapshot.rates[install!.package.capability] ?? 0,
|
||||
status: paused ? label : '',
|
||||
paused: paused,
|
||||
),
|
||||
],
|
||||
if (downloading || install?.state == ProcessingResourceState.failed)
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (downloading)
|
||||
TextButton(
|
||||
onPressed: togglePause,
|
||||
child: Text(
|
||||
paused
|
||||
? context.l10n.resumeDownload
|
||||
: context.l10n.pauseDownload,
|
||||
),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: downloading ? cancel : retry,
|
||||
child: Text(
|
||||
downloading ? context.l10n.cancel : context.l10n.retryTask,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SubtitleTaskCard extends ConsumerStatefulWidget {
|
||||
const _SubtitleTaskCard({
|
||||
super.key,
|
||||
required this.entry,
|
||||
this.details = false,
|
||||
});
|
||||
final SubtitleTaskEntry entry;
|
||||
EditorTimelineSession get session => entry.owner.session;
|
||||
SubtitleBackgroundTask get job => entry.job;
|
||||
final bool details;
|
||||
TranscriptionClipTarget? get target => job.recognition.command.clipId == null
|
||||
? null
|
||||
: TranscriptionClipTarget(
|
||||
sequence: job.sequence,
|
||||
clipId: job.recognition.command.clipId!,
|
||||
mediaId: job.recognition.command.mediaId,
|
||||
name: entry.name,
|
||||
audioStream: job.recognition.command.audioStream,
|
||||
);
|
||||
@override
|
||||
ConsumerState<_SubtitleTaskCard> createState() => _SubtitleTaskCardState();
|
||||
}
|
||||
|
||||
class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
|
||||
SubtitleTaskActionsProvider get _provider =>
|
||||
subtitleTaskActionsProvider(widget.session, widget.job.id);
|
||||
SubtitleTaskActions get _actions => ref.read(_provider.notifier);
|
||||
bool get _picking => ref.read(_provider).isLoading;
|
||||
String? _validationError;
|
||||
String? get _error {
|
||||
final value = ref.read(_provider);
|
||||
if (_validationError != null) return _validationError;
|
||||
if (value.error case SubtitleActionException(:final kind, :final cause)) {
|
||||
if (cause is CommandRejected && cause.code == 'staleVersion') {
|
||||
return context.l10n.timelineChanged;
|
||||
}
|
||||
final message = context.l10n.errorMessage(cause);
|
||||
return switch (kind) {
|
||||
SubtitleActionKind.original => context.l10n.applyCaptionsError(message),
|
||||
SubtitleActionKind.translation =>
|
||||
context.l10n.applyTranslatedCaptionsError(message),
|
||||
_ => message,
|
||||
};
|
||||
}
|
||||
final result = value.value;
|
||||
return switch (result?.kind) {
|
||||
SubtitleActionKind.original => context.l10n.captionsAdded(
|
||||
result!.cueCount.toString(),
|
||||
),
|
||||
SubtitleActionKind.translation => context.l10n.translatedCaptionsAdded(
|
||||
result!.cueCount.toString(),
|
||||
),
|
||||
_ => null,
|
||||
};
|
||||
}
|
||||
|
||||
Future<void> _applyResult({bool translated = false}) async {
|
||||
if (_picking) return;
|
||||
final job = widget.job;
|
||||
final version = widget.session.version;
|
||||
String? clip = widget.target?.clipId;
|
||||
if (clip == null) {
|
||||
final candidates = await _actions.candidates(job, translated: translated);
|
||||
if (!mounted) return;
|
||||
if (candidates.isEmpty) {
|
||||
setState(
|
||||
() => _validationError = translated
|
||||
? context.l10n.placeTranslationMediaFirst
|
||||
: context.l10n.placeMediaFirst,
|
||||
);
|
||||
return;
|
||||
}
|
||||
clip = await showAppDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AppDialog(
|
||||
title: context.l10n.selectTargetClip,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final candidate in candidates)
|
||||
AppDialogOption(
|
||||
label:
|
||||
'${candidate.name ?? context.l10n.clip} · ${candidate.id.value}',
|
||||
onPressed: () => Navigator.pop(context, candidate.id.value),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (clip == null || !mounted) return;
|
||||
setState(() => _validationError = null);
|
||||
await _actions.apply(
|
||||
job,
|
||||
clip,
|
||||
expectedVersion: version,
|
||||
translated: translated,
|
||||
);
|
||||
}
|
||||
|
||||
String _failureMessage(String? code) => switch (code) {
|
||||
'notConfigured' => context.l10n.transcriptionAccessFailed,
|
||||
'noAudio' => context.l10n.transcriptionNoAudio,
|
||||
'invalidResult' => context.l10n.transcriptionInvalidResult,
|
||||
'workerExited' => context.l10n.transcriptionWorkerExited,
|
||||
'processingFailed' => context.l10n.transcriptionProcessingFailed,
|
||||
final value? => context.l10n.transcriptionError(value),
|
||||
null => context.l10n.transcriptionFailed,
|
||||
};
|
||||
|
||||
Future<void> _action(Future<void> Function() action) async {
|
||||
setState(() => _validationError = null);
|
||||
await action();
|
||||
if (mounted && !widget.details && _error != null) {
|
||||
ScaffoldMessenger.maybeOf(context)
|
||||
?.showSnackBar(SnackBar(content: Text(_error!)));
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(_provider);
|
||||
final job = widget.job;
|
||||
final taskSession = widget.session;
|
||||
final entry = widget.entry;
|
||||
final total = entry.total;
|
||||
final completed = entry.completed;
|
||||
final value = total == null || total <= 0 || completed == null
|
||||
? null
|
||||
: (completed / total).clamp(0.0, 1.0);
|
||||
final status = entry.status;
|
||||
final failure = entry.error;
|
||||
final label = switch (status) {
|
||||
TranscriptionStatus.queued =>
|
||||
!entry.hasTranslation
|
||||
? context.l10n.preparingMedia
|
||||
: context.l10n.preparingTranslation,
|
||||
TranscriptionStatus.running =>
|
||||
!entry.hasTranslation
|
||||
? context.l10n.transcribing
|
||||
: context.l10n.translatingCaptions,
|
||||
TranscriptionStatus.cancelling => context.l10n.cancelling,
|
||||
TranscriptionStatus.succeeded =>
|
||||
entry.followingUp
|
||||
? context.l10n.preparingTranslation
|
||||
: context.l10n.captionsGenerated,
|
||||
TranscriptionStatus.failed =>
|
||||
failure == 'sourceLanguageUnknown'
|
||||
? context.l10n.sourceLanguageUnknown
|
||||
: _failureMessage(failure),
|
||||
TranscriptionStatus.cancelled => context.l10n.cancelled,
|
||||
TranscriptionStatus.interrupted => context.l10n.interruptedTask,
|
||||
};
|
||||
if (!widget.details) {
|
||||
return _TaskSummary(
|
||||
name: entry.name,
|
||||
status: status == TranscriptionStatus.failed
|
||||
? context.l10n.backgroundTaskFailed
|
||||
: entry.recognitionAvailable &&
|
||||
entry.terminal &&
|
||||
status == TranscriptionStatus.succeeded
|
||||
? '$label · ${context.l10n.captionCount(entry.resultCues.length)}'
|
||||
: label,
|
||||
active: !entry.terminal,
|
||||
progress: entry.followingUp && entry.recognitionTerminal ? null : value,
|
||||
action: !entry.terminal
|
||||
? TextButton(
|
||||
onPressed: _picking
|
||||
? null
|
||||
: () => _action(() => _actions.cancel(job)),
|
||||
child: Text(context.l10n.cancel),
|
||||
)
|
||||
: status == TranscriptionStatus.failed ||
|
||||
status == TranscriptionStatus.interrupted ||
|
||||
status == TranscriptionStatus.cancelled
|
||||
? TextButton(
|
||||
onPressed: _picking || !taskSession.acceptsEdits
|
||||
? null
|
||||
: () => _action(() => _actions.retry(job)),
|
||||
child: Text(context.l10n.retryTask),
|
||||
)
|
||||
: null,
|
||||
onTap: () => _showTaskDetails(
|
||||
context,
|
||||
session: taskSession,
|
||||
builder: (_) => _SubtitleTaskDetails(entry),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(entry.name, style: Theme.of(context).textTheme.titleSmall),
|
||||
Text(
|
||||
_ownerName(entry.owner),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(label),
|
||||
if (!entry.terminal) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
LinearProgressIndicator(
|
||||
value: entry.followingUp && entry.recognitionTerminal
|
||||
? null
|
||||
: value,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
if (!entry.hasTranslation)
|
||||
Text(context.l10n.recognizedCaptions(entry.recognizedCues)),
|
||||
if (value != null &&
|
||||
!(entry.followingUp && entry.recognitionTerminal))
|
||||
Text('${(value * 100).floor()}%'),
|
||||
if (!entry.hasTranslation && entry.recentCues.isNotEmpty)
|
||||
Text(entry.recentCues.join('\n')),
|
||||
],
|
||||
Text(
|
||||
'${context.l10n.sourceLanguage}: ${context.l10n.subtitleLanguageName(entry.sourceLanguage)}',
|
||||
),
|
||||
if (entry.targetLanguage != 'none')
|
||||
Text(
|
||||
'${context.l10n.translationLanguage}: ${context.l10n.subtitleLanguageName(entry.targetLanguage)}',
|
||||
),
|
||||
if (entry.recognitionAvailable) ...[
|
||||
Text(context.l10n.captionCount(entry.recognizedCues)),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
SizedBox(
|
||||
height: 160,
|
||||
child: ListView.builder(
|
||||
primary: false,
|
||||
itemCount: entry.resultCues.length,
|
||||
itemBuilder: (context, index) => Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: SelectableText(entry.resultCues[index]),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
if (_error != null) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(_error!),
|
||||
],
|
||||
Wrap(
|
||||
alignment: WrapAlignment.end,
|
||||
spacing: 8,
|
||||
children: [
|
||||
if (!entry.terminal)
|
||||
TextButton(
|
||||
onPressed: _picking
|
||||
? null
|
||||
: () => _action(() => _actions.cancel(job)),
|
||||
child: Text(context.l10n.cancel),
|
||||
),
|
||||
if (entry.terminal &&
|
||||
(status == TranscriptionStatus.failed ||
|
||||
status == TranscriptionStatus.interrupted ||
|
||||
status == TranscriptionStatus.cancelled))
|
||||
TextButton(
|
||||
onPressed: _picking || !widget.session.acceptsEdits
|
||||
? null
|
||||
: () => _action(() => _actions.retry(job)),
|
||||
child: Text(context.l10n.retryTask),
|
||||
),
|
||||
if (entry.recognitionAvailable)
|
||||
TextButton(
|
||||
onPressed: _picking || !widget.session.acceptsEdits
|
||||
? null
|
||||
: _applyResult,
|
||||
child: Text(context.l10n.applyOriginalCaptions),
|
||||
),
|
||||
if (entry.translationAvailable)
|
||||
TextButton(
|
||||
onPressed: _picking || !widget.session.acceptsEdits
|
||||
? null
|
||||
: () => _applyResult(translated: true),
|
||||
child: Text(context.l10n.applyTranslatedCaptions),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/runtime/media_presentations.dart';
|
||||
|
||||
/// Subscribes to one cover frame so loading it only rebuilds its image.
|
||||
class MediaAssetCover extends ConsumerWidget {
|
||||
const MediaAssetCover({
|
||||
super.key,
|
||||
required this.asset,
|
||||
required this.fallback,
|
||||
this.errorFallback,
|
||||
this.fit = BoxFit.contain,
|
||||
this.timeMilliseconds = 0,
|
||||
});
|
||||
|
||||
final AssetDocument asset;
|
||||
final Widget fallback;
|
||||
final Widget? errorFallback;
|
||||
final BoxFit fit;
|
||||
final int timeMilliseconds;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final bytes = ref
|
||||
.watch(mediaCoverProvider(asset, timeMilliseconds: timeMilliseconds))
|
||||
.value;
|
||||
return bytes == null
|
||||
? fallback
|
||||
: Image.memory(
|
||||
bytes,
|
||||
fit: fit,
|
||||
excludeFromSemantics: true,
|
||||
errorBuilder: (_, _, _) => errorFallback ?? fallback,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
/// Drag data carries identities; feedback switches off inside the timeline.
|
||||
class MediaAssetDrag {
|
||||
MediaAssetDrag({required this.projectId, required this.assetId});
|
||||
final String projectId;
|
||||
final String assetId;
|
||||
final feedbackVisible = ValueNotifier<bool>(true);
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/runtime/media_presentations.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import 'audio_asset_tile.dart';
|
||||
import 'media_asset_cover.dart';
|
||||
|
||||
/// Compact full-width preview used by the media library's list layout.
|
||||
class MediaAssetStrip extends StatelessWidget {
|
||||
const MediaAssetStrip({super.key, required this.asset});
|
||||
static const height = 46.0;
|
||||
final AssetDocument asset;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => SizedBox(
|
||||
height: height,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
if (asset.metadata['kind'] == 'audio') {
|
||||
return AudioAssetTile(
|
||||
asset: asset,
|
||||
showName: false,
|
||||
aspectRatio: constraints.maxWidth / height,
|
||||
);
|
||||
}
|
||||
|
||||
return _VisualAssetStrip(asset: asset, width: constraints.maxWidth);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _VisualAssetStrip extends ConsumerWidget {
|
||||
const _VisualAssetStrip({required this.asset, required this.width});
|
||||
final AssetDocument asset;
|
||||
final double width;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final video = asset.metadata['kind'] == 'video';
|
||||
final duration = video
|
||||
? ref.watch(mediaDurationProvider(asset)).value
|
||||
: null;
|
||||
final count = (width / (MediaAssetStrip.height * 16 / 9)).ceil().clamp(
|
||||
1,
|
||||
16,
|
||||
);
|
||||
return ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (var index = 0; index < count; index++)
|
||||
Expanded(
|
||||
child: MediaAssetCover(
|
||||
asset: asset,
|
||||
fit: BoxFit.cover,
|
||||
timeMilliseconds: video && duration != null
|
||||
? (duration * 1000 * index / count).floor()
|
||||
: 0,
|
||||
fallback: const Center(child: Icon(Icons.movie_outlined)),
|
||||
errorFallback: const Center(
|
||||
child: Icon(Icons.broken_image_outlined),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class MediaAssetDuration extends ConsumerWidget {
|
||||
const MediaAssetDuration({super.key, required this.asset});
|
||||
final AssetDocument asset;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (!const {'audio', 'video'}.contains(asset.metadata['kind'])) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final duration = ref.watch(mediaDurationProvider(asset)).value;
|
||||
if (duration == null) return const SizedBox.shrink();
|
||||
final seconds = math.max(0, duration.floor());
|
||||
final hours = seconds ~/ 3600;
|
||||
final minutes = hours > 0 ? (seconds ~/ 60) % 60 : seconds ~/ 60;
|
||||
final text =
|
||||
'${hours > 0 ? '$hours:' : ''}'
|
||||
'${minutes.toString().padLeft(2, '0')}:'
|
||||
'${(seconds % 60).toString().padLeft(2, '0')}';
|
||||
return DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.black.withValues(alpha: .55),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
|
||||
child: Text(
|
||||
text,
|
||||
key: ValueKey('media-duration-${asset.id}'),
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.white,
|
||||
fontFeatures: const [FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/media_availability.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import 'audio_asset_tile.dart';
|
||||
import 'media_asset_drag.dart';
|
||||
import 'media_asset_strip.dart';
|
||||
import 'media_browser_controller.dart';
|
||||
import 'unavailable_media_placeholder.dart';
|
||||
import 'visual_asset_tile.dart';
|
||||
|
||||
extension MediaFilterLabel on MediaFilter {
|
||||
String label(BuildContext context) => switch (this) {
|
||||
MediaFilter.all => context.l10n.all,
|
||||
MediaFilter.image => context.l10n.picture,
|
||||
MediaFilter.video => context.l10n.video,
|
||||
MediaFilter.audio => context.l10n.audio,
|
||||
};
|
||||
}
|
||||
|
||||
const maximumMediaGridTileWidth = 160.0;
|
||||
|
||||
class MediaBrowserBody extends ConsumerStatefulWidget {
|
||||
const MediaBrowserBody({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.grid,
|
||||
this.draggable = false,
|
||||
});
|
||||
final String projectId;
|
||||
final bool grid;
|
||||
final bool draggable;
|
||||
@override
|
||||
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
|
||||
}
|
||||
|
||||
class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
|
||||
with WidgetsBindingObserver {
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
if (state == AppLifecycleState.resumed) {
|
||||
ref.invalidate(mediaAvailabilityProvider);
|
||||
}
|
||||
}
|
||||
|
||||
MediaBrowserController get _browser =>
|
||||
ref.read(mediaBrowserProvider(widget.projectId));
|
||||
bool get _checkingDrop => _browser.busy;
|
||||
String? get _selectedAssetId => _browser.selectedAssetId;
|
||||
set _selectedAssetId(String? value) => _browser.selectedAssetId = value;
|
||||
MediaFilter get _filter => _browser.filter;
|
||||
bool get _isGrid => widget.grid;
|
||||
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
|
||||
|
||||
Future<void> _action(Future<bool> Function() action) async {
|
||||
final ok = await action();
|
||||
if (!mounted || ok) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
context.l10n.failureMessage(
|
||||
ref.read(projectsProvider).asData?.value.error ??
|
||||
const AppFailure(AppErrorCode.operationFailed),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _rename(AssetDocument asset) async {
|
||||
final controller = TextEditingController(text: asset.name);
|
||||
final name = await showAppDialog<String>(
|
||||
context: context,
|
||||
builder: (context) => AppDialog(
|
||||
title: context.l10n.renameMedia,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(context.l10n.cancel),
|
||||
),
|
||||
ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (context, _) => FilledButton(
|
||||
onPressed: controller.text.trim().isEmpty
|
||||
? null
|
||||
: () => Navigator.pop(context, controller.text.trim()),
|
||||
child: Text(context.l10n.save),
|
||||
),
|
||||
),
|
||||
],
|
||||
child: AppField(
|
||||
label: context.l10n.name,
|
||||
child: TextField(
|
||||
controller: controller,
|
||||
autofocus: true,
|
||||
onSubmitted: (value) {
|
||||
if (value.trim().isNotEmpty) Navigator.pop(context, value.trim());
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
// The route's closing animation can still read its text controller.
|
||||
await Future<void>.delayed(const Duration(milliseconds: 200));
|
||||
controller.dispose();
|
||||
if (!mounted || name == null) return;
|
||||
await _action(() => _browser.rename(asset, name));
|
||||
}
|
||||
|
||||
Future<void> _remove(AssetDocument asset) async {
|
||||
final confirmed = await showAppDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AppDialog(
|
||||
title: context.l10n.removeMedia,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text(context.l10n.cancel),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: TextButton.styleFrom(
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
child: Text(context.l10n.remove),
|
||||
),
|
||||
],
|
||||
child: Text(context.l10n.removeMediaConfirmation(asset.name)),
|
||||
),
|
||||
);
|
||||
if (!mounted || confirmed != true) return;
|
||||
await _action(() => _browser.remove(asset));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: ref.watch(mediaBrowserProvider(widget.projectId)),
|
||||
builder: (context, _) => _buildBrowser(context),
|
||||
);
|
||||
Widget _buildBrowser(BuildContext context) {
|
||||
ref.watch(externalMediaImportProvider(widget.projectId));
|
||||
final workspace = ref.watch(projectsProvider).asData?.value;
|
||||
final active = workspace?.activeProject?.id == widget.projectId;
|
||||
final allAssets = active ? workspace!.assets : <AssetDocument>[];
|
||||
final assets = _filter == MediaFilter.all
|
||||
? allAssets
|
||||
: allAssets
|
||||
.where((asset) => asset.metadata['kind'] == _filter.kind)
|
||||
.toList();
|
||||
final timelineId = active ? workspace?.timeline?.id : null;
|
||||
final timeline = timelineId == null
|
||||
? null
|
||||
: ref
|
||||
.watch(editorTimelineProvider(widget.projectId, timelineId))
|
||||
.asData
|
||||
?.value;
|
||||
return assets.isEmpty
|
||||
? Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.medium),
|
||||
child: Text(
|
||||
_filter != MediaFilter.all
|
||||
? context.l10n.noMediaOfType(_filter.label(context))
|
||||
: _desktop
|
||||
? context.l10n.dragMediaHint
|
||||
: context.l10n.noMedia,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
)
|
||||
: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
const spacing = AppSpacing.small;
|
||||
final width = math.max(
|
||||
1.0,
|
||||
constraints.maxWidth - AppSpacing.compact * 2,
|
||||
);
|
||||
final columns = math.max(
|
||||
1,
|
||||
((width + spacing) / (maximumMediaGridTileWidth + spacing))
|
||||
.ceil(),
|
||||
);
|
||||
final tileWidth = (width - spacing * (columns - 1)) / columns;
|
||||
final textStyle = Theme.of(context).textTheme.bodySmall!;
|
||||
final labelHeight =
|
||||
MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) *
|
||||
(textStyle.height ?? 1.2);
|
||||
Widget item(BuildContext context, int index) {
|
||||
final asset = assets[index];
|
||||
return Consumer(
|
||||
builder: (context, ref, _) {
|
||||
final availability = ref
|
||||
.watch(
|
||||
mediaAvailabilityProvider(widget.projectId, asset),
|
||||
)
|
||||
.asData
|
||||
?.value;
|
||||
final unavailable =
|
||||
availability != null &&
|
||||
availability != MediaAvailability.available;
|
||||
return AppContextMenu(
|
||||
key: ValueKey(('media-menu', asset.id)),
|
||||
itemsBuilder: (_) {
|
||||
final available = ref
|
||||
.read(projectsProvider)
|
||||
.asData
|
||||
?.value;
|
||||
final canEdit =
|
||||
available?.activeProject?.id == widget.projectId &&
|
||||
available?.projectBusy == false &&
|
||||
!_checkingDrop;
|
||||
final sequence = timeline?.activeSequenceId;
|
||||
return [
|
||||
AppMenuItem(
|
||||
label: context.l10n.addToTimeline,
|
||||
icon: Icons.add,
|
||||
onPressed:
|
||||
canEdit &&
|
||||
!unavailable &&
|
||||
sequence != null &&
|
||||
available?.timeline?.id == timelineId
|
||||
? () =>
|
||||
_action(() => _browser.insertAsset(asset))
|
||||
: null,
|
||||
),
|
||||
AppMenuItem(
|
||||
label: context.l10n.rename,
|
||||
icon: Icons.drive_file_rename_outline,
|
||||
onPressed: canEdit ? () => _rename(asset) : null,
|
||||
),
|
||||
AppMenuItem(
|
||||
label: defaultTargetPlatform == TargetPlatform.macOS
|
||||
? context.l10n.revealFinder
|
||||
: context.l10n.revealFileManager,
|
||||
icon: Icons.folder_open,
|
||||
onPressed: canEdit && _desktop
|
||||
? () => _action(() => _browser.reveal(asset))
|
||||
: null,
|
||||
),
|
||||
const AppMenuSeparator(),
|
||||
AppMenuItem(
|
||||
label: context.l10n.removeMedia,
|
||||
icon: Icons.delete_outline,
|
||||
destructive: true,
|
||||
onPressed: canEdit ? () => _remove(asset) : null,
|
||||
),
|
||||
];
|
||||
},
|
||||
child: Listener(
|
||||
onPointerDown: (event) {
|
||||
if (event.buttons == 2) {
|
||||
setState(() => _selectedAssetId = asset.id);
|
||||
}
|
||||
},
|
||||
child: _SelectableAsset(
|
||||
key: ValueKey(asset.id),
|
||||
grid: _isGrid,
|
||||
drag: MediaAssetDrag(
|
||||
projectId: widget.projectId,
|
||||
assetId: asset.id,
|
||||
),
|
||||
name: asset.name,
|
||||
draggable:
|
||||
widget.draggable &&
|
||||
!workspace!.projectBusy &&
|
||||
!_checkingDrop &&
|
||||
!unavailable,
|
||||
selected: _selectedAssetId == asset.id,
|
||||
onTap: () => _browser.selectAsset(asset),
|
||||
child: _assetTile(asset, availability),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return ScrollEdgeFadeBuilder(
|
||||
key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)),
|
||||
builder: (controller) => !_isGrid
|
||||
? ListView.separated(
|
||||
key: PageStorageKey(('media-list', widget.projectId)),
|
||||
controller: controller,
|
||||
padding: const EdgeInsets.all(AppSpacing.compact),
|
||||
itemCount: assets.length,
|
||||
itemBuilder: item,
|
||||
separatorBuilder: (_, _) =>
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
)
|
||||
: GridView.builder(
|
||||
key: PageStorageKey(('media-grid', widget.projectId)),
|
||||
controller: controller,
|
||||
padding: const EdgeInsets.all(AppSpacing.compact),
|
||||
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: columns,
|
||||
crossAxisSpacing: spacing,
|
||||
mainAxisSpacing: AppSpacing.compact,
|
||||
mainAxisExtent:
|
||||
tileWidth * 9 / 16 +
|
||||
AppSpacing.small +
|
||||
labelHeight +
|
||||
2,
|
||||
),
|
||||
itemCount: assets.length,
|
||||
itemBuilder: item,
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _assetTile(AssetDocument asset, MediaAvailability? availability) {
|
||||
final unavailable =
|
||||
availability != null && availability != MediaAvailability.available;
|
||||
final cover = unavailable
|
||||
? AspectRatio(
|
||||
aspectRatio: 16 / 9,
|
||||
child: _isGrid
|
||||
? UnavailableMediaPlaceholder(availability: availability)
|
||||
: ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: Center(
|
||||
child: Text(
|
||||
availability == MediaAvailability.missing
|
||||
? context.l10n.mediaMissing
|
||||
: context.l10n.mediaUnavailable,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: !_isGrid &&
|
||||
const {'audio', 'video', 'image'}.contains(asset.metadata['kind'])
|
||||
? MediaAssetStrip(asset: asset)
|
||||
: switch (asset.metadata['kind']) {
|
||||
'video' ||
|
||||
'image' => VisualAssetTile(asset: asset, showName: false),
|
||||
'audio' => AudioAssetTile(asset: asset, showName: false),
|
||||
_ => AspectRatio(
|
||||
aspectRatio: 16 / 9,
|
||||
child: ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: const Icon(Icons.insert_drive_file_outlined),
|
||||
),
|
||||
),
|
||||
};
|
||||
final name = Tooltip(
|
||||
// Hover still shows the full name; touch long press belongs to actions.
|
||||
triggerMode: TooltipTriggerMode.manual,
|
||||
message: asset.name,
|
||||
child: Text(
|
||||
asset.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ClipRRect(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
child: Stack(
|
||||
children: [
|
||||
if (!_isGrid)
|
||||
SizedBox(height: MediaAssetStrip.height, child: cover)
|
||||
else
|
||||
cover,
|
||||
Positioned(
|
||||
top: 4,
|
||||
right: 4,
|
||||
child: MediaAssetDuration(asset: asset),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
name,
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SelectableAsset extends StatelessWidget {
|
||||
const _SelectableAsset({
|
||||
super.key,
|
||||
required this.grid,
|
||||
required this.selected,
|
||||
required this.drag,
|
||||
required this.name,
|
||||
required this.draggable,
|
||||
required this.onTap,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final bool selected;
|
||||
final bool grid;
|
||||
final MediaAssetDrag drag;
|
||||
final String name;
|
||||
final bool draggable;
|
||||
final VoidCallback onTap;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final selectionDecoration = BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
border: Border.all(color: Theme.of(context).colorScheme.primary),
|
||||
);
|
||||
final tile = Semantics(
|
||||
selected: selected,
|
||||
child: InkWell(
|
||||
onTap: onTap,
|
||||
hoverColor: Colors.transparent,
|
||||
highlightColor: Colors.transparent,
|
||||
splashFactory: NoSplash.splashFactory,
|
||||
child: Stack(
|
||||
children: [
|
||||
child,
|
||||
if (selected && !grid)
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
height: MediaAssetStrip.height,
|
||||
child: IgnorePointer(
|
||||
child: DecoratedBox(decoration: selectionDecoration),
|
||||
),
|
||||
),
|
||||
if (selected && grid)
|
||||
Positioned(
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 0,
|
||||
child: IgnorePointer(
|
||||
child: AspectRatio(
|
||||
aspectRatio: 16 / 9,
|
||||
child: DecoratedBox(decoration: selectionDecoration),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
return Draggable<MediaAssetDrag>(
|
||||
data: drag,
|
||||
maxSimultaneousDrags: draggable ? 1 : 0,
|
||||
dragAnchorStrategy: pointerDragAnchorStrategy,
|
||||
onDragStarted: onTap,
|
||||
onDragEnd: (_) => drag.feedbackVisible.value = true,
|
||||
feedback: ValueListenableBuilder<bool>(
|
||||
valueListenable: drag.feedbackVisible,
|
||||
builder: (context, visible, child) =>
|
||||
visible ? child! : const SizedBox.shrink(),
|
||||
child: Material(
|
||||
elevation: 4,
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHigh,
|
||||
child: SizedBox(
|
||||
width: 144,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.small),
|
||||
child: Text(
|
||||
name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: tile,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import '../../integrations/platform/file_picker.dart';
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
import '../../workspace/media_file_extensions.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/media_availability.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
import '../../workspace/media_import_feedback.dart';
|
||||
import '../../workspace/preview_target.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
enum MediaFilter {
|
||||
all(null),
|
||||
image('image'),
|
||||
video('video'),
|
||||
audio('audio');
|
||||
|
||||
const MediaFilter(this.kind);
|
||||
final String? kind;
|
||||
}
|
||||
|
||||
final mediaBrowserProvider = Provider.family<MediaBrowserController, String>((
|
||||
ref,
|
||||
projectId,
|
||||
) {
|
||||
final controller = MediaBrowserController(ref, projectId);
|
||||
ref.onDispose(controller.dispose);
|
||||
return controller;
|
||||
});
|
||||
|
||||
/// Project-specific browsing choices are shared by every media presentation.
|
||||
class MediaBrowserController extends ChangeNotifier {
|
||||
MediaBrowserController(this._ref, this.projectId);
|
||||
final Ref _ref;
|
||||
final String projectId;
|
||||
final feedback = MediaImportFeedbackController();
|
||||
bool _working = false;
|
||||
bool _disposed = false;
|
||||
bool get busy =>
|
||||
_working || _ref.read(externalMediaImportProvider(projectId)).isLoading;
|
||||
bool get active =>
|
||||
!_disposed &&
|
||||
_ref.mounted &&
|
||||
_ref.read(projectsProvider).value?.activeProject?.id == projectId;
|
||||
bool get canEdit =>
|
||||
active &&
|
||||
_ref.read(projectsProvider).value?.projectBusy == false &&
|
||||
!busy;
|
||||
bool get canImport =>
|
||||
canEdit && _ref.read(platformCapabilitiesProvider).localFileSelection;
|
||||
|
||||
Future<ExternalMediaSelection?> pickFiles() => _import(
|
||||
() => _ref
|
||||
.read(filePickerProvider)
|
||||
.pickFiles(allowedExtensions: selectableMediaFileExtensions),
|
||||
);
|
||||
|
||||
Future<ExternalMediaSelection?> importFiles(List<ExternalMediaFile> files) =>
|
||||
_import(() async => files);
|
||||
|
||||
Future<ExternalMediaSelection?> _import(
|
||||
Future<List<ExternalMediaFile>> Function() select,
|
||||
) async {
|
||||
if (!canImport) return null;
|
||||
_working = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
final files = await select();
|
||||
if (!active ||
|
||||
files.isEmpty ||
|
||||
_ref.read(projectsProvider).value?.projectBusy != false) {
|
||||
return null;
|
||||
}
|
||||
final result = await _ref
|
||||
.read(externalMediaImportProvider(projectId).notifier)
|
||||
.importFiles(files);
|
||||
final asset = result?.selected.firstOrNull;
|
||||
if (!_disposed && asset != null) {
|
||||
_selectedAssetId = asset.id;
|
||||
if (_filter != MediaFilter.all &&
|
||||
asset.metadata['kind'] != _filter.kind) {
|
||||
_filter = MediaFilter.all;
|
||||
}
|
||||
}
|
||||
if (!_disposed) feedback.recordResult(result);
|
||||
return result;
|
||||
} catch (_) {
|
||||
if (!_disposed) feedback.recordFailure();
|
||||
rethrow;
|
||||
} finally {
|
||||
_working = false;
|
||||
if (!_disposed) notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
void selectAsset(AssetDocument asset) {
|
||||
selectedAssetId = asset.id;
|
||||
_ref.invalidate(mediaAvailabilityProvider(projectId, asset));
|
||||
final timeline = _ref.read(projectsProvider).value?.timeline;
|
||||
if (timeline != null) {
|
||||
_ref
|
||||
.read(previewNavigationProvider(projectId, timeline.id).notifier)
|
||||
.showAsset(asset);
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> rename(AssetDocument asset, String name) async =>
|
||||
canEdit &&
|
||||
await _ref
|
||||
.read(projectsProvider.notifier)
|
||||
.editMediaAsset(projectId, asset.id, name: name);
|
||||
|
||||
Future<bool> remove(AssetDocument asset) async {
|
||||
if (!canEdit) return false;
|
||||
final removed = await _ref
|
||||
.read(projectsProvider.notifier)
|
||||
.editMediaAsset(projectId, asset.id);
|
||||
if (removed && !_disposed && _selectedAssetId == asset.id) {
|
||||
selectedAssetId = null;
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
Future<bool> reveal(AssetDocument asset) async =>
|
||||
canEdit &&
|
||||
await _ref
|
||||
.read(projectsProvider.notifier)
|
||||
.revealMediaAsset(projectId, asset);
|
||||
|
||||
Future<bool> insertAsset(AssetDocument asset) async {
|
||||
if (!canEdit ||
|
||||
_ref.read(mediaAvailabilityProvider(projectId, asset)).value !=
|
||||
MediaAvailability.available) {
|
||||
return false;
|
||||
}
|
||||
final timelineId = _ref.read(projectsProvider).value?.timeline?.id;
|
||||
if (timelineId == null) return false;
|
||||
final session = _ref
|
||||
.read(editorTimelineProvider(projectId, timelineId))
|
||||
.value;
|
||||
final sequence = session?.activeSequenceId;
|
||||
if (session == null || sequence == null) return false;
|
||||
final inserted = await _ref
|
||||
.read(projectsProvider.notifier)
|
||||
.insertTimelineAsset(
|
||||
projectId: projectId,
|
||||
session: session,
|
||||
sequenceId: sequence,
|
||||
assetId: asset.id,
|
||||
position: session.view(sequence).playheadTick,
|
||||
);
|
||||
if (inserted && active) {
|
||||
_ref
|
||||
.read(previewNavigationProvider(projectId, timelineId).notifier)
|
||||
.showTimeline();
|
||||
}
|
||||
return inserted;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
feedback.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String? _selectedAssetId;
|
||||
MediaFilter _filter = MediaFilter.all;
|
||||
bool _grid = true;
|
||||
|
||||
String? get selectedAssetId => _selectedAssetId;
|
||||
MediaFilter get filter => _filter;
|
||||
bool get grid => _grid;
|
||||
|
||||
set selectedAssetId(String? value) {
|
||||
_selectedAssetId = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
set filter(MediaFilter value) {
|
||||
_filter = value;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
set grid(bool value) {
|
||||
_grid = value;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../workspace/media_import.dart';
|
||||
import '../../workspace/media_import_feedback.dart';
|
||||
import 'media_browser_controller.dart';
|
||||
|
||||
Future<void> pickMediaFiles(MediaBrowserController browser) async {
|
||||
try {
|
||||
await browser.pickFiles();
|
||||
} catch (_) {
|
||||
// The controller retains the failure for its next visible presentation.
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> importMediaFiles(
|
||||
MediaBrowserController browser,
|
||||
List<ExternalMediaFile> files,
|
||||
) async {
|
||||
try {
|
||||
await browser.importFiles(files);
|
||||
} catch (_) {
|
||||
// The controller retains the failure for its next visible presentation.
|
||||
}
|
||||
}
|
||||
|
||||
class MediaImportFeedbackListener extends StatefulWidget {
|
||||
const MediaImportFeedbackListener({
|
||||
super.key,
|
||||
required this.feedback,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final MediaImportFeedbackController feedback;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<MediaImportFeedbackListener> createState() =>
|
||||
_MediaImportFeedbackListenerState();
|
||||
}
|
||||
|
||||
class _MediaImportFeedbackListenerState
|
||||
extends State<MediaImportFeedbackListener> {
|
||||
bool _scheduled = false;
|
||||
bool get _visible =>
|
||||
TickerMode.valuesOf(context).enabled &&
|
||||
(ModalRoute.of(context)?.isCurrent ?? true);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
widget.feedback.addListener(_schedule);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
_schedule();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant MediaImportFeedbackListener oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.feedback != widget.feedback) {
|
||||
oldWidget.feedback.removeListener(_schedule);
|
||||
widget.feedback.addListener(_schedule);
|
||||
}
|
||||
_schedule();
|
||||
}
|
||||
|
||||
void _schedule() {
|
||||
if (_scheduled || !widget.feedback.hasPending) return;
|
||||
_scheduled = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_scheduled = false;
|
||||
if (!mounted || !_visible || !widget.feedback.hasPending) return;
|
||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||
if (messenger == null) return;
|
||||
for (final result in widget.feedback.takePending()) {
|
||||
final messages = [
|
||||
if (result == null) context.l10n.operationFailed,
|
||||
for (final failure
|
||||
in result?.result?.failures ?? <MediaImportFailure>[])
|
||||
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
|
||||
if (result?.failed == true) context.l10n.noImportableFiles,
|
||||
];
|
||||
messenger.showSnackBar(
|
||||
SnackBar(
|
||||
content: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxHeight: 180),
|
||||
child: SingleChildScrollView(child: Text(messages.join('\n'))),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
WidgetsBinding.instance.ensureVisualUpdate();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.feedback.removeListener(_schedule);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => widget.child;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/media_availability.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import 'media_browser_body.dart';
|
||||
import 'media_browser_controller.dart';
|
||||
import 'media_browser_feedback.dart';
|
||||
|
||||
class MediaBrowserPage extends StatelessWidget {
|
||||
const MediaBrowserPage({super.key, required this.projectId});
|
||||
final String projectId;
|
||||
@override
|
||||
Widget build(BuildContext context) => TouchMediaBrowser(
|
||||
key: const Key('media-browser-page'),
|
||||
projectId: projectId,
|
||||
);
|
||||
}
|
||||
|
||||
class MediaBrowserDrawer extends StatelessWidget {
|
||||
const MediaBrowserDrawer({super.key, required this.projectId});
|
||||
final String projectId;
|
||||
@override
|
||||
Widget build(BuildContext context) => TouchMediaBrowser(
|
||||
key: const Key('media-browser-drawer'),
|
||||
projectId: projectId,
|
||||
);
|
||||
}
|
||||
|
||||
/// Touch controls share browser commands and item components with desktop.
|
||||
class TouchMediaBrowser extends ConsumerWidget {
|
||||
const TouchMediaBrowser({super.key, required this.projectId});
|
||||
final String projectId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final browser = ref.watch(mediaBrowserProvider(projectId));
|
||||
ref.watch(externalMediaImportProvider(projectId));
|
||||
final workspace = ref.watch(projectsProvider).value;
|
||||
final timelineId = workspace?.activeProject?.id == projectId
|
||||
? workspace?.timeline?.id
|
||||
: null;
|
||||
final timeline = timelineId == null
|
||||
? null
|
||||
: ref.watch(editorTimelineProvider(projectId, timelineId)).value;
|
||||
return ListenableBuilder(
|
||||
listenable: browser,
|
||||
builder: (context, _) {
|
||||
final selected = workspace?.assets
|
||||
.where((asset) => asset.id == browser.selectedAssetId)
|
||||
.firstOrNull;
|
||||
final availability = selected == null
|
||||
? null
|
||||
: ref.watch(mediaAvailabilityProvider(projectId, selected)).value;
|
||||
final canInsert =
|
||||
browser.canEdit &&
|
||||
selected != null &&
|
||||
timeline?.activeSequenceId != null &&
|
||||
availability == MediaAvailability.available;
|
||||
return MediaImportFeedbackListener(
|
||||
feedback: browser.feedback,
|
||||
child: Material(
|
||||
key: const Key('media-panel-surface'),
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
key: const Key('media-panel-header'),
|
||||
height: 56,
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox.square(
|
||||
dimension: 48,
|
||||
child: IconButton(
|
||||
key: const Key('media-import-button'),
|
||||
tooltip: context.l10n.importMedia,
|
||||
onPressed: browser.canImport
|
||||
? () => pickMediaFiles(browser)
|
||||
: null,
|
||||
icon: const Icon(Icons.add),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: DropdownButton<MediaFilter>(
|
||||
key: const Key('media-category-picker'),
|
||||
isExpanded: true,
|
||||
underline: const SizedBox.shrink(),
|
||||
value: browser.filter,
|
||||
items: [
|
||||
for (final filter in MediaFilter.values)
|
||||
DropdownMenuItem(
|
||||
value: filter,
|
||||
child: Text(filter.label(context)),
|
||||
),
|
||||
],
|
||||
onChanged: (filter) {
|
||||
if (filter != null) browser.filter = filter;
|
||||
},
|
||||
),
|
||||
),
|
||||
SizedBox.square(
|
||||
dimension: 48,
|
||||
child: IconButton(
|
||||
key: const Key('media-layout-toggle'),
|
||||
tooltip: browser.grid
|
||||
? context.l10n.listLayout
|
||||
: context.l10n.gridLayout,
|
||||
icon: Icon(
|
||||
browser.grid
|
||||
? Icons.view_list_outlined
|
||||
: Icons.grid_view_outlined,
|
||||
),
|
||||
onPressed: () => browser.grid = !browser.grid,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (browser.busy) const LinearProgressIndicator(),
|
||||
Expanded(
|
||||
key: const Key('media-panel-body'),
|
||||
child: MediaBrowserBody(
|
||||
projectId: projectId,
|
||||
grid: browser.grid,
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
key: const Key('media-add-selected'),
|
||||
style: FilledButton.styleFrom(
|
||||
minimumSize: const Size(0, 48),
|
||||
),
|
||||
onPressed: !canInsert
|
||||
? null
|
||||
: () async {
|
||||
final inserted = await browser.insertAsset(
|
||||
selected,
|
||||
);
|
||||
if (!inserted && context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.operationFailed),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.add),
|
||||
label: Text(
|
||||
context.l10n.addToTimeline,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../integrations/platform/native_project_drop_region.dart';
|
||||
import '../../integrations/platform/platform_capabilities.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/widgets/drop_to_add_overlay.dart';
|
||||
import '../../workspace/external_media_import.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import 'media_browser_body.dart';
|
||||
import 'media_browser_controller.dart';
|
||||
import 'media_browser_feedback.dart';
|
||||
|
||||
/// Desktop presentation owns compact controls and native file dragging.
|
||||
class MediaPanel extends ConsumerStatefulWidget {
|
||||
const MediaPanel({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
this.backgroundColor,
|
||||
this.grid,
|
||||
this.onGridChanged,
|
||||
}) : assert((grid == null) == (onGridChanged == null));
|
||||
final String projectId;
|
||||
final Color? backgroundColor;
|
||||
final bool? grid;
|
||||
final ValueChanged<bool>? onGridChanged;
|
||||
@override
|
||||
ConsumerState<MediaPanel> createState() => _MediaPanelState();
|
||||
}
|
||||
|
||||
class _MediaPanelState extends ConsumerState<MediaPanel> {
|
||||
bool _hovering = false;
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(projectsProvider);
|
||||
final browser = ref.watch(mediaBrowserProvider(widget.projectId));
|
||||
ref.watch(externalMediaImportProvider(widget.projectId));
|
||||
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
|
||||
return ListenableBuilder(
|
||||
listenable: browser,
|
||||
builder: (context, _) {
|
||||
final grid = widget.grid ?? browser.grid;
|
||||
final visible =
|
||||
TickerMode.valuesOf(context).enabled &&
|
||||
(ModalRoute.of(context)?.isCurrent ?? true);
|
||||
final enabled = browser.canImport && visible;
|
||||
void toggleGrid() {
|
||||
final next = !grid;
|
||||
if (widget.onGridChanged case final onChanged?) {
|
||||
onChanged(next);
|
||||
} else {
|
||||
browser.grid = next;
|
||||
}
|
||||
}
|
||||
|
||||
final content = MediaImportFeedbackListener(
|
||||
feedback: browser.feedback,
|
||||
child: Material(
|
||||
key: const Key('media-panel-surface'),
|
||||
color: widget.backgroundColor,
|
||||
child: Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
key: const Key('media-panel-header'),
|
||||
height: AppControlSize.panelToolbar,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(AppSpacing.gap),
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final compact = constraints.maxWidth < 180;
|
||||
final controls = Row(
|
||||
mainAxisSize: compact
|
||||
? MainAxisSize.min
|
||||
: MainAxisSize.max,
|
||||
children: [
|
||||
if (compact)
|
||||
SizedBox.square(
|
||||
dimension: AppControlSize.headerButton,
|
||||
child: IconButton(
|
||||
key: const Key('media-import-button'),
|
||||
tooltip: context.l10n.importMedia,
|
||||
onPressed: enabled
|
||||
? () => pickMediaFiles(browser)
|
||||
: null,
|
||||
icon: const Icon(
|
||||
Icons.add,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
)
|
||||
else
|
||||
SizedBox(
|
||||
height: AppControlSize.headerButton,
|
||||
child: TextButton.icon(
|
||||
key: const Key('media-import-button'),
|
||||
style: AppTheme.toolbarButtonStyle(
|
||||
context,
|
||||
),
|
||||
onPressed: enabled
|
||||
? () => pickMediaFiles(browser)
|
||||
: null,
|
||||
icon: const Icon(
|
||||
Icons.add,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
label: Text(context.l10n.importMedia),
|
||||
),
|
||||
),
|
||||
if (compact)
|
||||
const SizedBox(width: AppSpacing.tiny)
|
||||
else
|
||||
const Spacer(),
|
||||
SizedBox(
|
||||
width: 76,
|
||||
child: AppSelect<MediaFilter>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
label: context.l10n.mediaCategory,
|
||||
outlined: false,
|
||||
controlHeight: AppControlSize.headerButton,
|
||||
textStyle: AppTheme.toolbarTextStyle(
|
||||
context,
|
||||
),
|
||||
value: browser.filter,
|
||||
onChanged: (value) =>
|
||||
browser.filter = value,
|
||||
options: [
|
||||
for (final filter in MediaFilter.values)
|
||||
AppSelectOption(
|
||||
filter,
|
||||
filter.label(context),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.tiny),
|
||||
SizedBox.square(
|
||||
dimension: AppControlSize.headerButton,
|
||||
child: IconButton(
|
||||
key: const Key('media-layout-toggle'),
|
||||
onPressed: toggleGrid,
|
||||
icon: Icon(
|
||||
grid
|
||||
? Icons.view_list_outlined
|
||||
: Icons.grid_view_outlined,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
tooltip: grid
|
||||
? context.l10n.listLayout
|
||||
: context.l10n.gridLayout,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
return compact
|
||||
? SingleChildScrollView(
|
||||
key: const Key('media-header-scroll'),
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: controls,
|
||||
)
|
||||
: controls;
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
key: const Key('media-panel-body'),
|
||||
child: MediaBrowserBody(
|
||||
projectId: widget.projectId,
|
||||
grid: grid,
|
||||
draggable: true,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (browser.busy)
|
||||
const DelayedLoadingIndicator(
|
||||
child: Align(
|
||||
alignment: Alignment.topCenter,
|
||||
child: LinearProgressIndicator(),
|
||||
),
|
||||
),
|
||||
if (_hovering && enabled)
|
||||
const DropToAddOverlay(key: Key('media-drop-highlight')),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
if (!nativeDrop) return content;
|
||||
return NativeProjectDropRegion(
|
||||
enabled: visible && browser.active && (enabled || browser.busy),
|
||||
onEnter: (_) {
|
||||
if (enabled) setState(() => _hovering = true);
|
||||
},
|
||||
onExit: () {
|
||||
if (mounted && _hovering) setState(() => _hovering = false);
|
||||
},
|
||||
onDrop: (files) async {
|
||||
setState(() => _hovering = false);
|
||||
await importMediaFiles(browser, files);
|
||||
},
|
||||
child: content,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'processing_targets.freezed.dart';
|
||||
|
||||
/// A fixed timeline target, retained even if selection or active sequence changes.
|
||||
@freezed
|
||||
abstract class TranscriptionClipTarget with _$TranscriptionClipTarget {
|
||||
const factory TranscriptionClipTarget({
|
||||
required SequenceId sequence,
|
||||
required String clipId,
|
||||
required String mediaId,
|
||||
required String name,
|
||||
required int audioStream,
|
||||
}) = _TranscriptionClipTarget;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class BackgroundRemovalClipTarget with _$BackgroundRemovalClipTarget {
|
||||
const factory BackgroundRemovalClipTarget({
|
||||
required SequenceId sequence,
|
||||
required String clipId,
|
||||
required String mediaId,
|
||||
required String name,
|
||||
}) = _BackgroundRemovalClipTarget;
|
||||
}
|
||||
@@ -0,0 +1,855 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'processing_targets.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$TranscriptionClipTarget {
|
||||
SequenceId get sequence;
|
||||
String get clipId;
|
||||
String get mediaId;
|
||||
String get name;
|
||||
int get audioStream;
|
||||
|
||||
/// Create a copy of TranscriptionClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$TranscriptionClipTargetCopyWith<TranscriptionClipTarget> get copyWith =>
|
||||
_$TranscriptionClipTargetCopyWithImpl<TranscriptionClipTarget>(
|
||||
this as TranscriptionClipTarget,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as TranscriptionClipTarget;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is TranscriptionClipTarget &&
|
||||
(identical(other.sequence, _this.sequence) ||
|
||||
other.sequence == _this.sequence) &&
|
||||
(identical(other.clipId, _this.clipId) ||
|
||||
other.clipId == _this.clipId) &&
|
||||
(identical(other.mediaId, _this.mediaId) ||
|
||||
other.mediaId == _this.mediaId) &&
|
||||
(identical(other.name, _this.name) || other.name == _this.name) &&
|
||||
(identical(other.audioStream, _this.audioStream) ||
|
||||
other.audioStream == _this.audioStream));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as TranscriptionClipTarget;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.sequence,
|
||||
_this.clipId,
|
||||
_this.mediaId,
|
||||
_this.name,
|
||||
_this.audioStream,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as TranscriptionClipTarget;
|
||||
return 'TranscriptionClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name}, audioStream: ${_this.audioStream})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $TranscriptionClipTargetCopyWith<$Res> {
|
||||
factory $TranscriptionClipTargetCopyWith(
|
||||
TranscriptionClipTarget value,
|
||||
$Res Function(TranscriptionClipTarget) _then,
|
||||
) = _$TranscriptionClipTargetCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
int audioStream,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$TranscriptionClipTargetCopyWithImpl<$Res>
|
||||
implements $TranscriptionClipTargetCopyWith<$Res> {
|
||||
_$TranscriptionClipTargetCopyWithImpl(this._self, this._then);
|
||||
|
||||
final TranscriptionClipTarget _self;
|
||||
final $Res Function(TranscriptionClipTarget) _then;
|
||||
|
||||
/// Create a copy of TranscriptionClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? sequence = null,
|
||||
Object? clipId = null,
|
||||
Object? mediaId = null,
|
||||
Object? name = null,
|
||||
Object? audioStream = null,
|
||||
}) {
|
||||
return _then(
|
||||
TranscriptionClipTarget(
|
||||
sequence: null == sequence
|
||||
? _self.sequence
|
||||
: sequence // ignore: cast_nullable_to_non_nullable
|
||||
as SequenceId,
|
||||
clipId: null == clipId
|
||||
? _self.clipId
|
||||
: clipId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
mediaId: null == mediaId
|
||||
? _self.mediaId
|
||||
: mediaId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
audioStream: null == audioStream
|
||||
? _self.audioStream
|
||||
: audioStream // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [TranscriptionClipTarget].
|
||||
extension TranscriptionClipTargetPatterns on TranscriptionClipTarget {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_TranscriptionClipTarget value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _TranscriptionClipTarget() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_TranscriptionClipTarget value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _TranscriptionClipTarget():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_TranscriptionClipTarget value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _TranscriptionClipTarget() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
int audioStream,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _TranscriptionClipTarget() when $default != null:
|
||||
return $default(
|
||||
_that.sequence,
|
||||
_that.clipId,
|
||||
_that.mediaId,
|
||||
_that.name,
|
||||
_that.audioStream,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
int audioStream,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _TranscriptionClipTarget():
|
||||
return $default(
|
||||
_that.sequence,
|
||||
_that.clipId,
|
||||
_that.mediaId,
|
||||
_that.name,
|
||||
_that.audioStream,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
int audioStream,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _TranscriptionClipTarget() when $default != null:
|
||||
return $default(
|
||||
_that.sequence,
|
||||
_that.clipId,
|
||||
_that.mediaId,
|
||||
_that.name,
|
||||
_that.audioStream,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _TranscriptionClipTarget implements TranscriptionClipTarget {
|
||||
const _TranscriptionClipTarget({
|
||||
required this.sequence,
|
||||
required this.clipId,
|
||||
required this.mediaId,
|
||||
required this.name,
|
||||
required this.audioStream,
|
||||
});
|
||||
|
||||
@override
|
||||
final SequenceId sequence;
|
||||
@override
|
||||
final String clipId;
|
||||
@override
|
||||
final String mediaId;
|
||||
@override
|
||||
final String name;
|
||||
@override
|
||||
final int audioStream;
|
||||
|
||||
/// Create a copy of TranscriptionClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$TranscriptionClipTargetCopyWith<_TranscriptionClipTarget> get copyWith =>
|
||||
__$TranscriptionClipTargetCopyWithImpl<_TranscriptionClipTarget>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _TranscriptionClipTarget &&
|
||||
(identical(other.sequence, sequence) ||
|
||||
other.sequence == sequence) &&
|
||||
(identical(other.clipId, clipId) || other.clipId == clipId) &&
|
||||
(identical(other.mediaId, mediaId) || other.mediaId == mediaId) &&
|
||||
(identical(other.name, name) || other.name == name) &&
|
||||
(identical(other.audioStream, audioStream) ||
|
||||
other.audioStream == audioStream));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
sequence,
|
||||
clipId,
|
||||
mediaId,
|
||||
name,
|
||||
audioStream,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'TranscriptionClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name, audioStream: $audioStream)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$TranscriptionClipTargetCopyWith<$Res>
|
||||
implements $TranscriptionClipTargetCopyWith<$Res> {
|
||||
factory _$TranscriptionClipTargetCopyWith(
|
||||
_TranscriptionClipTarget value,
|
||||
$Res Function(_TranscriptionClipTarget) _then,
|
||||
) = __$TranscriptionClipTargetCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
int audioStream,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$TranscriptionClipTargetCopyWithImpl<$Res>
|
||||
implements _$TranscriptionClipTargetCopyWith<$Res> {
|
||||
__$TranscriptionClipTargetCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _TranscriptionClipTarget _self;
|
||||
final $Res Function(_TranscriptionClipTarget) _then;
|
||||
|
||||
/// Create a copy of TranscriptionClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? sequence = null,
|
||||
Object? clipId = null,
|
||||
Object? mediaId = null,
|
||||
Object? name = null,
|
||||
Object? audioStream = null,
|
||||
}) {
|
||||
return _then(
|
||||
_TranscriptionClipTarget(
|
||||
sequence: null == sequence
|
||||
? _self.sequence
|
||||
: sequence // ignore: cast_nullable_to_non_nullable
|
||||
as SequenceId,
|
||||
clipId: null == clipId
|
||||
? _self.clipId
|
||||
: clipId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
mediaId: null == mediaId
|
||||
? _self.mediaId
|
||||
: mediaId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
audioStream: null == audioStream
|
||||
? _self.audioStream
|
||||
: audioStream // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
mixin _$BackgroundRemovalClipTarget {
|
||||
SequenceId get sequence;
|
||||
String get clipId;
|
||||
String get mediaId;
|
||||
String get name;
|
||||
|
||||
/// Create a copy of BackgroundRemovalClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$BackgroundRemovalClipTargetCopyWith<BackgroundRemovalClipTarget>
|
||||
get copyWith =>
|
||||
_$BackgroundRemovalClipTargetCopyWithImpl<BackgroundRemovalClipTarget>(
|
||||
this as BackgroundRemovalClipTarget,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as BackgroundRemovalClipTarget;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is BackgroundRemovalClipTarget &&
|
||||
(identical(other.sequence, _this.sequence) ||
|
||||
other.sequence == _this.sequence) &&
|
||||
(identical(other.clipId, _this.clipId) ||
|
||||
other.clipId == _this.clipId) &&
|
||||
(identical(other.mediaId, _this.mediaId) ||
|
||||
other.mediaId == _this.mediaId) &&
|
||||
(identical(other.name, _this.name) || other.name == _this.name));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as BackgroundRemovalClipTarget;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.sequence,
|
||||
_this.clipId,
|
||||
_this.mediaId,
|
||||
_this.name,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as BackgroundRemovalClipTarget;
|
||||
return 'BackgroundRemovalClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $BackgroundRemovalClipTargetCopyWith<$Res> {
|
||||
factory $BackgroundRemovalClipTargetCopyWith(
|
||||
BackgroundRemovalClipTarget value,
|
||||
$Res Function(BackgroundRemovalClipTarget) _then,
|
||||
) = _$BackgroundRemovalClipTargetCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({SequenceId sequence, String clipId, String mediaId, String name});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$BackgroundRemovalClipTargetCopyWithImpl<$Res>
|
||||
implements $BackgroundRemovalClipTargetCopyWith<$Res> {
|
||||
_$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then);
|
||||
|
||||
final BackgroundRemovalClipTarget _self;
|
||||
final $Res Function(BackgroundRemovalClipTarget) _then;
|
||||
|
||||
/// Create a copy of BackgroundRemovalClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? sequence = null,
|
||||
Object? clipId = null,
|
||||
Object? mediaId = null,
|
||||
Object? name = null,
|
||||
}) {
|
||||
return _then(
|
||||
BackgroundRemovalClipTarget(
|
||||
sequence: null == sequence
|
||||
? _self.sequence
|
||||
: sequence // ignore: cast_nullable_to_non_nullable
|
||||
as SequenceId,
|
||||
clipId: null == clipId
|
||||
? _self.clipId
|
||||
: clipId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
mediaId: null == mediaId
|
||||
? _self.mediaId
|
||||
: mediaId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [BackgroundRemovalClipTarget].
|
||||
extension BackgroundRemovalClipTargetPatterns on BackgroundRemovalClipTarget {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_BackgroundRemovalClipTarget value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _BackgroundRemovalClipTarget() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_BackgroundRemovalClipTarget value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _BackgroundRemovalClipTarget():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_BackgroundRemovalClipTarget value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _BackgroundRemovalClipTarget() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _BackgroundRemovalClipTarget() when $default != null:
|
||||
return $default(
|
||||
_that.sequence,
|
||||
_that.clipId,
|
||||
_that.mediaId,
|
||||
_that.name,
|
||||
);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _BackgroundRemovalClipTarget():
|
||||
return $default(
|
||||
_that.sequence,
|
||||
_that.clipId,
|
||||
_that.mediaId,
|
||||
_that.name,
|
||||
);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(
|
||||
SequenceId sequence,
|
||||
String clipId,
|
||||
String mediaId,
|
||||
String name,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _BackgroundRemovalClipTarget() when $default != null:
|
||||
return $default(
|
||||
_that.sequence,
|
||||
_that.clipId,
|
||||
_that.mediaId,
|
||||
_that.name,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _BackgroundRemovalClipTarget implements BackgroundRemovalClipTarget {
|
||||
const _BackgroundRemovalClipTarget({
|
||||
required this.sequence,
|
||||
required this.clipId,
|
||||
required this.mediaId,
|
||||
required this.name,
|
||||
});
|
||||
|
||||
@override
|
||||
final SequenceId sequence;
|
||||
@override
|
||||
final String clipId;
|
||||
@override
|
||||
final String mediaId;
|
||||
@override
|
||||
final String name;
|
||||
|
||||
/// Create a copy of BackgroundRemovalClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$BackgroundRemovalClipTargetCopyWith<_BackgroundRemovalClipTarget>
|
||||
get copyWith =>
|
||||
__$BackgroundRemovalClipTargetCopyWithImpl<_BackgroundRemovalClipTarget>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _BackgroundRemovalClipTarget &&
|
||||
(identical(other.sequence, sequence) ||
|
||||
other.sequence == sequence) &&
|
||||
(identical(other.clipId, clipId) || other.clipId == clipId) &&
|
||||
(identical(other.mediaId, mediaId) || other.mediaId == mediaId) &&
|
||||
(identical(other.name, name) || other.name == name));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, sequence, clipId, mediaId, name);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'BackgroundRemovalClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$BackgroundRemovalClipTargetCopyWith<$Res>
|
||||
implements $BackgroundRemovalClipTargetCopyWith<$Res> {
|
||||
factory _$BackgroundRemovalClipTargetCopyWith(
|
||||
_BackgroundRemovalClipTarget value,
|
||||
$Res Function(_BackgroundRemovalClipTarget) _then,
|
||||
) = __$BackgroundRemovalClipTargetCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({SequenceId sequence, String clipId, String mediaId, String name});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$BackgroundRemovalClipTargetCopyWithImpl<$Res>
|
||||
implements _$BackgroundRemovalClipTargetCopyWith<$Res> {
|
||||
__$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _BackgroundRemovalClipTarget _self;
|
||||
final $Res Function(_BackgroundRemovalClipTarget) _then;
|
||||
|
||||
/// Create a copy of BackgroundRemovalClipTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? sequence = null,
|
||||
Object? clipId = null,
|
||||
Object? mediaId = null,
|
||||
Object? name = null,
|
||||
}) {
|
||||
return _then(
|
||||
_BackgroundRemovalClipTarget(
|
||||
sequence: null == sequence
|
||||
? _self.sequence
|
||||
: sequence // ignore: cast_nullable_to_non_nullable
|
||||
as SequenceId,
|
||||
clipId: null == clipId
|
||||
? _self.clipId
|
||||
: clipId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
mediaId: null == mediaId
|
||||
? _self.mediaId
|
||||
: mediaId // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,267 @@
|
||||
import 'package:cutdex/diagnostics/app_diagnostics.dart';
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_configuration.dart';
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'processing_targets.dart';
|
||||
|
||||
part 'subtitle_download.g.dart';
|
||||
part 'subtitle_download.freezed.dart';
|
||||
|
||||
enum SubtitleStartFailure { start, download, engine }
|
||||
|
||||
@freezed
|
||||
abstract class SubtitleRequest with _$SubtitleRequest {
|
||||
const factory SubtitleRequest({
|
||||
required EditorTimelineSession session,
|
||||
required SequenceId? sequence,
|
||||
AssetDocument? asset,
|
||||
TranscriptionClipTarget? target,
|
||||
@Default('auto') String language,
|
||||
@Default('none') String targetLanguage,
|
||||
}) = _SubtitleRequest;
|
||||
}
|
||||
|
||||
@freezed
|
||||
sealed class SubtitleDownloadState with _$SubtitleDownloadState {
|
||||
const SubtitleDownloadState._();
|
||||
const factory SubtitleDownloadState.idle() = SubtitleIdle;
|
||||
const factory SubtitleDownloadState.starting(SubtitleRequest request) =
|
||||
SubtitleStarting;
|
||||
const factory SubtitleDownloadState.downloading(
|
||||
SubtitleRequest request, {
|
||||
required ProcessingCapability stage,
|
||||
ProcessingResourceRepository? repository,
|
||||
@Default(0) double progress,
|
||||
@Default(false) bool paused,
|
||||
}) = SubtitleDownloading;
|
||||
const factory SubtitleDownloadState.started(SubtitleRequest request) =
|
||||
SubtitleStarted;
|
||||
const factory SubtitleDownloadState.cancelled(SubtitleRequest request) =
|
||||
SubtitleCancelled;
|
||||
const factory SubtitleDownloadState.failed(
|
||||
SubtitleRequest request,
|
||||
SubtitleStartFailure failure,
|
||||
) = SubtitleFailed;
|
||||
|
||||
SubtitleRequest? get request => switch (this) {
|
||||
SubtitleIdle() => null,
|
||||
SubtitleStarting(:final request) ||
|
||||
SubtitleDownloading(:final request) ||
|
||||
SubtitleStarted(:final request) ||
|
||||
SubtitleCancelled(:final request) ||
|
||||
SubtitleFailed(:final request) => request,
|
||||
};
|
||||
bool get running => this is SubtitleStarting || this is SubtitleDownloading;
|
||||
}
|
||||
|
||||
/// Owns the download and task handoff even when its dialog is closed.
|
||||
@Riverpod(keepAlive: true)
|
||||
class SubtitleDownload extends _$SubtitleDownload {
|
||||
ProcessingResourceRepository? _repository;
|
||||
bool _cancelled = false;
|
||||
|
||||
@override
|
||||
SubtitleDownloadState build() {
|
||||
ref.onDispose(() {
|
||||
_cancelled = true;
|
||||
_repository?.cancelSubtitleResources();
|
||||
});
|
||||
return const SubtitleDownloadState.idle();
|
||||
}
|
||||
|
||||
Future<void> start(SubtitleRequest request, {bool download = false}) async {
|
||||
if (state.running) return;
|
||||
_cancelled = false;
|
||||
var resourceInstalled = false;
|
||||
final session = request.session;
|
||||
final release = session.retainViews();
|
||||
state = download
|
||||
? SubtitleDownloadState.downloading(
|
||||
request,
|
||||
stage: session.transcriptions?.recognitionAvailable == true
|
||||
? ProcessingCapability.translation
|
||||
: ProcessingCapability.transcription,
|
||||
)
|
||||
: SubtitleDownloadState.starting(request);
|
||||
ProcessingResourceRepository? repository;
|
||||
void changed() {
|
||||
if (!ref.mounted || state is! SubtitleDownloading) return;
|
||||
final current = state as SubtitleDownloading;
|
||||
state = current.copyWith(
|
||||
paused: repository?.subtitlePaused ?? current.paused,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final service = session.transcriptions;
|
||||
if (download) {
|
||||
final loaded = await ref.read(
|
||||
processingResourceRepositoryProvider.future,
|
||||
);
|
||||
repository = loaded;
|
||||
if (_cancelled || !ref.mounted) {
|
||||
return;
|
||||
}
|
||||
_repository = loaded;
|
||||
final pausedBeforeLoad = (state as SubtitleDownloading).paused;
|
||||
state = (state as SubtitleDownloading).copyWith(repository: loaded);
|
||||
loaded.addListener(changed);
|
||||
final install = loaded.ensureSubtitleResources(
|
||||
available: {
|
||||
if (service?.recognitionAvailable == true)
|
||||
ProcessingCapability.transcription,
|
||||
if (service?.translationAvailable == true)
|
||||
ProcessingCapability.translation,
|
||||
},
|
||||
onProgress: (stage, progress) {
|
||||
if (!ref.mounted) return;
|
||||
if (state case SubtitleDownloading(:final paused)) {
|
||||
state = SubtitleDownloadState.downloading(
|
||||
request,
|
||||
stage: stage,
|
||||
repository: loaded,
|
||||
progress: progress,
|
||||
paused: paused,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
if (pausedBeforeLoad) loaded.pauseSubtitleResources();
|
||||
await install;
|
||||
resourceInstalled = true;
|
||||
if (_cancelled || !ref.mounted) {
|
||||
return;
|
||||
}
|
||||
final processing = ProcessingConfiguration.configured(
|
||||
diagnostics: AppDiagnostics.report,
|
||||
resourcesRoot: loaded.root.parent.path,
|
||||
);
|
||||
final speechBackend = service?.backend ?? processing?.backend;
|
||||
final speechModel =
|
||||
service?.modelDirectory ?? processing?.transcriptionModel;
|
||||
final translationBackend =
|
||||
service?.translationBackend ?? processing?.backend;
|
||||
final translationModel =
|
||||
service?.translationModel ?? processing?.translationModel;
|
||||
if (speechBackend == null ||
|
||||
speechModel == null ||
|
||||
translationBackend == null ||
|
||||
translationModel == null) {
|
||||
throw AppException(AppErrorCode.subtitleEngineUnavailable);
|
||||
}
|
||||
session.configureProcessing(
|
||||
transcriptionBackend: speechBackend,
|
||||
transcriptionModel: speechModel,
|
||||
translationBackend: translationBackend,
|
||||
translationModel: translationModel,
|
||||
);
|
||||
}
|
||||
if (_cancelled || !ref.mounted) {
|
||||
return;
|
||||
}
|
||||
await _startSubtitles(request);
|
||||
if (ref.mounted) state = SubtitleDownloadState.started(request);
|
||||
} on ProcessingResourceCancelledException {
|
||||
if (ref.mounted) state = SubtitleDownloadState.cancelled(request);
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = SubtitleDownloadState.failed(
|
||||
request,
|
||||
!download
|
||||
? SubtitleStartFailure.start
|
||||
: resourceInstalled
|
||||
? SubtitleStartFailure.engine
|
||||
: SubtitleStartFailure.download,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
repository?.removeListener(changed);
|
||||
_repository = null;
|
||||
if (ref.mounted && _cancelled && state.running) {
|
||||
state = SubtitleDownloadState.cancelled(request);
|
||||
}
|
||||
release();
|
||||
}
|
||||
}
|
||||
|
||||
void togglePause() {
|
||||
if (state case SubtitleDownloading(:final paused)) {
|
||||
state = (state as SubtitleDownloading).copyWith(paused: !paused);
|
||||
if (paused) {
|
||||
_repository?.resumeSubtitleResources();
|
||||
} else {
|
||||
_repository?.pauseSubtitleResources();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void cancel() {
|
||||
if (!state.running) return;
|
||||
_cancelled = true;
|
||||
_repository?.cancelSubtitleResources();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _startSubtitles(SubtitleRequest request) async {
|
||||
final mediaId = request.target?.mediaId ?? request.asset?.id;
|
||||
final name = request.target?.name ?? request.asset?.name ?? mediaId;
|
||||
final sequence = request.sequence;
|
||||
if (sequence == null || mediaId == null || name == null) {
|
||||
throw const CommandRejected(
|
||||
'missingSequence',
|
||||
'Sequence or media does not exist',
|
||||
);
|
||||
}
|
||||
await request.session.subtitleWorkflows.start(
|
||||
sequence: sequence,
|
||||
command: StartTranscription(
|
||||
mediaId: mediaId,
|
||||
clipId: request.target?.clipId,
|
||||
audioStream: request.target?.audioStream ?? 0,
|
||||
language: request.language,
|
||||
),
|
||||
name: name,
|
||||
targetLanguage: request.targetLanguage,
|
||||
);
|
||||
}
|
||||
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
@riverpod
|
||||
class SubtitleStart extends _$SubtitleStart {
|
||||
@override
|
||||
SubtitleDownloadState build(EditorTimelineSession session) =>
|
||||
const SubtitleDownloadState.idle();
|
||||
|
||||
void reset() {
|
||||
if (!state.running) state = const SubtitleDownloadState.idle();
|
||||
}
|
||||
|
||||
Future<void> start(SubtitleRequest request) async {
|
||||
if (state.running) return;
|
||||
final lease = ref.keepAlive();
|
||||
final release = session.retainViews();
|
||||
state = SubtitleDownloadState.starting(request);
|
||||
try {
|
||||
await _startSubtitles(request);
|
||||
if (ref.mounted) state = SubtitleDownloadState.started(request);
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = SubtitleDownloadState.failed(
|
||||
request,
|
||||
SubtitleStartFailure.start,
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
release();
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,174 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'subtitle_download.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Owns the download and task handoff even when its dialog is closed.
|
||||
|
||||
@ProviderFor(SubtitleDownload)
|
||||
final subtitleDownloadProvider = SubtitleDownloadProvider._();
|
||||
|
||||
/// Owns the download and task handoff even when its dialog is closed.
|
||||
final class SubtitleDownloadProvider
|
||||
extends $NotifierProvider<SubtitleDownload, SubtitleDownloadState> {
|
||||
/// Owns the download and task handoff even when its dialog is closed.
|
||||
SubtitleDownloadProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'subtitleDownloadProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$subtitleDownloadHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
SubtitleDownload create() => SubtitleDownload();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(SubtitleDownloadState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<SubtitleDownloadState>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$subtitleDownloadHash() => r'2bf89e93b596e3b24f3880279477c91227b261b4';
|
||||
|
||||
/// Owns the download and task handoff even when its dialog is closed.
|
||||
|
||||
abstract class _$SubtitleDownload extends $Notifier<SubtitleDownloadState> {
|
||||
SubtitleDownloadState build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<SubtitleDownloadState, SubtitleDownloadState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<SubtitleDownloadState, SubtitleDownloadState>,
|
||||
SubtitleDownloadState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
|
||||
@ProviderFor(SubtitleStart)
|
||||
final subtitleStartProvider = SubtitleStartFamily._();
|
||||
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
final class SubtitleStartProvider
|
||||
extends $NotifierProvider<SubtitleStart, SubtitleDownloadState> {
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
SubtitleStartProvider._({
|
||||
required SubtitleStartFamily super.from,
|
||||
required EditorTimelineSession super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'subtitleStartProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$subtitleStartHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'subtitleStartProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
SubtitleStart create() => SubtitleStart();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(SubtitleDownloadState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<SubtitleDownloadState>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SubtitleStartProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$subtitleStartHash() => r'3278b419fd819fa4dcc021815280cc1cce72dbb5';
|
||||
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
|
||||
final class SubtitleStartFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
SubtitleStart,
|
||||
SubtitleDownloadState,
|
||||
SubtitleDownloadState,
|
||||
SubtitleDownloadState,
|
||||
EditorTimelineSession
|
||||
> {
|
||||
SubtitleStartFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'subtitleStartProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
|
||||
SubtitleStartProvider call(EditorTimelineSession session) =>
|
||||
SubtitleStartProvider._(argument: session, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'subtitleStartProvider';
|
||||
}
|
||||
|
||||
/// Configured sessions can start independently of another project's download.
|
||||
|
||||
abstract class _$SubtitleStart extends $Notifier<SubtitleDownloadState> {
|
||||
late final _$args = ref.$arg as EditorTimelineSession;
|
||||
EditorTimelineSession get session => _$args;
|
||||
|
||||
SubtitleDownloadState build(EditorTimelineSession session);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<SubtitleDownloadState, SubtitleDownloadState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<SubtitleDownloadState, SubtitleDownloadState>,
|
||||
SubtitleDownloadState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, () => build(_$args));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
part 'subtitle_task_actions.g.dart';
|
||||
part 'subtitle_task_actions.freezed.dart';
|
||||
|
||||
enum SubtitleActionKind { original, translation, cancel, retry }
|
||||
|
||||
@freezed
|
||||
abstract class SubtitleActionFeedback with _$SubtitleActionFeedback {
|
||||
const factory SubtitleActionFeedback({
|
||||
required SubtitleActionKind kind,
|
||||
int? cueCount,
|
||||
}) = _SubtitleActionFeedback;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class SubtitleActionException
|
||||
with _$SubtitleActionException
|
||||
implements Exception {
|
||||
const factory SubtitleActionException(SubtitleActionKind kind, Object cause) =
|
||||
_SubtitleActionException;
|
||||
}
|
||||
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
@riverpod
|
||||
class SubtitleTaskActions extends _$SubtitleTaskActions {
|
||||
@override
|
||||
AsyncValue<SubtitleActionFeedback?> build(
|
||||
EditorTimelineSession session,
|
||||
String jobId,
|
||||
) => const AsyncData(null);
|
||||
|
||||
Future<List<ElementDto>> candidates(
|
||||
SubtitleBackgroundTask job, {
|
||||
bool translated = false,
|
||||
}) async {
|
||||
final recognition = job.recognition;
|
||||
return session.persistence
|
||||
.timeline(job.sequence)
|
||||
.exportDto()
|
||||
.elements
|
||||
.where((element) {
|
||||
final binding = element.payloadRef == null
|
||||
? null
|
||||
: session.mediaBinding(element.payloadRef!);
|
||||
return (translated
|
||||
? binding?.media.uri == recognition.source
|
||||
: binding?.media.id == recognition.command.mediaId) &&
|
||||
binding?.audioTrackIndex == recognition.command.audioStream;
|
||||
})
|
||||
.toList();
|
||||
}
|
||||
|
||||
Future<void> apply(
|
||||
SubtitleBackgroundTask job,
|
||||
String clipId, {
|
||||
required String expectedVersion,
|
||||
bool translated = false,
|
||||
}) => _run(
|
||||
translated ? SubtitleActionKind.translation : SubtitleActionKind.original,
|
||||
() async {
|
||||
final recognition = job.recognition;
|
||||
final outcome = translated
|
||||
? await session.executeCommand(
|
||||
job.sequence,
|
||||
ApplySubtitleTranslation(
|
||||
source: recognition.source!.toFilePath(),
|
||||
audioStream: recognition.command.audioStream,
|
||||
sourceStartMs: recognition.sourceStartMs,
|
||||
taskId: job.translation!.id,
|
||||
clipId: clipId,
|
||||
expectedVersion: expectedVersion,
|
||||
),
|
||||
)
|
||||
: await session.executeCommand(
|
||||
job.sequence,
|
||||
ApplyTranscription(
|
||||
taskId: recognition.id,
|
||||
clipId: clipId,
|
||||
expectedVersion: expectedVersion,
|
||||
),
|
||||
);
|
||||
final ids = (outcome.data['captionIds'] as List).cast<String>();
|
||||
final view = session.view(job.sequence);
|
||||
final handle = ids.isEmpty
|
||||
? null
|
||||
: view.version.kernelVersion.query().elementById(
|
||||
ElementId(ids.first),
|
||||
);
|
||||
final component = handle == null
|
||||
? null
|
||||
: session.captionComponentFor(job.sequence, handle);
|
||||
if (component != null) view.setSelection([component]);
|
||||
return outcome.data['cueCount'] as int;
|
||||
},
|
||||
);
|
||||
|
||||
Future<void> cancel(SubtitleBackgroundTask job) =>
|
||||
_run(SubtitleActionKind.cancel, () async {
|
||||
await session.subtitleWorkflows.cancel(job);
|
||||
return null;
|
||||
});
|
||||
Future<void> retry(SubtitleBackgroundTask job) =>
|
||||
_run(SubtitleActionKind.retry, () async {
|
||||
await session.subtitleWorkflows.retry(job);
|
||||
return null;
|
||||
});
|
||||
|
||||
Future<void> _run(
|
||||
SubtitleActionKind kind,
|
||||
Future<int?> Function() action,
|
||||
) async {
|
||||
if (state.isLoading) return;
|
||||
final lease = ref.keepAlive();
|
||||
final release = session.retainViews();
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
final count = await action();
|
||||
if (ref.mounted) {
|
||||
state = AsyncData(SubtitleActionFeedback(kind: kind, cueCount: count));
|
||||
}
|
||||
} catch (error, stack) {
|
||||
if (ref.mounted) {
|
||||
state = AsyncError(SubtitleActionException(kind, error), stack);
|
||||
}
|
||||
} finally {
|
||||
release();
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// coverage:ignore-file
|
||||
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
|
||||
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
|
||||
|
||||
part of 'subtitle_task_actions.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$SubtitleActionFeedback {
|
||||
SubtitleActionKind get kind;
|
||||
int? get cueCount;
|
||||
|
||||
/// Create a copy of SubtitleActionFeedback
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$SubtitleActionFeedbackCopyWith<SubtitleActionFeedback> get copyWith =>
|
||||
_$SubtitleActionFeedbackCopyWithImpl<SubtitleActionFeedback>(
|
||||
this as SubtitleActionFeedback,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as SubtitleActionFeedback;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is SubtitleActionFeedback &&
|
||||
(identical(other.kind, _this.kind) || other.kind == _this.kind) &&
|
||||
(identical(other.cueCount, _this.cueCount) ||
|
||||
other.cueCount == _this.cueCount));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as SubtitleActionFeedback;
|
||||
return Object.hash(runtimeType, _this.kind, _this.cueCount);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as SubtitleActionFeedback;
|
||||
return 'SubtitleActionFeedback(kind: ${_this.kind}, cueCount: ${_this.cueCount})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $SubtitleActionFeedbackCopyWith<$Res> {
|
||||
factory $SubtitleActionFeedbackCopyWith(
|
||||
SubtitleActionFeedback value,
|
||||
$Res Function(SubtitleActionFeedback) _then,
|
||||
) = _$SubtitleActionFeedbackCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({SubtitleActionKind kind, int? cueCount});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$SubtitleActionFeedbackCopyWithImpl<$Res>
|
||||
implements $SubtitleActionFeedbackCopyWith<$Res> {
|
||||
_$SubtitleActionFeedbackCopyWithImpl(this._self, this._then);
|
||||
|
||||
final SubtitleActionFeedback _self;
|
||||
final $Res Function(SubtitleActionFeedback) _then;
|
||||
|
||||
/// Create a copy of SubtitleActionFeedback
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? kind = null, Object? cueCount = freezed}) {
|
||||
return _then(
|
||||
SubtitleActionFeedback(
|
||||
kind: null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as SubtitleActionKind,
|
||||
cueCount: freezed == cueCount
|
||||
? _self.cueCount
|
||||
: cueCount // ignore: cast_nullable_to_non_nullable
|
||||
as int?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [SubtitleActionFeedback].
|
||||
extension SubtitleActionFeedbackPatterns on SubtitleActionFeedback {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_SubtitleActionFeedback value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionFeedback() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_SubtitleActionFeedback value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionFeedback():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_SubtitleActionFeedback value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionFeedback() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(SubtitleActionKind kind, int? cueCount)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionFeedback() when $default != null:
|
||||
return $default(_that.kind, _that.cueCount);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(SubtitleActionKind kind, int? cueCount) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionFeedback():
|
||||
return $default(_that.kind, _that.cueCount);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(SubtitleActionKind kind, int? cueCount)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionFeedback() when $default != null:
|
||||
return $default(_that.kind, _that.cueCount);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _SubtitleActionFeedback implements SubtitleActionFeedback {
|
||||
const _SubtitleActionFeedback({required this.kind, this.cueCount});
|
||||
|
||||
@override
|
||||
final SubtitleActionKind kind;
|
||||
@override
|
||||
final int? cueCount;
|
||||
|
||||
/// Create a copy of SubtitleActionFeedback
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$SubtitleActionFeedbackCopyWith<_SubtitleActionFeedback> get copyWith =>
|
||||
__$SubtitleActionFeedbackCopyWithImpl<_SubtitleActionFeedback>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _SubtitleActionFeedback &&
|
||||
(identical(other.kind, kind) || other.kind == kind) &&
|
||||
(identical(other.cueCount, cueCount) ||
|
||||
other.cueCount == cueCount));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, kind, cueCount);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'SubtitleActionFeedback(kind: $kind, cueCount: $cueCount)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$SubtitleActionFeedbackCopyWith<$Res>
|
||||
implements $SubtitleActionFeedbackCopyWith<$Res> {
|
||||
factory _$SubtitleActionFeedbackCopyWith(
|
||||
_SubtitleActionFeedback value,
|
||||
$Res Function(_SubtitleActionFeedback) _then,
|
||||
) = __$SubtitleActionFeedbackCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({SubtitleActionKind kind, int? cueCount});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$SubtitleActionFeedbackCopyWithImpl<$Res>
|
||||
implements _$SubtitleActionFeedbackCopyWith<$Res> {
|
||||
__$SubtitleActionFeedbackCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _SubtitleActionFeedback _self;
|
||||
final $Res Function(_SubtitleActionFeedback) _then;
|
||||
|
||||
/// Create a copy of SubtitleActionFeedback
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? kind = null, Object? cueCount = freezed}) {
|
||||
return _then(
|
||||
_SubtitleActionFeedback(
|
||||
kind: null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as SubtitleActionKind,
|
||||
cueCount: freezed == cueCount
|
||||
? _self.cueCount
|
||||
: cueCount // ignore: cast_nullable_to_non_nullable
|
||||
as int?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
mixin _$SubtitleActionException {
|
||||
SubtitleActionKind get kind;
|
||||
Object get cause;
|
||||
|
||||
/// Create a copy of SubtitleActionException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$SubtitleActionExceptionCopyWith<SubtitleActionException> get copyWith =>
|
||||
_$SubtitleActionExceptionCopyWithImpl<SubtitleActionException>(
|
||||
this as SubtitleActionException,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as SubtitleActionException;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is SubtitleActionException &&
|
||||
(identical(other.kind, _this.kind) || other.kind == _this.kind) &&
|
||||
const DeepCollectionEquality().equals(other.cause, _this.cause));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as SubtitleActionException;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.kind,
|
||||
const DeepCollectionEquality().hash(_this.cause),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as SubtitleActionException;
|
||||
return 'SubtitleActionException(kind: ${_this.kind}, cause: ${_this.cause})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $SubtitleActionExceptionCopyWith<$Res> {
|
||||
factory $SubtitleActionExceptionCopyWith(
|
||||
SubtitleActionException value,
|
||||
$Res Function(SubtitleActionException) _then,
|
||||
) = _$SubtitleActionExceptionCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({SubtitleActionKind kind, Object cause});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$SubtitleActionExceptionCopyWithImpl<$Res>
|
||||
implements $SubtitleActionExceptionCopyWith<$Res> {
|
||||
_$SubtitleActionExceptionCopyWithImpl(this._self, this._then);
|
||||
|
||||
final SubtitleActionException _self;
|
||||
final $Res Function(SubtitleActionException) _then;
|
||||
|
||||
/// Create a copy of SubtitleActionException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? kind = null, Object? cause = null}) {
|
||||
return _then(
|
||||
SubtitleActionException(
|
||||
null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as SubtitleActionKind,
|
||||
null == cause ? _self.cause : cause,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [SubtitleActionException].
|
||||
extension SubtitleActionExceptionPatterns on SubtitleActionException {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_SubtitleActionException value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionException() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_SubtitleActionException value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionException():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_SubtitleActionException value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionException() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(SubtitleActionKind kind, Object cause)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionException() when $default != null:
|
||||
return $default(_that.kind, _that.cause);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(SubtitleActionKind kind, Object cause) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionException():
|
||||
return $default(_that.kind, _that.cause);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(SubtitleActionKind kind, Object cause)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _SubtitleActionException() when $default != null:
|
||||
return $default(_that.kind, _that.cause);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _SubtitleActionException implements SubtitleActionException {
|
||||
const _SubtitleActionException(this.kind, this.cause);
|
||||
|
||||
@override
|
||||
final SubtitleActionKind kind;
|
||||
@override
|
||||
final Object cause;
|
||||
|
||||
/// Create a copy of SubtitleActionException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$SubtitleActionExceptionCopyWith<_SubtitleActionException> get copyWith =>
|
||||
__$SubtitleActionExceptionCopyWithImpl<_SubtitleActionException>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _SubtitleActionException &&
|
||||
(identical(other.kind, kind) || other.kind == kind) &&
|
||||
const DeepCollectionEquality().equals(other.cause, cause));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
kind,
|
||||
const DeepCollectionEquality().hash(cause),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'SubtitleActionException(kind: $kind, cause: $cause)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$SubtitleActionExceptionCopyWith<$Res>
|
||||
implements $SubtitleActionExceptionCopyWith<$Res> {
|
||||
factory _$SubtitleActionExceptionCopyWith(
|
||||
_SubtitleActionException value,
|
||||
$Res Function(_SubtitleActionException) _then,
|
||||
) = __$SubtitleActionExceptionCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({SubtitleActionKind kind, Object cause});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$SubtitleActionExceptionCopyWithImpl<$Res>
|
||||
implements _$SubtitleActionExceptionCopyWith<$Res> {
|
||||
__$SubtitleActionExceptionCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _SubtitleActionException _self;
|
||||
final $Res Function(_SubtitleActionException) _then;
|
||||
|
||||
/// Create a copy of SubtitleActionException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? kind = null, Object? cause = null}) {
|
||||
return _then(
|
||||
_SubtitleActionException(
|
||||
null == kind
|
||||
? _self.kind
|
||||
: kind // ignore: cast_nullable_to_non_nullable
|
||||
as SubtitleActionKind,
|
||||
null == cause ? _self.cause : cause,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'subtitle_task_actions.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
|
||||
@ProviderFor(SubtitleTaskActions)
|
||||
final subtitleTaskActionsProvider = SubtitleTaskActionsFamily._();
|
||||
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
final class SubtitleTaskActionsProvider
|
||||
extends
|
||||
$NotifierProvider<
|
||||
SubtitleTaskActions,
|
||||
AsyncValue<SubtitleActionFeedback?>
|
||||
> {
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
SubtitleTaskActionsProvider._({
|
||||
required SubtitleTaskActionsFamily super.from,
|
||||
required (EditorTimelineSession, String) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'subtitleTaskActionsProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$subtitleTaskActionsHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'subtitleTaskActionsProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
SubtitleTaskActions create() => SubtitleTaskActions();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AsyncValue<SubtitleActionFeedback?> value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AsyncValue<SubtitleActionFeedback?>>(
|
||||
value,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SubtitleTaskActionsProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$subtitleTaskActionsHash() =>
|
||||
r'6308d7270d9a363b70bb03ae8dbbbbc83d2a71b7';
|
||||
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
|
||||
final class SubtitleTaskActionsFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
SubtitleTaskActions,
|
||||
AsyncValue<SubtitleActionFeedback?>,
|
||||
AsyncValue<SubtitleActionFeedback?>,
|
||||
AsyncValue<SubtitleActionFeedback?>,
|
||||
(EditorTimelineSession, String)
|
||||
> {
|
||||
SubtitleTaskActionsFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'subtitleTaskActionsProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
|
||||
SubtitleTaskActionsProvider call(
|
||||
EditorTimelineSession session,
|
||||
String jobId,
|
||||
) => SubtitleTaskActionsProvider._(argument: (session, jobId), from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'subtitleTaskActionsProvider';
|
||||
}
|
||||
|
||||
/// One operation state is shared by the compact card and its details dialog.
|
||||
|
||||
abstract class _$SubtitleTaskActions
|
||||
extends $Notifier<AsyncValue<SubtitleActionFeedback?>> {
|
||||
late final _$args = ref.$arg as (EditorTimelineSession, String);
|
||||
EditorTimelineSession get session => _$args.$1;
|
||||
String get jobId => _$args.$2;
|
||||
|
||||
AsyncValue<SubtitleActionFeedback?> build(
|
||||
EditorTimelineSession session,
|
||||
String jobId,
|
||||
);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<
|
||||
AsyncValue<SubtitleActionFeedback?>,
|
||||
AsyncValue<SubtitleActionFeedback?>
|
||||
>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
AsyncValue<SubtitleActionFeedback?>,
|
||||
AsyncValue<SubtitleActionFeedback?>
|
||||
>,
|
||||
AsyncValue<SubtitleActionFeedback?>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:cutdex_sdk/runtime/processing_contracts.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../shared/widgets/confirm_resource_download_cancel.dart';
|
||||
import '../../shared/widgets/processing_resource_download_dialog.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
import 'processing_targets.dart';
|
||||
import 'subtitle_download.dart';
|
||||
export 'processing_targets.dart';
|
||||
|
||||
class TranscriptionDialog extends ConsumerStatefulWidget {
|
||||
const TranscriptionDialog({
|
||||
super.key,
|
||||
required this.session,
|
||||
this.asset,
|
||||
this.target,
|
||||
}) : assert(asset == null || target == null);
|
||||
const TranscriptionDialog.forCurrentTask({
|
||||
super.key,
|
||||
required this.session,
|
||||
this.asset,
|
||||
this.target,
|
||||
}) : assert(asset == null || target == null);
|
||||
final EditorTimelineSession session;
|
||||
final AssetDocument? asset;
|
||||
final TranscriptionClipTarget? target;
|
||||
@override
|
||||
ConsumerState<TranscriptionDialog> createState() =>
|
||||
_TranscriptionDialogState();
|
||||
}
|
||||
|
||||
class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
|
||||
String _translationSource = 'auto';
|
||||
String _translationTarget = 'none';
|
||||
bool _closing = false;
|
||||
late final VoidCallback _release;
|
||||
SubtitleStartProvider get _startProvider =>
|
||||
subtitleStartProvider(widget.session);
|
||||
SubtitleDownloadState get _download {
|
||||
final global = ref.read(subtitleDownloadProvider);
|
||||
final local = ref.read(_startProvider);
|
||||
if (identical(global.request?.session, widget.session) && global.running) {
|
||||
return global;
|
||||
}
|
||||
return local is SubtitleIdle ? global : local;
|
||||
}
|
||||
|
||||
bool get _ownsDownload =>
|
||||
identical(_download.request?.session, widget.session);
|
||||
bool get _installingResource =>
|
||||
_ownsDownload && _download is SubtitleDownloading;
|
||||
bool get _picking => _ownsDownload && _download is SubtitleStarting;
|
||||
bool get _resourcePaused => _ownsDownload
|
||||
? switch (_download) {
|
||||
SubtitleDownloading(:final paused) => paused,
|
||||
_ => false,
|
||||
}
|
||||
: false;
|
||||
double? get _resourceProgress => _ownsDownload
|
||||
? switch (_download) {
|
||||
SubtitleDownloading(:final progress) => progress,
|
||||
_ => null,
|
||||
}
|
||||
: null;
|
||||
ProcessingCapability get _resourceStage => _ownsDownload
|
||||
? switch (_download) {
|
||||
SubtitleDownloading(:final stage) => stage,
|
||||
_ => ProcessingCapability.transcription,
|
||||
}
|
||||
: ProcessingCapability.transcription;
|
||||
ProcessingResourceRepository? get _resourceRepository => _ownsDownload
|
||||
? switch (_download) {
|
||||
SubtitleDownloading(:final repository) => repository,
|
||||
_ => null,
|
||||
}
|
||||
: null;
|
||||
TranscriptionClipTarget? get _target =>
|
||||
_installingResource ? _download.request?.target : widget.target;
|
||||
AssetDocument? get _asset =>
|
||||
_installingResource ? _download.request?.asset : widget.asset;
|
||||
String? get _mediaId => _target?.mediaId ?? _asset?.id;
|
||||
String? get _error => !_ownsDownload
|
||||
? null
|
||||
: switch (_download) {
|
||||
SubtitleFailed(:final failure) => switch (failure) {
|
||||
SubtitleStartFailure.start => context.l10n.startTranscriptionFailed,
|
||||
SubtitleStartFailure.download =>
|
||||
context.l10n.processingResourceDownloadFailed,
|
||||
SubtitleStartFailure.engine =>
|
||||
context.l10n.subtitleEngineUnavailable,
|
||||
},
|
||||
_ => null,
|
||||
};
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_release = widget.session.retainViews();
|
||||
if (_ownsDownload && _download.running) {
|
||||
_translationSource = _download.request!.language;
|
||||
_translationTarget = _download.request!.targetLanguage;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_release();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _dismissDialog() {
|
||||
if (!mounted) return;
|
||||
final route = ModalRoute.of(context);
|
||||
if (route == null) return;
|
||||
final navigator = Navigator.of(context);
|
||||
if (route.isCurrent) {
|
||||
navigator.pop();
|
||||
} else {
|
||||
navigator.removeRoute(route);
|
||||
}
|
||||
}
|
||||
|
||||
SubtitleRequest _request() => SubtitleRequest(
|
||||
session: widget.session,
|
||||
sequence: _target?.sequence ?? widget.session.activeSequenceId,
|
||||
target: _target,
|
||||
asset: _asset,
|
||||
language: _translationSource,
|
||||
targetLanguage: _translationTarget,
|
||||
);
|
||||
Future<void> _start() => ref.read(_startProvider.notifier).start(_request());
|
||||
Future<void> _downloadResourceAndStart() {
|
||||
ref.read(_startProvider.notifier).reset();
|
||||
return ref
|
||||
.read(subtitleDownloadProvider.notifier)
|
||||
.start(_request(), download: true);
|
||||
}
|
||||
|
||||
void _toggleResourceDownload() =>
|
||||
ref.read(subtitleDownloadProvider.notifier).togglePause();
|
||||
void _cancelResourceDownload() =>
|
||||
ref.read(subtitleDownloadProvider.notifier).cancel();
|
||||
|
||||
String _translationLanguageLabel(String code) =>
|
||||
context.l10n.subtitleLanguageName(code);
|
||||
|
||||
Widget _translationLanguageMenu({
|
||||
required String label,
|
||||
required String value,
|
||||
required String other,
|
||||
required ValueChanged<String> onChanged,
|
||||
bool source = false,
|
||||
bool enabled = true,
|
||||
}) => AppField(
|
||||
label: label,
|
||||
child: AppSelect<String>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
label: label,
|
||||
value: value,
|
||||
searchable: true,
|
||||
searchHint: context.l10n.searchOptions(label),
|
||||
onChanged: enabled ? onChanged : null,
|
||||
options: [
|
||||
if (source) ...[
|
||||
AppSelectOption('auto', context.l10n.autoDetect),
|
||||
] else
|
||||
AppSelectOption('none', context.l10n.noTranslation),
|
||||
for (final code in [
|
||||
'zh',
|
||||
'en',
|
||||
'ja',
|
||||
'ko',
|
||||
if (source) 'yue',
|
||||
...m2m100LanguageNames.keys.where(
|
||||
(code) => !const {'zh', 'en', 'ja', 'ko'}.contains(code),
|
||||
),
|
||||
])
|
||||
AppSelectOption(
|
||||
code,
|
||||
_translationLanguageLabel(code),
|
||||
enabled: code != other,
|
||||
searchTerms: [
|
||||
code,
|
||||
?subtitleNativeLanguageNames[code],
|
||||
?m2m100LanguageNames[code],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget _buildModelDownloadDialog() {
|
||||
final packages =
|
||||
_resourceRepository?.catalog ?? defaultProcessingResourceCatalog;
|
||||
final service = widget.session.transcriptions;
|
||||
final downloadBytes = packages
|
||||
.where(
|
||||
(package) =>
|
||||
ProcessingResourceRepository.subtitleCapabilities.contains(
|
||||
package.capability,
|
||||
) &&
|
||||
!(package.capability == ProcessingCapability.transcription &&
|
||||
service?.recognitionAvailable == true) &&
|
||||
!(package.capability == ProcessingCapability.translation &&
|
||||
service?.translationAvailable == true),
|
||||
)
|
||||
.fold<int>(0, (total, package) => total + package.bytes);
|
||||
final totalBytes = packages
|
||||
.where(
|
||||
(package) => ProcessingResourceRepository.subtitleCapabilities
|
||||
.contains(package.capability),
|
||||
)
|
||||
.fold<int>(0, (total, package) => total + package.bytes);
|
||||
final progressTotal = _resourceRepository?.subtitleTotalBytes ?? totalBytes;
|
||||
final downloadedBytes =
|
||||
_resourceRepository?.subtitleDownloadedBytes ??
|
||||
((_resourceProgress ?? 0) * progressTotal).round();
|
||||
return ProcessingResourceDownloadDialog(
|
||||
title: context.l10n.subtitleResourceDownloadTask,
|
||||
description: context.l10n.subtitleResourcesRequired,
|
||||
resourceName: _resourceStage == ProcessingCapability.transcription
|
||||
? context.l10n.speechResourceStage
|
||||
: context.l10n.translationResourceStage,
|
||||
downloadSize: context.l10n.subtitleResourcesDownloadSize(
|
||||
formatResourceBytes(downloadBytes),
|
||||
),
|
||||
downloading: _installingResource,
|
||||
paused: _resourcePaused,
|
||||
downloadedBytes: downloadedBytes,
|
||||
totalBytes: progressTotal,
|
||||
bytesPerSecond: _resourceRepository?.subtitleDownloadBytesPerSecond ?? 0,
|
||||
error: _error,
|
||||
downloadButtonKey: const Key('download-transcription-resource'),
|
||||
pauseButtonKey: const Key('download-transcription-resource'),
|
||||
backgroundButtonKey: const Key('background-transcription-resource'),
|
||||
onCancel: () async {
|
||||
if (_installingResource &&
|
||||
!await confirmResourceDownloadCancellation(context)) {
|
||||
return;
|
||||
}
|
||||
if (!mounted) return;
|
||||
_cancelResourceDownload();
|
||||
_dismissDialog();
|
||||
},
|
||||
onDownload: _downloadResourceAndStart,
|
||||
onTogglePause: _toggleResourceDownload,
|
||||
onBackground: _dismissDialog,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(subtitleDownloadProvider);
|
||||
ref.watch(_startProvider);
|
||||
void handleResult(SubtitleDownloadState next) {
|
||||
if (_closing || !identical(next.request?.session, widget.session)) return;
|
||||
if (next is SubtitleStarted || next is SubtitleCancelled) {
|
||||
_closing = true;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
final messenger = ScaffoldMessenger.maybeOf(context);
|
||||
final message = context.l10n.subtitleTaskStarted;
|
||||
_dismissDialog();
|
||||
if (next is SubtitleStarted) {
|
||||
messenger?.showSnackBar(SnackBar(content: Text(message)));
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
ref.listen(subtitleDownloadProvider, (_, next) => handleResult(next));
|
||||
ref.listen(_startProvider, (_, next) => handleResult(next));
|
||||
return ListenableBuilder(
|
||||
listenable: widget.session,
|
||||
builder: (context, _) {
|
||||
final service = widget.session.transcriptions;
|
||||
if (service?.recognitionAvailable != true ||
|
||||
service?.translationAvailable != true ||
|
||||
_installingResource) {
|
||||
return _buildModelDownloadDialog();
|
||||
}
|
||||
final busy =
|
||||
(service?.tasks.any((task) => !task.terminal) ?? false) ||
|
||||
(service?.translationTasks.any((task) => !task.terminal) ?? false);
|
||||
return AppDialog(
|
||||
title: _target == null
|
||||
? context.l10n.transcribe
|
||||
: context.l10n.generateCaptions,
|
||||
withShadow: true,
|
||||
width: 560,
|
||||
actions: [
|
||||
if (_mediaId != null && service != null)
|
||||
FilledButton(
|
||||
onPressed: busy || _picking || !widget.session.acceptsEdits
|
||||
? null
|
||||
: _start,
|
||||
child: Text(context.l10n.generateCaptions),
|
||||
),
|
||||
],
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_translationLanguageMenu(
|
||||
label: context.l10n.sourceLanguage,
|
||||
value: _translationSource,
|
||||
other: _translationTarget,
|
||||
source: true,
|
||||
enabled: !busy && !_picking,
|
||||
onChanged: (value) =>
|
||||
setState(() => _translationSource = value),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.compact),
|
||||
_translationLanguageMenu(
|
||||
label: context.l10n.translationLanguage,
|
||||
value: _translationTarget,
|
||||
other: _translationSource,
|
||||
enabled:
|
||||
service?.translationAvailable == true &&
|
||||
!busy &&
|
||||
!_picking,
|
||||
onChanged: (value) =>
|
||||
setState(() => _translationTarget = value),
|
||||
),
|
||||
if (service?.translationAvailable != true)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: AppSpacing.small),
|
||||
child: Text(context.l10n.translationNotConfigured),
|
||||
),
|
||||
if (_error != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: AppSpacing.compact),
|
||||
child: Text(_error!),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/media_availability.dart';
|
||||
|
||||
class UnavailableMediaPlaceholder extends StatelessWidget {
|
||||
const UnavailableMediaPlaceholder({
|
||||
super.key,
|
||||
required this.availability,
|
||||
this.showLabel = true,
|
||||
this.isPreview = false,
|
||||
});
|
||||
final MediaAvailability availability;
|
||||
final bool showLabel;
|
||||
final bool isPreview;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final label = availability == MediaAvailability.missing
|
||||
? context.l10n.mediaMissing
|
||||
: context.l10n.mediaUnavailable;
|
||||
// Project covers share the canvas background, including missing media.
|
||||
return ColoredBox(
|
||||
color: isPreview
|
||||
? Colors.transparent
|
||||
: AppSurfaces.of(context).previewBackground,
|
||||
child: Center(
|
||||
child: FittedBox(
|
||||
fit: BoxFit.scaleDown,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.broken_image_outlined,
|
||||
size: isPreview ? 32 : 24,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
if (showLabel) ...[
|
||||
const SizedBox(height: AppSpacing.gap),
|
||||
Text(
|
||||
label,
|
||||
style:
|
||||
(isPreview
|
||||
? theme.textTheme.bodyMedium
|
||||
: theme.textTheme.bodySmall)
|
||||
?.copyWith(color: theme.colorScheme.error),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import 'package:cutdex_sdk/project.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'media_asset_cover.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
class VisualAssetTile extends StatelessWidget {
|
||||
const VisualAssetTile({super.key, required this.asset, this.showName = true});
|
||||
final AssetDocument asset;
|
||||
final bool showName;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
AspectRatio(
|
||||
key: ValueKey('visual-cover-${asset.id}'),
|
||||
aspectRatio: 16 / 9,
|
||||
child: ColoredBox(
|
||||
color: AppSurfaces.of(context).previewBackground,
|
||||
child: MediaAssetCover(
|
||||
asset: asset,
|
||||
fallback: Center(
|
||||
child: Icon(
|
||||
asset.metadata['kind'] == 'image'
|
||||
? Icons.image_outlined
|
||||
: Icons.movie_outlined,
|
||||
size: AppIconSize.emptyState,
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
if (showName) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Tooltip(
|
||||
message: asset.name,
|
||||
child: Text(
|
||||
asset.name,
|
||||
key: ValueKey('visual-name-${asset.id}'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
class FullscreenPlaybackBar extends StatefulWidget {
|
||||
const FullscreenPlaybackBar({
|
||||
super.key,
|
||||
required this.positionTick,
|
||||
required this.durationTick,
|
||||
required this.frameTick,
|
||||
required this.playing,
|
||||
required this.onPlayPause,
|
||||
required this.onSeek,
|
||||
required this.onExit,
|
||||
required this.onScrubStart,
|
||||
required this.onScrubUpdate,
|
||||
required this.onScrubEnd,
|
||||
});
|
||||
|
||||
final int positionTick;
|
||||
final int durationTick;
|
||||
final int frameTick;
|
||||
final bool playing;
|
||||
final VoidCallback? onPlayPause;
|
||||
final ValueChanged<int>? onSeek;
|
||||
final VoidCallback? onExit;
|
||||
final VoidCallback? onScrubStart;
|
||||
final ValueChanged<int>? onScrubUpdate;
|
||||
final ValueChanged<int>? onScrubEnd;
|
||||
|
||||
@override
|
||||
State<FullscreenPlaybackBar> createState() => _FullscreenPlaybackBarState();
|
||||
}
|
||||
|
||||
class _FullscreenPlaybackBarState extends State<FullscreenPlaybackBar> {
|
||||
double? _dragPosition;
|
||||
|
||||
int get _position => (_dragPosition?.round() ?? widget.positionTick).clamp(
|
||||
0,
|
||||
widget.durationTick,
|
||||
);
|
||||
|
||||
void _step(int direction) {
|
||||
final tick = (_position ~/ widget.frameTick + direction) * widget.frameTick;
|
||||
widget.onSeek?.call(tick.clamp(0, widget.durationTick));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
if (_dragPosition case final value?) {
|
||||
final end = widget.onScrubEnd;
|
||||
scheduleMicrotask(() => end?.call(value.round()));
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final enabled = widget.onSeek != null && widget.durationTick > 0;
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
return SizedBox(
|
||||
key: const Key('fullscreen-playback-bar'),
|
||||
height: 76,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(
|
||||
AppSpacing.compact,
|
||||
AppSpacing.tiny,
|
||||
AppSpacing.compact,
|
||||
AppSpacing.small,
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 36,
|
||||
child: Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: _button(
|
||||
context,
|
||||
Icons.first_page,
|
||||
context.l10n.previewGoToStart,
|
||||
enabled ? () => widget.onSeek!(0) : null,
|
||||
),
|
||||
),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
_button(
|
||||
context,
|
||||
Icons.skip_previous,
|
||||
context.l10n.previewPreviousFrame,
|
||||
enabled && _position > 0 ? () => _step(-1) : null,
|
||||
),
|
||||
_button(
|
||||
context,
|
||||
widget.playing ? Icons.pause : Icons.play_arrow,
|
||||
widget.playing ? context.l10n.pause : context.l10n.play,
|
||||
widget.onPlayPause,
|
||||
size: 32,
|
||||
),
|
||||
_button(
|
||||
context,
|
||||
Icons.skip_next,
|
||||
context.l10n.previewNextFrame,
|
||||
enabled && _position < widget.durationTick
|
||||
? () => _step(1)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: _button(
|
||||
context,
|
||||
Icons.fullscreen_exit,
|
||||
context.l10n.exitPreviewFullscreen,
|
||||
widget.onExit,
|
||||
key: const Key('preview-fullscreen'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
_timeLabel(context, _time(_position)),
|
||||
Expanded(
|
||||
child: SliderTheme(
|
||||
data: SliderTheme.of(context).copyWith(
|
||||
trackHeight: 4,
|
||||
activeTrackColor: colors.outline,
|
||||
inactiveTrackColor: colors.surfaceContainerHighest,
|
||||
thumbColor: colors.onSurface,
|
||||
overlayColor: colors.onSurface.withValues(alpha: .12),
|
||||
thumbShape: const RoundSliderThumbShape(
|
||||
enabledThumbRadius: 5,
|
||||
disabledThumbRadius: 5,
|
||||
elevation: 0,
|
||||
pressedElevation: 0,
|
||||
),
|
||||
overlayShape: const RoundSliderOverlayShape(
|
||||
overlayRadius: 10,
|
||||
),
|
||||
trackShape: const RoundedRectSliderTrackShape(),
|
||||
),
|
||||
child: Slider(
|
||||
key: const Key('fullscreen-progress'),
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.small,
|
||||
),
|
||||
value: _position.toDouble(),
|
||||
max: widget.durationTick > 0
|
||||
? widget.durationTick.toDouble()
|
||||
: 1,
|
||||
onChangeStart: enabled
|
||||
? (value) {
|
||||
setState(() => _dragPosition = value);
|
||||
widget.onScrubStart?.call();
|
||||
}
|
||||
: null,
|
||||
onChanged: enabled
|
||||
? (value) {
|
||||
setState(() => _dragPosition = value);
|
||||
widget.onScrubUpdate?.call(value.round());
|
||||
}
|
||||
: null,
|
||||
onChangeEnd: enabled
|
||||
? (value) {
|
||||
setState(() => _dragPosition = null);
|
||||
widget.onScrubEnd?.call(value.round());
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
),
|
||||
_timeLabel(
|
||||
context,
|
||||
'-${_time(widget.durationTick - _position)}',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _button(
|
||||
BuildContext context,
|
||||
IconData icon,
|
||||
String tooltip,
|
||||
VoidCallback? onPressed, {
|
||||
double size = 20,
|
||||
Key? key,
|
||||
}) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
return IconButton(
|
||||
key: key,
|
||||
tooltip: tooltip,
|
||||
onPressed: onPressed,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints: const BoxConstraints.tightFor(width: 36, height: 36),
|
||||
visualDensity: VisualDensity.compact,
|
||||
color: colors.onSurface,
|
||||
disabledColor: colors.onSurface.withValues(alpha: .38),
|
||||
icon: Icon(icon, size: size),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _timeLabel(BuildContext context, String value) => SizedBox(
|
||||
width: 62,
|
||||
child: Text(
|
||||
value,
|
||||
textAlign: TextAlign.center,
|
||||
maxLines: 1,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
fontFeatures: [const FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
String _time(int tick) {
|
||||
final seconds = tick ~/ TimelineClock.ticksPerSecond;
|
||||
final minutes = seconds ~/ 60;
|
||||
final tail = '${seconds % 60}'.padLeft(2, '0');
|
||||
if (minutes < 60) return '${minutes.toString().padLeft(2, '0')}:$tail';
|
||||
return '${minutes ~/ 60}:${(minutes % 60).toString().padLeft(2, '0')}:$tail';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
|
||||
/// Moves the existing preview into the root overlay, retaining its native view.
|
||||
class PreviewFullscreenHost extends StatefulWidget {
|
||||
const PreviewFullscreenHost({super.key, required this.child});
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
State<PreviewFullscreenHost> createState() => _PreviewFullscreenHostState();
|
||||
}
|
||||
|
||||
class _PreviewFullscreenHostState extends State<PreviewFullscreenHost> {
|
||||
late final _nativeSession = NativeFullscreenSession(
|
||||
onExit: () {
|
||||
if (!mounted) return;
|
||||
_overlay.hide();
|
||||
setState(() => _fullscreen = false);
|
||||
},
|
||||
);
|
||||
final _overlay = OverlayPortalController();
|
||||
final _contentKey = GlobalKey();
|
||||
bool _fullscreen = false;
|
||||
bool _busy = false;
|
||||
bool get _native => !kIsWeb && defaultTargetPlatform == TargetPlatform.macOS;
|
||||
|
||||
Future<void> _toggle() async {
|
||||
if (_busy) return;
|
||||
final entering = !_fullscreen;
|
||||
setState(() {
|
||||
_busy = true;
|
||||
_fullscreen = entering;
|
||||
});
|
||||
if (entering) {
|
||||
_overlay.show();
|
||||
if (_native) {
|
||||
_nativeSession.attach();
|
||||
}
|
||||
} else {
|
||||
_overlay.hide();
|
||||
}
|
||||
try {
|
||||
if (_native) await _nativeSession.setFullscreen(entering);
|
||||
} catch (error) {
|
||||
if (mounted) {
|
||||
_overlay.hide();
|
||||
setState(() => _fullscreen = false);
|
||||
debugPrint('Could not change preview fullscreen: $error');
|
||||
}
|
||||
} finally {
|
||||
if (mounted) setState(() => _busy = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nativeSession.dispose(exitFullscreen: _native && _fullscreen);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fullscreenTheme = AppTheme.previewFullscreenTheme;
|
||||
final previewBackground = fullscreenTheme
|
||||
.extension<AppSurfaces>()!
|
||||
.previewBackground;
|
||||
final content = PreviewFullscreenScope(
|
||||
key: _contentKey,
|
||||
fullscreen: _fullscreen,
|
||||
toggle: _busy ? null : _toggle,
|
||||
child: widget.child,
|
||||
);
|
||||
return OverlayPortal(
|
||||
overlayLocation: OverlayChildLocation.rootOverlay,
|
||||
controller: _overlay,
|
||||
overlayChildBuilder: (context) => Positioned.fill(
|
||||
child: Theme(
|
||||
data: fullscreenTheme,
|
||||
child: Material(
|
||||
color: previewBackground,
|
||||
child: CallbackShortcuts(
|
||||
bindings: {
|
||||
const SingleActivator(LogicalKeyboardKey.escape): () {
|
||||
if (_fullscreen && !_busy) unawaited(_toggle());
|
||||
},
|
||||
},
|
||||
child: Focus(autofocus: true, child: content),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
child: _fullscreen ? const SizedBox.expand() : content,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PreviewFullscreenScope extends InheritedWidget {
|
||||
const PreviewFullscreenScope({
|
||||
super.key,
|
||||
required this.fullscreen,
|
||||
required this.toggle,
|
||||
required super.child,
|
||||
});
|
||||
final bool fullscreen;
|
||||
final VoidCallback? toggle;
|
||||
|
||||
static PreviewFullscreenScope? of(BuildContext context) =>
|
||||
context.dependOnInheritedWidgetOfExactType<PreviewFullscreenScope>();
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(PreviewFullscreenScope oldWidget) =>
|
||||
fullscreen != oldWidget.fullscreen || toggle != oldWidget.toggle;
|
||||
}
|
||||
|
||||
/// Keeps the canvas mounted while the toolbar floats over fullscreen playback.
|
||||
class PreviewFullscreenLayout extends StatelessWidget {
|
||||
const PreviewFullscreenLayout({
|
||||
super.key,
|
||||
required this.canvas,
|
||||
required this.toolbar,
|
||||
});
|
||||
final Widget canvas;
|
||||
final Widget toolbar;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fullscreen = PreviewFullscreenScope.of(context)?.fullscreen == true;
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
Positioned.fill(
|
||||
bottom: fullscreen ? 0 : AppControlSize.panelHeader,
|
||||
child: canvas,
|
||||
),
|
||||
Align(
|
||||
alignment: Alignment.bottomCenter,
|
||||
child: Container(
|
||||
margin: fullscreen
|
||||
? const EdgeInsets.only(
|
||||
left: AppSpacing.extraLarge,
|
||||
right: AppSpacing.extraLarge,
|
||||
bottom: AppSpacing.emptyState,
|
||||
)
|
||||
: EdgeInsets.zero,
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: fullscreen ? 560 : double.infinity,
|
||||
),
|
||||
decoration: fullscreen
|
||||
? BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainer
|
||||
.withValues(alpha: .93),
|
||||
borderRadius: BorderRadius.circular(AppRadius.large),
|
||||
)
|
||||
: null,
|
||||
child: toolbar,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
|
||||
import '../../errors/app_failure.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
|
||||
String previewErrorMessage(Object e, AppLocalizations l10n) => switch (e) {
|
||||
AppException(:final failure) => l10n.failureMessage(failure),
|
||||
EditorMediaException(code: EditorMediaError.invalidTrack) =>
|
||||
l10n.previewInvalidTrack,
|
||||
EditorMediaException(code: EditorMediaError.unsupportedColorInterpretation) =>
|
||||
l10n.colorBackendUnsupported,
|
||||
ExecutionException(code: ExecutionErrorCode.missingMedia) =>
|
||||
l10n.previewMissingBinding,
|
||||
ExecutionException() => l10n.previewUnsupportedEdits,
|
||||
RuntimeException(code: 'unsupported') => l10n.previewUnsupportedConfiguration,
|
||||
RuntimeException(code: 'invalidArgument', :final message)
|
||||
when message.contains('HDR to SDR requires explicit tone mapping') =>
|
||||
l10n.previewHdrUnsupported,
|
||||
RuntimeException(code: 'invalidArgument', :final message)
|
||||
when message.contains('Audio source interval exceeds track') =>
|
||||
l10n.previewAudioOutOfRange,
|
||||
RuntimeException(code: 'invalidArgument', :final message) =>
|
||||
l10n.previewParameterError(message),
|
||||
RuntimeException(code: 'resourceMissing') => l10n.previewResourceMissing,
|
||||
RuntimeException(code: 'playback/failed', :final details)
|
||||
when details['nativeDomain'] == 'AVFoundationErrorDomain' &&
|
||||
details['nativeCode'] == '-11841' =>
|
||||
l10n.previewInvalidComposition,
|
||||
Error() => l10n.previewInvalidData,
|
||||
String message => message,
|
||||
_ => l10n.previewFailed,
|
||||
};
|
||||
@@ -0,0 +1,732 @@
|
||||
import '../../diagnostics/app_diagnostics.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/features/properties/canvas_presets.dart';
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
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/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/media_availability.dart';
|
||||
import '../../workspace/preview_controller_registry.dart';
|
||||
import '../../workspace/preview_target.dart';
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import '../media/audio_asset_tile.dart';
|
||||
import '../media/unavailable_media_placeholder.dart';
|
||||
import 'fullscreen_playback_bar.dart';
|
||||
import 'preview_fullscreen.dart';
|
||||
import 'preview_messages.dart';
|
||||
|
||||
export '../../workspace/preview_target.dart' show runtimeConnectionProvider;
|
||||
|
||||
part 'preview_panel.g.dart';
|
||||
|
||||
/// The editor failed before a native preview session could be created.
|
||||
final class EditorSessionStartupException implements Exception {
|
||||
const EditorSessionStartupException(this.cause);
|
||||
final Object cause;
|
||||
@override
|
||||
String toString() => 'Editor session startup failed: $cause';
|
||||
}
|
||||
|
||||
@riverpod
|
||||
FutureOr<Raw<PreviewController?>> editorPreview(
|
||||
Ref ref,
|
||||
String projectId,
|
||||
String timelineId,
|
||||
) {
|
||||
final ids = (projectId, timelineId);
|
||||
|
||||
final timelineState = ref.watch(
|
||||
editorTimelineProvider(projectId, timelineId),
|
||||
);
|
||||
if (timelineState case AsyncData(:final value)) {
|
||||
return _preparePreview(ref, ids, value);
|
||||
}
|
||||
if (timelineState case AsyncError(:final error, :final stackTrace)) {
|
||||
AppDiagnostics.failure(
|
||||
'preview',
|
||||
'editorStartup',
|
||||
error,
|
||||
stackTrace,
|
||||
context: {'projectId': projectId, 'timelineId': timelineId},
|
||||
);
|
||||
Error.throwWithStackTrace(EditorSessionStartupException(error), stackTrace);
|
||||
}
|
||||
return _preparePreviewAfterTimeline(ref, ids);
|
||||
}
|
||||
|
||||
Future<PreviewController?> _preparePreviewAfterTimeline(
|
||||
Ref ref,
|
||||
(String, String) ids,
|
||||
) async {
|
||||
try {
|
||||
final timeline = await ref.read(
|
||||
editorTimelineProvider(ids.$1, ids.$2).future,
|
||||
);
|
||||
return await _preparePreview(ref, ids, timeline);
|
||||
} catch (error, stack) {
|
||||
if (error is EditorSessionStartupException) rethrow;
|
||||
AppDiagnostics.failure(
|
||||
'preview',
|
||||
'editorStartup',
|
||||
error,
|
||||
stack,
|
||||
context: {'projectId': ids.$1, 'timelineId': ids.$2},
|
||||
);
|
||||
Error.throwWithStackTrace(EditorSessionStartupException(error), stack);
|
||||
}
|
||||
}
|
||||
|
||||
FutureOr<PreviewController?> _preparePreview(
|
||||
Ref ref,
|
||||
(String, String) ids,
|
||||
EditorTimelineSession timeline,
|
||||
) {
|
||||
final sequence = timeline.activeSequenceId;
|
||||
if (sequence == null || timeline.sequenceDurationTicks(sequence) == 0) {
|
||||
void startWhenContentExists() {
|
||||
final active = timeline.activeSequenceId;
|
||||
if (active != null && timeline.sequenceDurationTicks(active) > 0) {
|
||||
unawaited(
|
||||
ref
|
||||
.read(previewControllerRegistryProvider)
|
||||
.invalidate(ids)
|
||||
.catchError((Object _) {}),
|
||||
);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
timeline.addListener(startWhenContentExists);
|
||||
ref.onDispose(() => timeline.removeListener(startWhenContentExists));
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
if (!ref.mounted) throw StateError('Editor closed');
|
||||
final result = ref
|
||||
.read(previewControllerRegistryProvider)
|
||||
.prepare(ids, timeline);
|
||||
if (result case Future<PreviewController?> future) {
|
||||
return future.catchError((Object error, StackTrace stack) {
|
||||
AppDiagnostics.failure(
|
||||
'preview',
|
||||
'nativeStartup',
|
||||
error,
|
||||
stack,
|
||||
context: {'projectId': ids.$1, 'timelineId': ids.$2},
|
||||
);
|
||||
Error.throwWithStackTrace(error, stack);
|
||||
});
|
||||
}
|
||||
return result;
|
||||
} catch (error, stack) {
|
||||
AppDiagnostics.failure(
|
||||
'preview',
|
||||
'nativeStartup',
|
||||
error,
|
||||
stack,
|
||||
context: {'projectId': ids.$1, 'timelineId': ids.$2},
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
class EditorPreviewPanel extends StatelessWidget {
|
||||
const EditorPreviewPanel({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => PreviewFullscreenHost(
|
||||
child: _EditorPreviewContent(projectId: projectId, timelineId: timelineId),
|
||||
);
|
||||
}
|
||||
|
||||
class _EditorPreviewContent extends ConsumerWidget {
|
||||
const _EditorPreviewContent({
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final provider = editorPreviewProvider(projectId, timelineId);
|
||||
final state = ref.watch(provider);
|
||||
final controller = state.asData?.value;
|
||||
Widget panel() {
|
||||
final activeController = controller;
|
||||
final showCanvas =
|
||||
state.hasError ||
|
||||
(activeController != null &&
|
||||
(activeController.durationTick > 0 ||
|
||||
activeController.error != null));
|
||||
final overlayBuilder =
|
||||
activeController != null &&
|
||||
PreviewFullscreenScope.of(context)?.fullscreen != true &&
|
||||
activeController.session != null &&
|
||||
activeController.error == null
|
||||
? (Rect rect) => ListenableBuilder(
|
||||
listenable: activeController.positionChanges,
|
||||
builder: (context, _) => Theme(
|
||||
data: AppTheme.previewCanvasTheme,
|
||||
child:
|
||||
activeController.maskEditingElement != null ||
|
||||
activeController.obscureEditingElement != null
|
||||
? MaskInteractionOverlay(
|
||||
controller: activeController,
|
||||
canvasRect: rect,
|
||||
obscure: activeController.obscureEditingElement != null,
|
||||
)
|
||||
: PreviewInteractionOverlay(
|
||||
onError: (_) => ScaffoldMessenger.maybeOf(context)
|
||||
?.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
context.l10n.canvasTransformFailed,
|
||||
),
|
||||
),
|
||||
),
|
||||
controller: activeController,
|
||||
canvasRect: rect,
|
||||
),
|
||||
),
|
||||
)
|
||||
: null;
|
||||
return WorkspacePanel(
|
||||
headerHeight: 0,
|
||||
showHeaderDivider: false,
|
||||
child: PreviewFullscreenLayout(
|
||||
canvas: showCanvas
|
||||
? Padding(
|
||||
padding:
|
||||
PreviewFullscreenScope.of(context)?.fullscreen == true
|
||||
? EdgeInsets.zero
|
||||
: AppSpacing.panelSection,
|
||||
child: PreviewCanvas(
|
||||
alignment: Alignment.center,
|
||||
horizontalPadding: 0,
|
||||
backgroundColor: AppSurfaces.of(context).previewBackground,
|
||||
overlayBuilder: overlayBuilder,
|
||||
aspectRatio:
|
||||
(activeController?.canvas ?? ProjectCanvas.widescreen)
|
||||
.aspectRatio,
|
||||
child: Theme(
|
||||
data: AppTheme.previewCanvasTheme,
|
||||
child: Builder(
|
||||
builder: (context) => state.when(
|
||||
loading: () => const DelayedLoadingIndicator(
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
error: (error, _) => Center(
|
||||
child: SingleChildScrollView(
|
||||
primary: false,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
error is EditorSessionStartupException
|
||||
? context.l10n.editorSessionStartFailed
|
||||
: error is RuntimeException &&
|
||||
error.code == 'unsupported'
|
||||
? context.l10n.nativePreviewUnsupported
|
||||
: context.l10n.previewStartFailed,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
if (error
|
||||
is EditorSessionStartupException) {
|
||||
ref.invalidate(
|
||||
editorTimelineProvider(
|
||||
projectId,
|
||||
timelineId,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
unawaited(
|
||||
ref
|
||||
.read(
|
||||
previewControllerRegistryProvider,
|
||||
)
|
||||
.invalidate((
|
||||
projectId,
|
||||
timelineId,
|
||||
)),
|
||||
);
|
||||
ref.invalidate(provider);
|
||||
}
|
||||
},
|
||||
child: Text(context.l10n.retry),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
data: (preview) {
|
||||
if (preview == null) {
|
||||
return const SizedBox.expand(
|
||||
key: Key('empty-preview-area'),
|
||||
);
|
||||
}
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
if (preview.session case final session?)
|
||||
RuntimePreview(session: session),
|
||||
ListenableBuilder(
|
||||
listenable: preview.positionChanges,
|
||||
builder: (context, _) {
|
||||
final unavailable =
|
||||
preview.unavailableAtPlayhead;
|
||||
if (preview.error != null ||
|
||||
unavailable.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
return IgnorePointer(
|
||||
child: Align(
|
||||
alignment: Alignment.bottomCenter,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(
|
||||
AppSpacing.medium,
|
||||
),
|
||||
child: Text(
|
||||
context.l10n.mediaOffline(
|
||||
unavailable.join(', '),
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
if (preview.error != null ||
|
||||
preview.durationTick == 0)
|
||||
ColoredBox(
|
||||
color: AppSurfaces.of(context)
|
||||
.previewBackground,
|
||||
child: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(
|
||||
AppSpacing.medium,
|
||||
),
|
||||
child: Text(
|
||||
preview.error == null
|
||||
? context.l10n.noPreviewContent
|
||||
: previewErrorMessage(
|
||||
preview.error!,
|
||||
context.l10n,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
: const SizedBox.expand(key: Key('empty-preview-area')),
|
||||
toolbar: _PreviewToolbar(controller: controller),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
final target = ref.watch(previewTargetProvider(projectId, timelineId));
|
||||
final navigation = ref.watch(
|
||||
previewNavigationProvider(projectId, timelineId),
|
||||
);
|
||||
return CallbackShortcuts(
|
||||
bindings: PreviewFullscreenScope.of(context)?.fullscreen == true
|
||||
? {
|
||||
const SingleActivator(LogicalKeyboardKey.space): () =>
|
||||
target.togglePlayback?.call(),
|
||||
}
|
||||
: const {},
|
||||
child: switch (navigation) {
|
||||
SourcePreviewTarget(:final asset, :final controller)
|
||||
when controller != null =>
|
||||
_SourcePreviewPanel(
|
||||
key: ValueKey(asset.id),
|
||||
asset: asset,
|
||||
projectId: projectId,
|
||||
source: controller,
|
||||
),
|
||||
_ => Builder(
|
||||
builder: (context) {
|
||||
target.togglePlayback = controller == null
|
||||
? null
|
||||
: () => unawaited(controller.togglePlayback());
|
||||
return controller == null
|
||||
? panel()
|
||||
: ListenableBuilder(
|
||||
listenable: controller,
|
||||
builder: (_, _) => panel(),
|
||||
);
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SourcePreviewPanel extends ConsumerWidget {
|
||||
const _SourcePreviewPanel({
|
||||
super.key,
|
||||
required this.asset,
|
||||
required this.projectId,
|
||||
required this.source,
|
||||
});
|
||||
final AssetDocument asset;
|
||||
final String projectId;
|
||||
final SourcePreviewController source;
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final availability = ref
|
||||
.watch(mediaAvailabilityProvider(projectId, asset))
|
||||
.asData
|
||||
?.value;
|
||||
return ListenableBuilder(
|
||||
listenable: source,
|
||||
builder: (context, _) {
|
||||
// The availability probe can finish while a newly dropped file is
|
||||
// still switching security-scoped leases. Once the runtime has opened
|
||||
// the source, that live session is stronger evidence than the stale
|
||||
// probe result and must not be covered by an unavailable placeholder.
|
||||
final unavailable =
|
||||
availability != null &&
|
||||
availability != MediaAvailability.available &&
|
||||
source.session == null &&
|
||||
source.image == null;
|
||||
return CallbackShortcuts(
|
||||
bindings: {
|
||||
const SingleActivator(LogicalKeyboardKey.space):
|
||||
source.togglePlayback,
|
||||
},
|
||||
child: Focus(
|
||||
autofocus: true,
|
||||
child: WorkspacePanel(
|
||||
title: asset.name,
|
||||
showHeaderDivider: false,
|
||||
headerHeight:
|
||||
PreviewFullscreenScope.of(context)?.fullscreen == true
|
||||
? 0
|
||||
: AppControlSize.panelHeader,
|
||||
child: PreviewFullscreenLayout(
|
||||
canvas: Padding(
|
||||
padding:
|
||||
PreviewFullscreenScope.of(context)?.fullscreen == true
|
||||
? EdgeInsets.zero
|
||||
: AppSpacing.panelSection,
|
||||
child: PreviewCanvas(
|
||||
alignment: Alignment.center,
|
||||
horizontalPadding: 0,
|
||||
backgroundColor: AppSurfaces.of(context).previewBackground,
|
||||
aspectRatio: source.aspectRatio,
|
||||
child: unavailable
|
||||
? UnavailableMediaPlaceholder(
|
||||
availability: availability,
|
||||
isPreview: true,
|
||||
)
|
||||
: Theme(
|
||||
data: AppTheme.previewCanvasTheme,
|
||||
child: Builder(
|
||||
builder: (context) {
|
||||
if (source.error case final error?) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(
|
||||
AppSpacing.medium,
|
||||
),
|
||||
child: Text(
|
||||
previewErrorMessage(
|
||||
error,
|
||||
context.l10n,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (source.busy &&
|
||||
source.session == null &&
|
||||
source.image == null) {
|
||||
return DelayedLoadingIndicator(
|
||||
key: ValueKey(source),
|
||||
child: const Center(
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
);
|
||||
}
|
||||
if (source.image case final bytes?) {
|
||||
return Image.memory(
|
||||
bytes,
|
||||
fit: BoxFit.contain,
|
||||
);
|
||||
}
|
||||
if (source.session case final session?) {
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
RuntimePreview(session: session),
|
||||
if (source.audioOnly)
|
||||
IgnorePointer(
|
||||
child: AudioAssetTile(
|
||||
asset: asset,
|
||||
showName: false,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
toolbar: _PreviewToolbar(controller: null, source: source),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PreviewToolbar extends StatelessWidget {
|
||||
const _PreviewToolbar({required this.controller, this.source});
|
||||
|
||||
final PreviewController? controller;
|
||||
final SourcePreviewController? source;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final listenable = source == null && controller != null
|
||||
? Listenable.merge([controller!, controller!.positionChanges])
|
||||
: source;
|
||||
if (listenable != null) {
|
||||
return ListenableBuilder(
|
||||
listenable: listenable,
|
||||
builder: (context, _) => _build(context),
|
||||
);
|
||||
}
|
||||
return _build(context);
|
||||
}
|
||||
|
||||
Widget _build(BuildContext context) {
|
||||
final preview = controller;
|
||||
final playing = source?.playing ?? preview?.playing ?? false;
|
||||
final frameDuration =
|
||||
source?.frameDuration ??
|
||||
preview?.frameDuration ??
|
||||
TimelineFormat.fps30.frameDuration;
|
||||
if (PreviewFullscreenScope.of(context) case final fullscreen?
|
||||
when fullscreen.fullscreen) {
|
||||
final duration = source?.durationTick ?? preview?.durationTick ?? 0;
|
||||
final frameTick = TimelineClock.standard.toTicks(frameDuration);
|
||||
final canPlay = source?.canPlay ?? preview?.canPlay ?? false;
|
||||
Future<void> seek(int requested) async {
|
||||
final lastTick = duration > 0
|
||||
? ((duration - 1) ~/ frameTick) * frameTick
|
||||
: 0;
|
||||
final tick = requested.clamp(0, lastTick);
|
||||
try {
|
||||
final time = CommandTime(tick, TimelineClock.ticksPerSecond);
|
||||
if (source case final source?) {
|
||||
await source.control(SourcePreviewAction.seek, at: time);
|
||||
} else if (preview?.activeSequence() case final sequence?) {
|
||||
await preview!.controlPreview(
|
||||
sequence,
|
||||
PreviewAction.seek,
|
||||
at: time,
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
|
||||
SnackBar(content: Text(previewErrorMessage(error, context.l10n))),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final sequence = preview?.activeSequence();
|
||||
final view = sequence == null ? null : preview!.viewForSequence(sequence);
|
||||
void updateScrub(int tick) {
|
||||
if (source case final source?) {
|
||||
source.updateScrubbing(tick);
|
||||
} else {
|
||||
view?.seekTo(tick.clamp(0, duration));
|
||||
}
|
||||
}
|
||||
|
||||
return FullscreenPlaybackBar(
|
||||
positionTick: source?.positionTick ?? preview?.positionTick ?? 0,
|
||||
durationTick: duration,
|
||||
frameTick: frameTick,
|
||||
playing: playing,
|
||||
onPlayPause: canPlay
|
||||
? (source?.togglePlayback ?? preview?.togglePlayback)
|
||||
: null,
|
||||
onSeek: canPlay && duration > 0
|
||||
? (tick) => unawaited(seek(tick))
|
||||
: null,
|
||||
onExit: fullscreen.toggle,
|
||||
onScrubStart: source?.beginScrubbing ?? view?.beginScrubbing,
|
||||
onScrubUpdate: updateScrub,
|
||||
onScrubEnd: (tick) {
|
||||
updateScrub(tick);
|
||||
if (source case final source?) {
|
||||
source.endScrubbing();
|
||||
} else {
|
||||
view?.endScrubbing();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
return SizedBox(
|
||||
key: const Key('preview-toolbar'),
|
||||
height: AppControlSize.panelHeader,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
TextSpan(
|
||||
text: _time(
|
||||
source?.positionTick ?? preview?.positionTick ?? 0,
|
||||
frameDuration,
|
||||
),
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
TextSpan(
|
||||
text:
|
||||
' / ${_time(source?.durationTick ?? preview?.durationTick ?? 0, frameDuration)}',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
fontFeatures: [const FontFeature.tabularFigures()],
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: playing ? context.l10n.pause : context.l10n.play,
|
||||
onPressed: source != null
|
||||
? (source!.canPlay ? source!.togglePlayback : null)
|
||||
: preview != null && preview.canPlay
|
||||
? preview.togglePlayback
|
||||
: null,
|
||||
icon: Icon(playing ? Icons.pause : Icons.play_arrow),
|
||||
),
|
||||
Expanded(
|
||||
child: Align(
|
||||
alignment: Alignment.centerRight,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (preview != null &&
|
||||
(preview.error != null ||
|
||||
preview.hasUnavailableMedia)) ...[
|
||||
IconButton(
|
||||
tooltip: context.l10n.retryPreview,
|
||||
onPressed: preview.busy ? null : preview.retry,
|
||||
icon: const Icon(Icons.refresh),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.gap),
|
||||
],
|
||||
if (source == null &&
|
||||
PreviewFullscreenScope.of(context)?.fullscreen != true)
|
||||
Flexible(
|
||||
child: AppSelect<ProjectCanvas>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
label: context.l10n.canvasRatio,
|
||||
outlined: false,
|
||||
value: preview?.canvas ?? ProjectCanvas.widescreen,
|
||||
onChanged: preview?.setCanvas,
|
||||
options: [
|
||||
for (final entry
|
||||
in ProjectCanvasPresets.values.entries)
|
||||
AppSelectOption(entry.value, entry.key),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (PreviewFullscreenScope.of(context)
|
||||
case final fullscreen?)
|
||||
IconButton(
|
||||
key: const Key('preview-fullscreen'),
|
||||
tooltip: fullscreen.fullscreen
|
||||
? context.l10n.exitPreviewFullscreen
|
||||
: context.l10n.previewFullscreen,
|
||||
onPressed:
|
||||
fullscreen.fullscreen ||
|
||||
source?.session != null ||
|
||||
source?.image != null ||
|
||||
preview?.session != null
|
||||
? fullscreen.toggle
|
||||
: null,
|
||||
icon: Icon(
|
||||
fullscreen.fullscreen
|
||||
? Icons.fullscreen_exit
|
||||
: Icons.fullscreen,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _time(int tick, RationalTime frameDuration) {
|
||||
final frameTicks = TimelineClock.standard.toTicks(frameDuration);
|
||||
final fps = (frameDuration.denominator / frameDuration.numerator).round();
|
||||
final frames = (tick < 0 ? 0 : tick) ~/ frameTicks;
|
||||
final seconds = frames ~/ fps;
|
||||
return [
|
||||
seconds ~/ 3600,
|
||||
seconds ~/ 60 % 60,
|
||||
seconds % 60,
|
||||
frames % fps,
|
||||
].map((value) => value.toString().padLeft(2, '0')).join(':');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'preview_panel.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(editorPreview)
|
||||
final editorPreviewProvider = EditorPreviewFamily._();
|
||||
|
||||
final class EditorPreviewProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<Raw<PreviewController?>?>,
|
||||
Raw<PreviewController?>?,
|
||||
FutureOr<Raw<PreviewController?>?>
|
||||
>
|
||||
with
|
||||
$FutureModifier<Raw<PreviewController?>?>,
|
||||
$FutureProvider<Raw<PreviewController?>?> {
|
||||
EditorPreviewProvider._({
|
||||
required EditorPreviewFamily super.from,
|
||||
required (String, String) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'editorPreviewProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$editorPreviewHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'editorPreviewProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<Raw<PreviewController?>?> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<Raw<PreviewController?>?> create(Ref ref) {
|
||||
final argument = this.argument as (String, String);
|
||||
return editorPreview(ref, argument.$1, argument.$2);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is EditorPreviewProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$editorPreviewHash() => r'f612b965e1573a819af0e77f910a66021e937bfe';
|
||||
|
||||
final class EditorPreviewFamily extends $Family
|
||||
with
|
||||
$FunctionalFamilyOverride<
|
||||
FutureOr<Raw<PreviewController?>?>,
|
||||
(String, String)
|
||||
> {
|
||||
EditorPreviewFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'editorPreviewProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
EditorPreviewProvider call(String projectId, String timelineId) =>
|
||||
EditorPreviewProvider._(argument: (projectId, timelineId), from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'editorPreviewProvider';
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:uuid/uuid.dart';
|
||||
|
||||
import '../../integrations/agent/conversation_repository.dart';
|
||||
import '../../workspace/project_state.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../assistant/agent_conversation_service.dart';
|
||||
import '../assistant/agent_composer_store.dart';
|
||||
|
||||
part 'conversation_sidebar.g.dart';
|
||||
part 'conversation_sidebar.freezed.dart';
|
||||
|
||||
@freezed
|
||||
abstract class ConversationSnapshot with _$ConversationSnapshot {
|
||||
const factory ConversationSnapshot({
|
||||
String? projectId,
|
||||
@Default({}) Map<String, List<ConversationMetadata>> groups,
|
||||
@Default([]) List<ConversationMetadata> trashed,
|
||||
String? selectedId,
|
||||
@Default(false) bool reloadFailed,
|
||||
}) = _ConversationSnapshot;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ConversationWorkspaceKey with _$ConversationWorkspaceKey {
|
||||
const factory ConversationWorkspaceKey({
|
||||
String? projectId,
|
||||
required List<String> projectIds,
|
||||
}) = _ConversationWorkspaceKey;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class ConversationSelectionState with _$ConversationSelectionState {
|
||||
const factory ConversationSelectionState({
|
||||
String? selectedId,
|
||||
required String draftKey,
|
||||
@Default(false) bool initialized,
|
||||
}) = _ConversationSelectionState;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Future<String?> savedConversationSelection(Ref ref, String? projectId) async {
|
||||
if (projectId == null) return null;
|
||||
ref.watch(projectsProvider.select((value) => value.value?.activeProject?.id));
|
||||
final repository = await ref.watch(conversationRepositoryProvider.future);
|
||||
return repository.selected(projectId);
|
||||
}
|
||||
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
@Riverpod(keepAlive: true)
|
||||
class ConversationSelection extends _$ConversationSelection {
|
||||
String? _draftKey;
|
||||
@override
|
||||
ConversationSelectionState build(String? projectId) {
|
||||
final composers = ref.read(agentComposerStoreProvider);
|
||||
ref.onDispose(() {
|
||||
if (_draftKey case final key?) composers.removeDraft(projectId, key);
|
||||
});
|
||||
ref.watch(
|
||||
projectsProvider.select((value) => value.value?.activeProject?.id),
|
||||
);
|
||||
final saved = savedConversationSelectionProvider(projectId);
|
||||
ref.listen(saved, (_, next) {
|
||||
if (!state.initialized &&
|
||||
next.hasValue &&
|
||||
!next.isLoading &&
|
||||
!next.hasError) {
|
||||
state = state.copyWith(selectedId: next.value, initialized: true);
|
||||
}
|
||||
});
|
||||
final selected = ref.read(saved);
|
||||
final initialized =
|
||||
selected.hasValue && !selected.isLoading && !selected.hasError;
|
||||
_draftKey = const Uuid().v4();
|
||||
return ConversationSelectionState(
|
||||
draftKey: _draftKey!,
|
||||
selectedId: initialized ? selected.value : null,
|
||||
initialized: initialized,
|
||||
);
|
||||
}
|
||||
|
||||
void newConversation() {
|
||||
ref.read(agentComposerStoreProvider).removeDraft(projectId, state.draftKey);
|
||||
_draftKey = const Uuid().v4();
|
||||
state = ConversationSelectionState(draftKey: _draftKey!, initialized: true);
|
||||
}
|
||||
|
||||
void select(String id) =>
|
||||
state = state.copyWith(selectedId: id, initialized: true);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class ConversationSidebar extends _$ConversationSidebar {
|
||||
int _revision = 0;
|
||||
|
||||
@override
|
||||
Future<ConversationSnapshot> build() async {
|
||||
await ref.watch(
|
||||
projectsProvider.selectAsync(
|
||||
(workspace) => ConversationWorkspaceKey(
|
||||
projectId: workspace.activeProject?.id,
|
||||
projectIds: [for (final project in workspace.recent) project.id],
|
||||
),
|
||||
),
|
||||
);
|
||||
_revision++;
|
||||
final workspace = ref.read(projectsProvider).requireValue;
|
||||
return _load(workspace);
|
||||
}
|
||||
|
||||
Future<ConversationSnapshot> _load(ProjectState workspace) async {
|
||||
final projectId = workspace.activeProject?.id;
|
||||
if (projectId == null && workspace.recent.isEmpty) {
|
||||
return const ConversationSnapshot();
|
||||
}
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
final lists = await Future.wait([
|
||||
for (final project in workspace.recent) repository.list(project.id),
|
||||
]);
|
||||
return ConversationSnapshot(
|
||||
projectId: projectId,
|
||||
groups: {
|
||||
for (var index = 0; index < workspace.recent.length; index++)
|
||||
workspace.recent[index].id: List.unmodifiable(lists[index]),
|
||||
},
|
||||
trashed: projectId == null
|
||||
? const []
|
||||
: List.unmodifiable(await repository.list(projectId, trash: true)),
|
||||
selectedId: await ref.read(
|
||||
savedConversationSelectionProvider(projectId).future,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> reload() async {
|
||||
final revision = ++_revision;
|
||||
final workspace = ref.read(projectsProvider).requireValue;
|
||||
try {
|
||||
final next = await _load(workspace);
|
||||
if (!ref.mounted ||
|
||||
revision != _revision ||
|
||||
ref.read(projectsProvider).value?.activeProject?.id !=
|
||||
next.projectId) {
|
||||
return;
|
||||
}
|
||||
state = AsyncData(next);
|
||||
} catch (error, stack) {
|
||||
if (ref.mounted && revision == _revision) {
|
||||
state = state.value == null
|
||||
? AsyncError(error, stack)
|
||||
: AsyncData(state.requireValue.copyWith(reloadFailed: true));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void newConversation() => ref
|
||||
.read(
|
||||
conversationSelectionProvider(
|
||||
ref.read(projectsProvider).value?.activeProject?.id,
|
||||
).notifier,
|
||||
)
|
||||
.newConversation();
|
||||
|
||||
Future<void> rememberSelection(ConversationMetadata item) async {
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
await repository.select(item.projectId, item.id);
|
||||
if (ref.mounted) {
|
||||
ref.invalidate(savedConversationSelectionProvider(item.projectId));
|
||||
}
|
||||
}
|
||||
|
||||
void activate(ConversationMetadata item) => ref
|
||||
.read(conversationSelectionProvider(item.projectId).notifier)
|
||||
.select(item.id);
|
||||
|
||||
Future<void> updateListing(
|
||||
ConversationMetadata item, {
|
||||
String? selectIfDraftKey,
|
||||
}) async {
|
||||
if (ref.read(projectsProvider).value?.activeProject?.id != item.projectId) {
|
||||
return;
|
||||
}
|
||||
final current = state.value ?? await future;
|
||||
if (!ref.mounted) return;
|
||||
_revision++;
|
||||
if (ref.read(projectsProvider).value?.activeProject?.id != item.projectId) {
|
||||
return;
|
||||
}
|
||||
final selection = ref.read(conversationSelectionProvider(item.projectId));
|
||||
final selectCreated =
|
||||
selectIfDraftKey != null &&
|
||||
selection.selectedId == null &&
|
||||
selection.draftKey == selectIfDraftKey;
|
||||
state = AsyncData(
|
||||
current.copyWith(
|
||||
groups: {
|
||||
...current.groups,
|
||||
item.projectId: [
|
||||
item,
|
||||
...?current.groups[item.projectId]?.where(
|
||||
(existing) => existing.id != item.id,
|
||||
),
|
||||
],
|
||||
},
|
||||
),
|
||||
);
|
||||
if (selectCreated) {
|
||||
ref
|
||||
.read(agentComposerStoreProvider)
|
||||
.promoteDraft(item.projectId, selectIfDraftKey, item.id);
|
||||
activate(item);
|
||||
await rememberSelection(item);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> rename(ConversationMetadata item, String title) =>
|
||||
updateMetadata(item.copyWith(title: title));
|
||||
Future<void> updateMetadata(ConversationMetadata item) async {
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
await repository.update(item);
|
||||
if (ref.mounted) await reload();
|
||||
}
|
||||
|
||||
Future<void> trash(ConversationMetadata item) async {
|
||||
await ref
|
||||
.read(agentConversationRegistryProvider)
|
||||
.cancel(item.projectId, item.id);
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
await repository.trash(item.projectId, item.id);
|
||||
if (!ref.mounted) return;
|
||||
_forgetRemovedSelection(item);
|
||||
await reload();
|
||||
}
|
||||
|
||||
Future<void> restore(ConversationMetadata item) async {
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
await repository.restore(item.projectId, item.id);
|
||||
if (ref.mounted) {
|
||||
ref.invalidate(savedConversationSelectionProvider(item.projectId));
|
||||
await reload();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> delete(ConversationMetadata item) async {
|
||||
await ref
|
||||
.read(agentConversationRegistryProvider)
|
||||
.cancel(item.projectId, item.id);
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
await repository.deletePermanently(item.projectId, item.id);
|
||||
if (!ref.mounted) return;
|
||||
_forgetRemovedSelection(item);
|
||||
ref
|
||||
.read(agentComposerStoreProvider)
|
||||
.removeConversation(item.projectId, item.id);
|
||||
await reload();
|
||||
}
|
||||
|
||||
void _forgetRemovedSelection(ConversationMetadata item) {
|
||||
ref.invalidate(savedConversationSelectionProvider(item.projectId));
|
||||
if (ref.read(projectsProvider).value?.activeProject?.id == item.projectId &&
|
||||
ref.read(conversationSelectionProvider(item.projectId)).selectedId ==
|
||||
item.id) {
|
||||
newConversation();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> emptyTrash() async {
|
||||
final items = state.value?.trashed ?? const <ConversationMetadata>[];
|
||||
final repository = await ref.read(conversationRepositoryProvider.future);
|
||||
for (final item in items) {
|
||||
await repository.deletePermanently(item.projectId, item.id);
|
||||
if (!ref.mounted) return;
|
||||
_forgetRemovedSelection(item);
|
||||
ref
|
||||
.read(agentComposerStoreProvider)
|
||||
.removeConversation(item.projectId, item.id);
|
||||
}
|
||||
if (ref.mounted) await reload();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,247 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'conversation_sidebar.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(savedConversationSelection)
|
||||
final savedConversationSelectionProvider = SavedConversationSelectionFamily._();
|
||||
|
||||
final class SavedConversationSelectionProvider
|
||||
extends $FunctionalProvider<AsyncValue<String?>, String?, FutureOr<String?>>
|
||||
with $FutureModifier<String?>, $FutureProvider<String?> {
|
||||
SavedConversationSelectionProvider._({
|
||||
required SavedConversationSelectionFamily super.from,
|
||||
required String? super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'savedConversationSelectionProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$savedConversationSelectionHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'savedConversationSelectionProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<String?> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<String?> create(Ref ref) {
|
||||
final argument = this.argument as String?;
|
||||
return savedConversationSelection(ref, argument);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SavedConversationSelectionProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$savedConversationSelectionHash() =>
|
||||
r'849182ed07f7227ba041f611ccdb3cbb1423f95e';
|
||||
|
||||
final class SavedConversationSelectionFamily extends $Family
|
||||
with $FunctionalFamilyOverride<FutureOr<String?>, String?> {
|
||||
SavedConversationSelectionFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'savedConversationSelectionProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: false,
|
||||
);
|
||||
|
||||
SavedConversationSelectionProvider call(String? projectId) =>
|
||||
SavedConversationSelectionProvider._(argument: projectId, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'savedConversationSelectionProvider';
|
||||
}
|
||||
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
|
||||
@ProviderFor(ConversationSelection)
|
||||
final conversationSelectionProvider = ConversationSelectionFamily._();
|
||||
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
final class ConversationSelectionProvider
|
||||
extends
|
||||
$NotifierProvider<ConversationSelection, ConversationSelectionState> {
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
ConversationSelectionProvider._({
|
||||
required ConversationSelectionFamily super.from,
|
||||
required String? super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'conversationSelectionProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$conversationSelectionHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'conversationSelectionProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ConversationSelection create() => ConversationSelection();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ConversationSelectionState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ConversationSelectionState>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is ConversationSelectionProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$conversationSelectionHash() =>
|
||||
r'eef3c6c95f86b017e73d3244adccc257f717699b';
|
||||
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
|
||||
final class ConversationSelectionFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
ConversationSelection,
|
||||
ConversationSelectionState,
|
||||
ConversationSelectionState,
|
||||
ConversationSelectionState,
|
||||
String?
|
||||
> {
|
||||
ConversationSelectionFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'conversationSelectionProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: false,
|
||||
);
|
||||
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
|
||||
ConversationSelectionProvider call(String? projectId) =>
|
||||
ConversationSelectionProvider._(argument: projectId, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'conversationSelectionProvider';
|
||||
}
|
||||
|
||||
/// Keeps a draft or explicit selection stable while the list refreshes.
|
||||
|
||||
abstract class _$ConversationSelection
|
||||
extends $Notifier<ConversationSelectionState> {
|
||||
late final _$args = ref.$arg as String?;
|
||||
String? get projectId => _$args;
|
||||
|
||||
ConversationSelectionState build(String? projectId);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<ConversationSelectionState, ConversationSelectionState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
ConversationSelectionState,
|
||||
ConversationSelectionState
|
||||
>,
|
||||
ConversationSelectionState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, () => build(_$args));
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(ConversationSidebar)
|
||||
final conversationSidebarProvider = ConversationSidebarProvider._();
|
||||
|
||||
final class ConversationSidebarProvider
|
||||
extends $AsyncNotifierProvider<ConversationSidebar, ConversationSnapshot> {
|
||||
ConversationSidebarProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'conversationSidebarProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$conversationSidebarHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ConversationSidebar create() => ConversationSidebar();
|
||||
}
|
||||
|
||||
String _$conversationSidebarHash() =>
|
||||
r'13122a844ce87622c8d4919042e4dbefc69b790f';
|
||||
|
||||
abstract class _$ConversationSidebar
|
||||
extends $AsyncNotifier<ConversationSnapshot> {
|
||||
FutureOr<ConversationSnapshot> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<AsyncValue<ConversationSnapshot>, ConversationSnapshot>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
AsyncValue<ConversationSnapshot>,
|
||||
ConversationSnapshot
|
||||
>,
|
||||
AsyncValue<ConversationSnapshot>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../workspace/project_state.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
class EmptyEditor extends StatelessWidget {
|
||||
const EmptyEditor({
|
||||
super.key,
|
||||
required this.state,
|
||||
required this.headerLeading,
|
||||
required this.showProjectName,
|
||||
});
|
||||
|
||||
final ProjectState state;
|
||||
final Widget headerLeading;
|
||||
final bool showProjectName;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: AppControlSize.panelHeader,
|
||||
child: WindowHeaderPadding(
|
||||
child: Row(
|
||||
children: [
|
||||
headerLeading,
|
||||
if (showProjectName)
|
||||
Expanded(
|
||||
child: Text(
|
||||
state.activeProject?.name ?? '',
|
||||
key: const Key('workspace-project-title'),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(AppSpacing.page),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.movie_outlined,
|
||||
size: AppIconSize.project,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
Text(
|
||||
state.activeProject == null
|
||||
? context.l10n.projectsEmpty
|
||||
: context.l10n.projectNoTimelines,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.headlineMedium,
|
||||
),
|
||||
if (state.activeProject != null) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(
|
||||
context.l10n.createTimelineHint,
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
class ProjectLoadingRegion extends StatelessWidget {
|
||||
const ProjectLoadingRegion({
|
||||
super.key,
|
||||
required this.loading,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final bool loading;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Stack(
|
||||
fit: StackFit.expand,
|
||||
children: [
|
||||
ExcludeFocus(
|
||||
excluding: loading,
|
||||
child: IgnorePointer(ignoring: loading, child: child),
|
||||
),
|
||||
if (loading)
|
||||
DelayedLoadingIndicator(
|
||||
child: Positioned.fill(
|
||||
child: ColoredBox(
|
||||
key: const Key('editor-project-loading'),
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: const Center(
|
||||
child: SizedBox.square(
|
||||
dimension: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,664 @@
|
||||
import 'package:cutdex/errors/app_failure.dart';
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../app/adaptive/desktop_workspace_controller.dart';
|
||||
import '../../app/adaptive/workspace_layout_policy.dart';
|
||||
import '../../app/shells/phone_workspace_shell.dart';
|
||||
import '../../app/shells/desktop_workspace_shell.dart';
|
||||
import '../../app/shells/tablet_workspace_shell.dart';
|
||||
import '../../integrations/platform/device_experience.dart';
|
||||
import '../../integrations/platform/editor_window_chrome.dart';
|
||||
import '../../integrations/platform/file_picker.dart';
|
||||
|
||||
import 'package:cutdex_native/cutdex_native.dart';
|
||||
|
||||
import '../../persistence/app_settings_repositories.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
import '../../workspace/projects.dart';
|
||||
import '../../workspace/view_settings.dart';
|
||||
import '../../workspace/workspace_mode.dart';
|
||||
import '../../workspace/workspace_navigation.dart';
|
||||
import '../../workspace/workspace_session_scope.dart';
|
||||
import '../assistant/workspace_agent_surface.dart';
|
||||
import '../editor/background_tasks_button.dart';
|
||||
import '../editor/editor_page.dart';
|
||||
import '../settings/settings_dialog.dart';
|
||||
import 'editor_loading_region.dart';
|
||||
import 'project_sidebar.dart';
|
||||
import 'widgets/name_dialog.dart';
|
||||
|
||||
/// The single application surface: project navigation beside the editor.
|
||||
|
||||
class EditingPage extends ConsumerStatefulWidget {
|
||||
const EditingPage({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<EditingPage> createState() => _EditingPageState();
|
||||
}
|
||||
|
||||
class _EditingPageState extends ConsumerState<EditingPage> {
|
||||
final _desktopSplits = DesktopWorkspaceController();
|
||||
final _editorKey = GlobalKey();
|
||||
final _agentKey = GlobalKey();
|
||||
final _navigationKey = GlobalKey();
|
||||
final _drawerNavigationKey = GlobalKey();
|
||||
final _desktopScaffoldKey = GlobalKey<ScaffoldState>();
|
||||
WorkspaceViewSettingsData get _viewSettings =>
|
||||
ref.read(workspaceViewSettingsProvider).value ??
|
||||
const WorkspaceViewSettingsData();
|
||||
WorkspaceViewSettings get _viewController =>
|
||||
ref.read(workspaceViewSettingsProvider.notifier);
|
||||
WorkspaceMode get _mode => _viewSettings.mode;
|
||||
set _mode(WorkspaceMode value) => _viewController.setMode(value);
|
||||
bool get _sidebarCollapsed => _viewSettings.sidebarCollapsed;
|
||||
set _sidebarCollapsed(bool value) =>
|
||||
_viewController.setSidebarCollapsed(value);
|
||||
double? get _sidebarWidthOverride => _viewSettings.sidebarWidth;
|
||||
set _sidebarWidthOverride(double? value) =>
|
||||
_viewController.setSidebarWidth(value);
|
||||
bool get _startupReady => ref.read(workspaceNavigationProvider).ready;
|
||||
bool get _switchingProject =>
|
||||
ref.read(workspaceNavigationProvider).switchingProject;
|
||||
String? get _selectedProjectId =>
|
||||
ref.read(workspaceNavigationProvider).selectedProjectId;
|
||||
|
||||
void _saveViewState({String? activeProjectId}) {
|
||||
if (!_startupReady) return;
|
||||
final current = ref.read(projectsProvider).value;
|
||||
unawaited(
|
||||
_viewController.save(
|
||||
activeProjectId: activeProjectId ?? current?.activeProject?.id,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _selectProject(
|
||||
BuildContext context,
|
||||
WidgetRef ref, {
|
||||
required bool create,
|
||||
}) async {
|
||||
if (ref.read(projectsProvider).value?.projectBusy == true) return;
|
||||
try {
|
||||
if (create) {
|
||||
final name = await askName(
|
||||
context,
|
||||
title: context.l10n.newProject,
|
||||
label: context.l10n.projectName,
|
||||
);
|
||||
if (name == null || !context.mounted) return;
|
||||
final created = await ref
|
||||
.read(projectsProvider.notifier)
|
||||
.createProject(
|
||||
name,
|
||||
initialTimelineName: context.l10n.defaultTimelineName(1),
|
||||
);
|
||||
if (!created && context.mounted) {
|
||||
final error = ref.read(projectsProvider).value?.error;
|
||||
if (error?.requiresProjectLocation == true) {
|
||||
await showSettingsDialog(context);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
final directory = await ref
|
||||
.read(filePickerProvider)
|
||||
.pickDirectory(confirmButtonText: context.l10n.openProject);
|
||||
if (directory == null || !context.mounted) return;
|
||||
await ref.read(projectsProvider.notifier).open(directory);
|
||||
} catch (_) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text(context.l10n.selectDirectoryFailed)),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openProject(WidgetRef ref, RecentProject project) =>
|
||||
ref.read(workspaceNavigationProvider.notifier).openProject(project);
|
||||
|
||||
Future<bool> _renameProject(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
RecentProject project,
|
||||
) async {
|
||||
if (ref.read(projectsProvider).value?.projectBusy == true) return false;
|
||||
final name = await askName(
|
||||
context,
|
||||
title: context.l10n.rename,
|
||||
label: context.l10n.projectName,
|
||||
initialValue: project.name,
|
||||
submitLabel: context.l10n.rename,
|
||||
);
|
||||
if (name == null || !context.mounted || name == project.name) return false;
|
||||
return ref.read(projectsProvider.notifier).renameProject(project, name);
|
||||
}
|
||||
|
||||
Future<void> _relocateProject(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
RecentProject project,
|
||||
) async {
|
||||
if (ref.read(projectsProvider).value?.projectBusy == true) return;
|
||||
final directory = await ref
|
||||
.read(filePickerProvider)
|
||||
.pickDirectory(confirmButtonText: context.l10n.openProject);
|
||||
if (directory == null || !context.mounted) return;
|
||||
await ref
|
||||
.read(projectsProvider.notifier)
|
||||
.open(directory, expectedId: project.id);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_desktopSplits.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _setMode(WorkspaceMode mode) {
|
||||
_mode = mode;
|
||||
_saveViewState();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(workspaceViewSettingsProvider);
|
||||
ref.watch(workspaceNavigationProvider);
|
||||
final experience = ref.watch(deviceExperienceProvider);
|
||||
final desktop = experience == DeviceExperience.desktop;
|
||||
final projects = ref.watch(projectsProvider);
|
||||
final state = projects.value ?? const ProjectState();
|
||||
return EditorWindowChrome(
|
||||
headerHeight: desktop ? AppControlSize.panelHeader : 48,
|
||||
builder: (context, integrated) => Scaffold(
|
||||
body: SafeArea(
|
||||
top: !integrated,
|
||||
child: AnimatedSwitcher(
|
||||
duration: const Duration(milliseconds: 320),
|
||||
child: !_startupReady
|
||||
? const _StartupLoading(key: ValueKey('startup-loading'))
|
||||
: WorkspaceSessionScope(
|
||||
key: const ValueKey('workspace-content'),
|
||||
state: state,
|
||||
child: Stack(
|
||||
children: [
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final navigationHiddenBySpace =
|
||||
desktop &&
|
||||
!WorkspaceLayoutPolicy.desktopNavigationFits(
|
||||
constraints.maxWidth,
|
||||
);
|
||||
final navigationCollapsed =
|
||||
_sidebarCollapsed || navigationHiddenBySpace;
|
||||
Widget controls({
|
||||
bool navigationToggle = true,
|
||||
}) => HeaderControlRegion(
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
spacing: AppSpacing.tiny,
|
||||
children: [
|
||||
if (navigationToggle)
|
||||
SizedBox.square(
|
||||
dimension: AppControlSize.headerButton,
|
||||
child: IconButton(
|
||||
key: const Key(
|
||||
'project-sidebar-toggle',
|
||||
),
|
||||
tooltip: navigationCollapsed
|
||||
? context.l10n.expandSidebar
|
||||
: context.l10n.collapseSidebar,
|
||||
onPressed: () {
|
||||
if (navigationHiddenBySpace) {
|
||||
_desktopScaffoldKey.currentState
|
||||
?.openDrawer();
|
||||
} else {
|
||||
_sidebarCollapsed =
|
||||
!_sidebarCollapsed;
|
||||
_saveViewState();
|
||||
}
|
||||
},
|
||||
style: sidebarActionButtonStyle(
|
||||
context,
|
||||
),
|
||||
icon: const Icon(
|
||||
Icons.view_sidebar_outlined,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (desktop &&
|
||||
navigationCollapsed &&
|
||||
navigationToggle)
|
||||
PopupMenuButton<WorkspaceMode>(
|
||||
key: const Key('desktop-workspace-mode'),
|
||||
initialValue: _mode,
|
||||
onSelected: _setMode,
|
||||
itemBuilder: (context) => [
|
||||
for (final mode in WorkspaceMode.values)
|
||||
PopupMenuItem(
|
||||
key: ValueKey(
|
||||
'desktop-mode-${mode.name}',
|
||||
),
|
||||
value: mode,
|
||||
child: Text(
|
||||
mode == WorkspaceMode.agent
|
||||
? context.l10n.workspaceAgent
|
||||
: context.l10n.workspaceCut,
|
||||
),
|
||||
),
|
||||
],
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 6,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
_mode == WorkspaceMode.agent
|
||||
? context.l10n.workspaceAgent
|
||||
: context.l10n.workspaceCut,
|
||||
),
|
||||
const Icon(
|
||||
Icons.keyboard_arrow_down,
|
||||
size: 16,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox.square(
|
||||
dimension: desktop
|
||||
? AppControlSize.headerButton
|
||||
: 48,
|
||||
child: IconButton(
|
||||
key: const Key('project-settings-button'),
|
||||
tooltip: context.l10n.settings,
|
||||
onPressed: () =>
|
||||
showSettingsDialog(context),
|
||||
style: sidebarActionButtonStyle(context),
|
||||
icon: const Icon(
|
||||
Icons.settings_outlined,
|
||||
size: AppIconSize.header,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox.square(
|
||||
dimension: desktop
|
||||
? AppControlSize.headerButton
|
||||
: 48,
|
||||
child: const BackgroundTasksButton(),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
Widget leading() => Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (navigationCollapsed && integrated)
|
||||
SizedBox(
|
||||
width: EditorWindowChrome.leadingWidth,
|
||||
),
|
||||
if (navigationCollapsed) controls(),
|
||||
const SizedBox(width: AppSpacing.compact),
|
||||
],
|
||||
);
|
||||
void selectProject(RecentProject project) {
|
||||
if (project.availability.canOpen) {
|
||||
_openProject(ref, project);
|
||||
} else {
|
||||
_relocateProject(context, ref, project);
|
||||
}
|
||||
}
|
||||
|
||||
final agent = WorkspaceAgentSurface(
|
||||
key: _agentKey,
|
||||
state: state,
|
||||
onSelectProject: (project) =>
|
||||
project.availability.canOpen
|
||||
? _openProject(ref, project)
|
||||
: _relocateProject(context, ref, project),
|
||||
onCreateProject: () =>
|
||||
_selectProject(context, ref, create: true),
|
||||
);
|
||||
Widget navigation({
|
||||
DesktopWorkspaceGeometry? geometry,
|
||||
VoidCallback? expandEditor,
|
||||
bool drawer = false,
|
||||
}) => ProjectSidebar(
|
||||
experience: experience,
|
||||
key: drawer
|
||||
? _drawerNavigationKey
|
||||
: _navigationKey,
|
||||
agent: desktop && !drawer
|
||||
? agent
|
||||
: const SizedBox.shrink(),
|
||||
navigationOnly: !desktop || drawer,
|
||||
onNavigationComplete: desktop && !drawer
|
||||
? null
|
||||
: () => Navigator.of(context).maybePop(),
|
||||
editorHidden: geometry?.editorHidden ?? false,
|
||||
onExpandEditor: expandEditor,
|
||||
agentHeaderLeading: desktop
|
||||
? leading()
|
||||
: const SizedBox.shrink(),
|
||||
navigationCollapsed:
|
||||
desktop && !drawer && navigationCollapsed,
|
||||
mode: _mode,
|
||||
onModeChanged: _setMode,
|
||||
navigationWidth: geometry?.sidebarWidth ?? 320,
|
||||
state: state,
|
||||
selectedProjectId:
|
||||
_selectedProjectId ?? state.activeProject?.id,
|
||||
integratedTitlebar: integrated,
|
||||
onCreateProject: () =>
|
||||
_selectProject(context, ref, create: true),
|
||||
onSelectProject: selectProject,
|
||||
onRenameProject: (project) =>
|
||||
_renameProject(context, ref, project),
|
||||
headerControls: desktop && !drawer
|
||||
? controls()
|
||||
: HeaderControlRegion(
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Builder(
|
||||
builder: (context) => IconButton(
|
||||
tooltip: MaterialLocalizations.of(
|
||||
context,
|
||||
).closeButtonTooltip,
|
||||
onPressed: () =>
|
||||
Scaffold.of(context)
|
||||
.closeDrawer(),
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
final editor = ProjectLoadingRegion(
|
||||
loading: _switchingProject,
|
||||
child:
|
||||
state.activeProject != null &&
|
||||
state.timeline != null
|
||||
? EditorWorkspace(
|
||||
key: _editorKey,
|
||||
experience: experience,
|
||||
projectId: state.activeProject!.id,
|
||||
timelineId: state.timeline!.id,
|
||||
projectName: state.activeProject!.name,
|
||||
showProjectName:
|
||||
desktop && _mode == WorkspaceMode.cut,
|
||||
integratedTitlebar: desktop && integrated,
|
||||
headerLeading:
|
||||
desktop && _mode == WorkspaceMode.cut
|
||||
? leading()
|
||||
: const SizedBox(
|
||||
width: AppSpacing.compact,
|
||||
),
|
||||
)
|
||||
: EmptyEditor(
|
||||
state: state,
|
||||
showProjectName:
|
||||
desktop && _mode == WorkspaceMode.cut,
|
||||
headerLeading:
|
||||
desktop && _mode == WorkspaceMode.cut
|
||||
? leading()
|
||||
: const SizedBox(
|
||||
width: AppSpacing.compact,
|
||||
),
|
||||
),
|
||||
);
|
||||
return switch (experience) {
|
||||
DeviceExperience.desktop => DesktopWorkspaceShell(
|
||||
controller: _desktopSplits,
|
||||
scaffoldKey: _desktopScaffoldKey,
|
||||
navigationDrawer: navigation(drawer: true),
|
||||
mode: _mode,
|
||||
sidebarCollapsed: navigationCollapsed,
|
||||
sidebarWidth: _sidebarWidthOverride,
|
||||
onSidebarCollapsedChanged: (value) {
|
||||
_sidebarCollapsed = value;
|
||||
_saveViewState();
|
||||
},
|
||||
onSidebarWidthChanged: (value) {
|
||||
_sidebarWidthOverride = value;
|
||||
_saveViewState();
|
||||
},
|
||||
sidebarBuilder: (geometry, expand) =>
|
||||
navigation(
|
||||
geometry: geometry,
|
||||
expandEditor: expand,
|
||||
),
|
||||
editor: editor,
|
||||
),
|
||||
DeviceExperience.tablet => TabletWorkspaceShell(
|
||||
mode: _mode,
|
||||
onModeChanged: _setMode,
|
||||
navigation: navigation(),
|
||||
headerActions: controls(
|
||||
navigationToggle: false,
|
||||
),
|
||||
title: state.activeProject?.name ?? 'Cutdex',
|
||||
integratedTitlebar: integrated,
|
||||
agent: agent,
|
||||
editor: editor,
|
||||
),
|
||||
DeviceExperience.phone => PhoneWorkspaceShell(
|
||||
mode: _mode,
|
||||
onModeChanged: _setMode,
|
||||
navigation: navigation(),
|
||||
headerActions: controls(
|
||||
navigationToggle: false,
|
||||
),
|
||||
title: state.activeProject?.name ?? 'Cutdex',
|
||||
integratedTitlebar: integrated,
|
||||
agent: agent,
|
||||
editor: editor,
|
||||
),
|
||||
};
|
||||
},
|
||||
),
|
||||
PositionedDirectional(
|
||||
top: AppSpacing.compact,
|
||||
end: AppSpacing.compact,
|
||||
child: _SonnerErrorToast(
|
||||
message: projects.hasError
|
||||
? const AppFailure(
|
||||
AppErrorCode.loadProjectsFailed,
|
||||
)
|
||||
: state.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _StartupLoading extends StatefulWidget {
|
||||
const _StartupLoading({super.key});
|
||||
|
||||
@override
|
||||
State<_StartupLoading> createState() => _StartupLoadingState();
|
||||
}
|
||||
|
||||
class _StartupLoadingState extends State<_StartupLoading>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _pulse = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 1800),
|
||||
)..repeat(reverse: true);
|
||||
|
||||
late final Animation<double> _opacity = Tween<double>(
|
||||
begin: 0.5,
|
||||
end: 1,
|
||||
).animate(CurvedAnimation(parent: _pulse, curve: Curves.easeInOut));
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pulse.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: FadeTransition(
|
||||
opacity: _opacity,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'CUTDEX',
|
||||
style: Theme.of(context).textTheme.titleMedium
|
||||
?.copyWith(fontWeight: FontWeight.w600, letterSpacing: 3),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
Text(
|
||||
context.l10n.openingWorkspace,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _SonnerErrorToast extends StatefulWidget {
|
||||
const _SonnerErrorToast({required this.message});
|
||||
|
||||
final AppFailure? message;
|
||||
|
||||
@override
|
||||
State<_SonnerErrorToast> createState() => _SonnerErrorToastState();
|
||||
}
|
||||
|
||||
class _SonnerErrorToastState extends State<_SonnerErrorToast> {
|
||||
static const _displayDuration = Duration(seconds: 6);
|
||||
|
||||
Timer? _timer;
|
||||
AppFailure? _displayedMessage;
|
||||
bool _visible = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_show(widget.message);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _SonnerErrorToast oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (widget.message != null &&
|
||||
(oldWidget.message == null || widget.message != oldWidget.message)) {
|
||||
_show(widget.message);
|
||||
}
|
||||
}
|
||||
|
||||
void _show(AppFailure? message) {
|
||||
if (message == null) return;
|
||||
_timer?.cancel();
|
||||
_displayedMessage = message;
|
||||
_visible = true;
|
||||
_timer = Timer(_displayDuration, _hide);
|
||||
}
|
||||
|
||||
void _hide() {
|
||||
if (mounted) setState(() => _visible = false);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_timer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final message = _displayedMessage;
|
||||
if (message == null) return const SizedBox.shrink();
|
||||
final theme = Theme.of(context);
|
||||
return IgnorePointer(
|
||||
ignoring: !_visible,
|
||||
child: AnimatedSlide(
|
||||
offset: _visible ? Offset.zero : const Offset(0.08, 0),
|
||||
duration: const Duration(milliseconds: 180),
|
||||
curve: Curves.easeOutCubic,
|
||||
child: AnimatedOpacity(
|
||||
opacity: _visible ? 1 : 0,
|
||||
duration: const Duration(milliseconds: 160),
|
||||
child: Semantics(
|
||||
liveRegion: true,
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 360),
|
||||
child: DecoratedBox(
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHigh,
|
||||
border: Border.all(color: theme.colorScheme.outlineVariant),
|
||||
borderRadius: BorderRadius.circular(AppRadius.large),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: theme.colorScheme.shadow.withValues(alpha: .25),
|
||||
blurRadius: 16,
|
||||
offset: const Offset(0, 6),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Padding(
|
||||
padding: const EdgeInsetsDirectional.only(
|
||||
start: AppSpacing.compact,
|
||||
top: AppSpacing.small,
|
||||
bottom: AppSpacing.small,
|
||||
end: AppSpacing.tiny,
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: AppIconSize.small,
|
||||
color: theme.colorScheme.error,
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
Flexible(
|
||||
child: Text(
|
||||
context.l10n.failureMessage(message),
|
||||
style: theme.textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: MaterialLocalizations.of(context)
|
||||
.closeButtonTooltip,
|
||||
onPressed: _hide,
|
||||
icon: const Icon(Icons.close, size: AppIconSize.small),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/project_state.dart';
|
||||
|
||||
class TouchProjectsHeader extends StatelessWidget {
|
||||
const TouchProjectsHeader({super.key, required this.onCreate});
|
||||
final VoidCallback? onCreate;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Row(
|
||||
children: [
|
||||
Expanded(child: Text(context.l10n.projects)),
|
||||
SizedBox.square(
|
||||
dimension: 48,
|
||||
child: IconButton(
|
||||
key: const Key('create-project'),
|
||||
tooltip: context.l10n.newProject,
|
||||
onPressed: onCreate,
|
||||
icon: const Icon(Icons.add),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Touch navigation keeps its actions visible and uses finger-sized targets.
|
||||
class TouchProjectTile extends StatelessWidget {
|
||||
const TouchProjectTile({
|
||||
super.key,
|
||||
required this.project,
|
||||
required this.selected,
|
||||
required this.expanded,
|
||||
required this.availabilityLabel,
|
||||
required this.onSelect,
|
||||
required this.onToggle,
|
||||
required this.onNewConversation,
|
||||
required this.onRename,
|
||||
required this.onRemove,
|
||||
});
|
||||
final RecentProject project;
|
||||
final bool selected;
|
||||
final bool expanded;
|
||||
final String availabilityLabel;
|
||||
final VoidCallback onSelect;
|
||||
final VoidCallback onToggle;
|
||||
final VoidCallback? onNewConversation;
|
||||
final VoidCallback? onRename;
|
||||
final VoidCallback? onRemove;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListTile(
|
||||
key: ValueKey('sidebar-project-${project.id}'),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
minTileHeight: 56,
|
||||
selected: selected,
|
||||
leading: IconButton(
|
||||
key: ValueKey('sidebar-project-toggle-${project.id}'),
|
||||
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
|
||||
tooltip: expanded
|
||||
? context.l10n.collapseProject
|
||||
: context.l10n.expandProject,
|
||||
onPressed: onToggle,
|
||||
icon: Icon(expanded ? Icons.expand_more : Icons.chevron_right),
|
||||
),
|
||||
title: Text(project.name, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
subtitle: project.availability.canOpen ? null : Text(availabilityLabel),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
IconButton(
|
||||
key: ValueKey('new-agent-conversation-${project.id}'),
|
||||
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
|
||||
tooltip: context.l10n.agentNewConversation,
|
||||
onPressed: onNewConversation,
|
||||
icon: const Icon(Icons.edit_square),
|
||||
),
|
||||
AppPopover(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
AppMenuItem(label: context.l10n.rename, onPressed: onRename),
|
||||
AppMenuItem(
|
||||
label: context.l10n.removeProjectFromSidebar,
|
||||
onPressed: onRemove,
|
||||
),
|
||||
],
|
||||
),
|
||||
builder: (context, toggle) => IconButton(
|
||||
key: ValueKey('sidebar-project-more-${project.id}'),
|
||||
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
|
||||
onPressed: toggle,
|
||||
icon: const Icon(Icons.more_horiz),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
onTap: onSelect,
|
||||
);
|
||||
}
|
||||
|
||||
class TouchConversationTile extends StatelessWidget {
|
||||
const TouchConversationTile({
|
||||
super.key,
|
||||
required this.id,
|
||||
required this.title,
|
||||
required this.selected,
|
||||
required this.onSelect,
|
||||
required this.actions,
|
||||
});
|
||||
final String id;
|
||||
final String title;
|
||||
final bool selected;
|
||||
final VoidCallback onSelect;
|
||||
final List<Widget> Function(BuildContext) actions;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListTile(
|
||||
key: ValueKey('sidebar-conversation-$id'),
|
||||
minTileHeight: 48,
|
||||
selected: selected,
|
||||
title: Text(title, maxLines: 1, overflow: TextOverflow.ellipsis),
|
||||
onTap: onSelect,
|
||||
trailing: AppPopover(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: actions(context)),
|
||||
builder: (context, toggle) => IconButton(
|
||||
key: ValueKey('sidebar-conversation-more-$id'),
|
||||
constraints: const BoxConstraints.tightFor(width: 48, height: 48),
|
||||
onPressed: toggle,
|
||||
icon: const Icon(Icons.more_horiz),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
Future<String?> askName(
|
||||
BuildContext context, {
|
||||
required String title,
|
||||
required String label,
|
||||
String? description,
|
||||
String initialValue = '',
|
||||
String? submitLabel,
|
||||
}) => showAppDialog<String>(
|
||||
context: context,
|
||||
builder: (_) => _NameDialog(
|
||||
title: title,
|
||||
label: label,
|
||||
description: description,
|
||||
initialValue: initialValue,
|
||||
submitLabel: submitLabel,
|
||||
),
|
||||
);
|
||||
|
||||
class _NameDialog extends StatefulWidget {
|
||||
const _NameDialog({
|
||||
required this.title,
|
||||
required this.label,
|
||||
this.description,
|
||||
required this.initialValue,
|
||||
this.submitLabel,
|
||||
});
|
||||
final String title;
|
||||
final String label;
|
||||
final String? description;
|
||||
final String initialValue;
|
||||
final String? submitLabel;
|
||||
@override
|
||||
State<_NameDialog> createState() => _NameDialogState();
|
||||
}
|
||||
|
||||
class _NameDialogState extends State<_NameDialog> {
|
||||
late final _controller = TextEditingController(text: widget.initialValue)
|
||||
..selection = TextSelection(
|
||||
baseOffset: 0,
|
||||
extentOffset: widget.initialValue.length,
|
||||
);
|
||||
final _form = GlobalKey<FormState>();
|
||||
@override
|
||||
void dispose() {
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
if (_form.currentState!.validate()) {
|
||||
Navigator.pop(context, _controller.text.trim());
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AppDialog(
|
||||
title: widget.title,
|
||||
description: widget.description,
|
||||
width: 420,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text(context.l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _submit,
|
||||
child: Text(widget.submitLabel ?? context.l10n.create),
|
||||
),
|
||||
],
|
||||
child: Builder(
|
||||
builder: (dialogContext) => Form(
|
||||
key: _form,
|
||||
child: TextFormField(
|
||||
controller: _controller,
|
||||
style: AppTheme.inputTextStyle(dialogContext),
|
||||
cursorHeight: AppTheme.inputCursorHeight(dialogContext),
|
||||
autofocus: true,
|
||||
maxLength: 80,
|
||||
buildCounter: (
|
||||
_, {
|
||||
required currentLength,
|
||||
required isFocused,
|
||||
maxLength,
|
||||
}) => null,
|
||||
decoration: InputDecoration(hintText: widget.label),
|
||||
validator: (value) => value == null || value.trim().isEmpty
|
||||
? context.l10n.enterName
|
||||
: RegExp(r'[/\\\x00-\x1F]').hasMatch(value) ||
|
||||
['.', '..'].contains(value.trim())
|
||||
? context.l10n.invalidName
|
||||
: null,
|
||||
onFieldSubmitted: (_) => _submit(),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
extension TransformChannelLabel on TransformChannel {
|
||||
String label(BuildContext context) => switch (this) {
|
||||
TransformChannel.position => context.l10n.position,
|
||||
TransformChannel.rotation => context.l10n.rotation,
|
||||
TransformChannel.scale => context.l10n.scale,
|
||||
};
|
||||
}
|
||||
|
||||
Map<String, List<String>> localizedMaskChannels(BuildContext context) => {
|
||||
context.l10n.position: ['center.x', 'center.y'],
|
||||
context.l10n.size: ['width', 'height'],
|
||||
context.l10n.rotation: ['rotation'],
|
||||
context.l10n.feather: ['feather'],
|
||||
};
|
||||
|
||||
// Stable channel identifiers are independent of the interface language.
|
||||
const maskChannels = {
|
||||
'position': ['center.x', 'center.y'],
|
||||
'size': ['width', 'height'],
|
||||
'rotation': ['rotation'],
|
||||
'feather': ['feather'],
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
/// Slider travel is a presentation choice, independent of authored gain.
|
||||
abstract final class AudioGainScale {
|
||||
static const decimalPlaces = 1;
|
||||
static double quantizeDb(double db) => double.parse(formatDb(db));
|
||||
static String formatDb(double db) {
|
||||
final text = db.toStringAsFixed(decimalPlaces);
|
||||
return text == '-0.0' ? '0.0' : text;
|
||||
}
|
||||
|
||||
// Reserve 70% of travel for -24...+6 dB. Zero is a separate mute endpoint.
|
||||
static double dbAt(double position) {
|
||||
if (!position.isFinite) throw ArgumentError.value(position);
|
||||
final p = position.clamp(0.0, 1.0);
|
||||
if (p <= .01) return -90;
|
||||
if (p <= .2) return -90 + (p - .01) / .19 * 66;
|
||||
if (p <= .9) return -24 + (p - .2) / .7 * 30;
|
||||
return 6 + (p - .9) / .1 * 6;
|
||||
}
|
||||
|
||||
static double positionAt(double db) {
|
||||
if (!db.isFinite) throw ArgumentError.value(db);
|
||||
final value = db.clamp(-90.0, 12.0);
|
||||
if (value <= -24) return .01 + (value + 90) / 66 * .19;
|
||||
if (value <= 6) return .2 + (value + 24) / 30 * .7;
|
||||
return .9 + (value - 6) / 6 * .1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex/features/properties/audio_gain_scale.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
export 'package:cutdex_sdk/editor.dart' show ClipAudioGain;
|
||||
|
||||
class AudioProperties extends StatefulWidget {
|
||||
const AudioProperties({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.sequence,
|
||||
required this.clip,
|
||||
required this.hasAudio,
|
||||
});
|
||||
final EditorTimelineSession session;
|
||||
final SequenceId sequence;
|
||||
final ElementRecord clip;
|
||||
final bool hasAudio;
|
||||
|
||||
@override
|
||||
State<AudioProperties> createState() => _AudioPropertiesState();
|
||||
}
|
||||
|
||||
class _AudioPropertiesState extends State<AudioProperties> {
|
||||
final _text = TextEditingController();
|
||||
final _focus = FocusNode();
|
||||
ClipAudioGain? _timeline;
|
||||
Object? _editVersion;
|
||||
int? _editTick;
|
||||
String? _error;
|
||||
bool _dirty = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focus.addListener(_focusChanged);
|
||||
}
|
||||
|
||||
void _focusChanged() {
|
||||
if (_focus.hasFocus) {
|
||||
_beginEdit();
|
||||
} else if (_dirty) {
|
||||
_submit(_text.text);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
widget.session.clearAudioGainPreview(widget.clip.id);
|
||||
_focus.removeListener(_focusChanged);
|
||||
_focus.dispose();
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _beginEdit() {
|
||||
final view = widget.session.view(widget.sequence);
|
||||
_editVersion = view.version.kernelVersion;
|
||||
_editTick = view.playheadTick;
|
||||
}
|
||||
|
||||
bool get _editValid {
|
||||
final view = widget.session.view(widget.sequence);
|
||||
return widget.session.activeSequenceId == widget.sequence &&
|
||||
(_editVersion == null ||
|
||||
identical(_editVersion, view.version.kernelVersion)) &&
|
||||
(_editTick == null || _editTick == view.playheadTick);
|
||||
}
|
||||
|
||||
bool _commit(ClipAudioGain value) {
|
||||
widget.session.clearAudioGainPreview(widget.clip.id);
|
||||
final view = widget.session.view(widget.sequence);
|
||||
final query = view.version.kernelVersion.query();
|
||||
final handle = query.elementById(widget.clip.id);
|
||||
if (handle == null || !_editValid) {
|
||||
setState(() {
|
||||
_timeline = null;
|
||||
_dirty = false;
|
||||
_error = null;
|
||||
});
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
widget.session.commands.setAudio(
|
||||
sequence: widget.sequence,
|
||||
clip: widget.clip.id,
|
||||
tick: _editTick ?? view.playheadTick,
|
||||
db: value.db,
|
||||
muted: value.muted,
|
||||
);
|
||||
setState(() {
|
||||
_timeline = null;
|
||||
_dirty = false;
|
||||
_editVersion = null;
|
||||
_editTick = null;
|
||||
_error = null;
|
||||
});
|
||||
return true;
|
||||
} catch (_) {
|
||||
setState(() => _error = context.l10n.updateVolumeFailed);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _submit(String text) {
|
||||
final db = double.tryParse(text.trim());
|
||||
if (db == null || !db.isFinite || db < -90 || db > 12) {
|
||||
setState(() => _error = context.l10n.invalidGain);
|
||||
return false;
|
||||
}
|
||||
return _commit(ClipAudioGain(AudioGainScale.quantizeDb(db)));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final view = widget.session.view(widget.sequence);
|
||||
return ListenableBuilder(
|
||||
listenable: view,
|
||||
builder: (context, _) {
|
||||
final query = view.version.kernelVersion.query();
|
||||
final handle = query.elementById(widget.clip.id);
|
||||
final record = handle == null ? widget.clip : query.element(handle);
|
||||
final localTick = handle == null
|
||||
? 0
|
||||
: view.playheadTick - query.absoluteStart(handle);
|
||||
final sourceTick = TimelineSourceClock(record).nearestSourceTick(
|
||||
localTick.clamp(0, record.duration > 0 ? record.duration - 1 : 0),
|
||||
);
|
||||
final saved = ClipAudioGain.fromRecord(record, sourceTick: sourceTick);
|
||||
final keyed =
|
||||
record.parameters?[ClipAudioGain.gainId]?.keyframeAt(sourceTick) !=
|
||||
null;
|
||||
final value = _editValid ? _timeline ?? saved : saved;
|
||||
final enabled = widget.hasAudio && handle != null;
|
||||
if (!_dirty) {
|
||||
final text = value.muted ? '-∞' : AudioGainScale.formatDb(value.db);
|
||||
if (_text.text != text) _text.text = text;
|
||||
}
|
||||
if (ClipAudioGain.isDetached(record)) {
|
||||
return Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
context.l10n.audioDetached,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
OutlinedButton.icon(
|
||||
key: const Key('audio-restore'),
|
||||
icon: const Icon(Icons.volume_up_outlined),
|
||||
label: Text(context.l10n.restoreAudio),
|
||||
onPressed: !enabled || !widget.session.acceptsEdits
|
||||
? null
|
||||
: () {
|
||||
try {
|
||||
widget.session.commands.setAudio(
|
||||
sequence: widget.sequence,
|
||||
clip: record.id,
|
||||
muted: false,
|
||||
);
|
||||
setState(() {
|
||||
_timeline = null;
|
||||
_dirty = false;
|
||||
_editVersion = null;
|
||||
_error = null;
|
||||
});
|
||||
} catch (_) {
|
||||
setState(
|
||||
() => _error = context.l10n.updateVolumeFailed,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
if (_error != null) Text(_error!),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.hasAudio
|
||||
? context.l10n.volume
|
||||
: context.l10n.unboundAudio,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('audio-key'),
|
||||
tooltip: context.l10n.toggleKeyframe(
|
||||
keyed
|
||||
? context.l10n.delete
|
||||
: context.l10n.addKeyframeAction,
|
||||
context.l10n.volume,
|
||||
),
|
||||
isSelected: keyed,
|
||||
icon: Transform.rotate(
|
||||
angle: 0.7853981633974483,
|
||||
child: Icon(
|
||||
keyed ? Icons.square : Icons.crop_square,
|
||||
size: 12,
|
||||
),
|
||||
),
|
||||
onPressed: !enabled
|
||||
? null
|
||||
: () {
|
||||
if (_dirty && !_submit(_text.text)) return;
|
||||
_focus.unfocus();
|
||||
FocusManager.instance
|
||||
.applyFocusChangesIfNeeded();
|
||||
try {
|
||||
widget.session.commands.editKeyframeChannel(
|
||||
sequence: widget.sequence,
|
||||
clip: widget.clip.id,
|
||||
tick: view.playheadTick,
|
||||
parameterIds: [ClipAudioGain.gainId],
|
||||
);
|
||||
} catch (_) {
|
||||
setState(
|
||||
() => _error =
|
||||
context.l10n.updateKeyframesFailed,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('audio-mute'),
|
||||
tooltip: value.muted
|
||||
? context.l10n.unmute
|
||||
: context.l10n.mute,
|
||||
isSelected: value.muted,
|
||||
icon: Icon(
|
||||
value.muted ? Icons.volume_off : Icons.volume_up,
|
||||
),
|
||||
onPressed: !enabled
|
||||
? null
|
||||
: () {
|
||||
_editVersion = null;
|
||||
_editTick = null;
|
||||
_commit(
|
||||
ClipAudioGain(saved.db, muted: !saved.muted),
|
||||
);
|
||||
},
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('audio-reset'),
|
||||
tooltip: context.l10n.resetVolume,
|
||||
icon: const Icon(Icons.restart_alt),
|
||||
onPressed: !enabled
|
||||
? null
|
||||
: () {
|
||||
_editVersion = null;
|
||||
_editTick = null;
|
||||
_commit(const ClipAudioGain(0));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: AppSlider(
|
||||
key: const Key('audio-slider'),
|
||||
value: value.muted
|
||||
? 0
|
||||
: AudioGainScale.positionAt(value.db),
|
||||
semanticFormatterCallback: (p) => p == 0
|
||||
? context.l10n.mute
|
||||
: '${AudioGainScale.formatDb(AudioGainScale.dbAt(p))} dB',
|
||||
onChangeStart: !enabled
|
||||
? null
|
||||
: (_) {
|
||||
_focus.unfocus();
|
||||
FocusManager.instance
|
||||
.applyFocusChangesIfNeeded();
|
||||
_beginEdit();
|
||||
},
|
||||
onChanged: !enabled
|
||||
? null
|
||||
: (p) => setState(() {
|
||||
if (!_editValid) {
|
||||
widget.session.clearAudioGainPreview(
|
||||
widget.clip.id,
|
||||
);
|
||||
_timeline = null;
|
||||
return;
|
||||
}
|
||||
_dirty = false;
|
||||
_timeline = p == 0
|
||||
? ClipAudioGain(saved.db, muted: true)
|
||||
: ClipAudioGain(
|
||||
AudioGainScale.quantizeDb(
|
||||
AudioGainScale.dbAt(p),
|
||||
),
|
||||
);
|
||||
widget.session.previewAudioGain(
|
||||
widget.sequence,
|
||||
widget.clip.id,
|
||||
_timeline!,
|
||||
);
|
||||
}),
|
||||
onChangeEnd: !enabled
|
||||
? null
|
||||
: (_) => _commit(_timeline ?? saved),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
SizedBox(
|
||||
width: 84,
|
||||
child: AppTextField(
|
||||
key: const Key('audio-db'),
|
||||
controller: _text,
|
||||
focusNode: _focus,
|
||||
label: null,
|
||||
unit: 'dB',
|
||||
enabled: enabled,
|
||||
errorText: _error,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
signed: true,
|
||||
decimal: true,
|
||||
),
|
||||
onChanged: (_) {
|
||||
if (!_dirty) {
|
||||
_beginEdit();
|
||||
}
|
||||
_dirty = true;
|
||||
},
|
||||
onSubmitted: _submit,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
|
||||
abstract final class ProjectCanvasPresets {
|
||||
static const values = {
|
||||
'16:9': ProjectCanvas.widescreen,
|
||||
'4:3': ProjectCanvas(1440, 1080),
|
||||
'1:1': ProjectCanvas(1080, 1080),
|
||||
'9:16': ProjectCanvas(1080, 1920),
|
||||
};
|
||||
}
|
||||
|
||||
extension ProjectCanvasLabel on ProjectCanvas {
|
||||
String label(BuildContext context) {
|
||||
for (final entry in ProjectCanvasPresets.values.entries) {
|
||||
if ((entry.value.aspectRatio - aspectRatio).abs() < 0.000001) {
|
||||
return entry.key;
|
||||
}
|
||||
}
|
||||
return context.l10n.custom;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'property_number_input.dart';
|
||||
|
||||
enum _CaptionPropertyCategory {
|
||||
captions,
|
||||
text;
|
||||
|
||||
String label(BuildContext context) => switch (this) {
|
||||
captions => context.l10n.captions,
|
||||
text => context.l10n.text,
|
||||
};
|
||||
}
|
||||
|
||||
/// Presentation only: validation, publication and history belong to editor.
|
||||
class CaptionProperties extends StatefulWidget {
|
||||
const CaptionProperties({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.sequence,
|
||||
required this.clipId,
|
||||
this.transformProperties,
|
||||
});
|
||||
final EditorTimelineSession session;
|
||||
final SequenceId sequence;
|
||||
final String clipId;
|
||||
final Widget? transformProperties;
|
||||
|
||||
@override
|
||||
State<CaptionProperties> createState() => _CaptionPropertiesState();
|
||||
}
|
||||
|
||||
class _CaptionPropertiesState extends State<CaptionProperties> {
|
||||
static const _maximumCommandSeconds = 9000000000000.0;
|
||||
_CaptionPropertyCategory _selected = _CaptionPropertyCategory.text;
|
||||
final _captionSearch = TextEditingController();
|
||||
String _captionQuery = '';
|
||||
bool _wrapCaptions = false;
|
||||
String? _scrubField;
|
||||
double? _scrubBase;
|
||||
double? _scrubTimeline;
|
||||
double _scrubScale = 1;
|
||||
String? _scrubVersion;
|
||||
|
||||
bool _save(SetCaption command) {
|
||||
try {
|
||||
widget.session.setCaption(widget.sequence, command);
|
||||
return true;
|
||||
} on CommandRejected catch (error) {
|
||||
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(
|
||||
error.code == 'staleVersion'
|
||||
? context.l10n.captionEditChanged
|
||||
: context.l10n.editFailed,
|
||||
),
|
||||
),
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
CommandTime _seconds(double value) =>
|
||||
CommandTime((value * 1000).round(), 1000);
|
||||
|
||||
bool _startScrub(String field, double value, double scale) {
|
||||
if (_scrubField != null) return false;
|
||||
setState(() {
|
||||
_scrubField = field;
|
||||
_scrubBase = value;
|
||||
_scrubTimeline = value;
|
||||
_scrubScale = scale;
|
||||
_scrubVersion = widget.session.version;
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
void _updateScrub(double distance, double min, double max) {
|
||||
final base = _scrubBase;
|
||||
if (base == null || _scrubVersion != widget.session.version) {
|
||||
_cancelScrub();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_scrubTimeline = (base + distance * _scrubScale).clamp(min, max);
|
||||
});
|
||||
}
|
||||
|
||||
void _endScrub() {
|
||||
final field = _scrubField;
|
||||
final value = _scrubTimeline;
|
||||
final base = _scrubBase;
|
||||
final version = _scrubVersion;
|
||||
_clearScrub();
|
||||
if (field == null || value == null || value == base || version == null) {
|
||||
return;
|
||||
}
|
||||
final command = switch (field) {
|
||||
'fontSize' => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
fontSize: value,
|
||||
expectedVersion: version,
|
||||
),
|
||||
'strokeWidth' => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
strokeWidth: value,
|
||||
expectedVersion: version,
|
||||
),
|
||||
'positionY' => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
positionY: value,
|
||||
expectedVersion: version,
|
||||
),
|
||||
'start' => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
start: _seconds(value),
|
||||
expectedVersion: version,
|
||||
),
|
||||
'duration' => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
duration: _seconds(value),
|
||||
expectedVersion: version,
|
||||
),
|
||||
_ => null,
|
||||
};
|
||||
if (command != null) _save(command);
|
||||
}
|
||||
|
||||
void _clearScrub() {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_scrubField = null;
|
||||
_scrubBase = null;
|
||||
_scrubTimeline = null;
|
||||
_scrubVersion = null;
|
||||
});
|
||||
}
|
||||
|
||||
void _cancelScrub() => _clearScrub();
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant CaptionProperties oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.clipId == widget.clipId &&
|
||||
oldWidget.sequence == widget.sequence) {
|
||||
return;
|
||||
}
|
||||
if (oldWidget.sequence != widget.sequence ||
|
||||
oldWidget.session != widget.session) {
|
||||
_selected = _CaptionPropertyCategory.text;
|
||||
}
|
||||
_scrubField = null;
|
||||
_scrubBase = null;
|
||||
_scrubTimeline = null;
|
||||
_scrubVersion = null;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_captionSearch.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _selectCue(String id) {
|
||||
final query = widget.session.persistence
|
||||
.timeline(widget.sequence)
|
||||
.current
|
||||
.query();
|
||||
final cue = query.elementById(ElementId(id));
|
||||
if (cue == null) return;
|
||||
final identity = widget.session.captionComponentFor(widget.sequence, cue);
|
||||
widget.session.view(widget.sequence).setSelection([identity ?? cue]);
|
||||
}
|
||||
|
||||
Widget _captionList(
|
||||
BuildContext context,
|
||||
List<({String id, String text})> cues,
|
||||
) {
|
||||
final matches = cues.indexed
|
||||
.where((entry) => entry.$2.text.toLowerCase().contains(_captionQuery))
|
||||
.toList();
|
||||
return Column(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.panelContentHorizontal,
|
||||
vertical: AppSpacing.small,
|
||||
),
|
||||
child: SizedBox(
|
||||
height: 28,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
key: const ValueKey('caption-search'),
|
||||
controller: _captionSearch,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
cursorHeight: AppTheme.inputCursorHeight(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
textInputAction: TextInputAction.search,
|
||||
decoration: InputDecoration(
|
||||
hintText: context.l10n.searchOptions(
|
||||
context.l10n.captions,
|
||||
),
|
||||
isDense: true,
|
||||
constraints: const BoxConstraints.tightFor(height: 28),
|
||||
contentPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 0,
|
||||
),
|
||||
prefixIcon: const Icon(Icons.search, size: 14),
|
||||
prefixIconConstraints: const BoxConstraints(
|
||||
minWidth: 28,
|
||||
minHeight: 28,
|
||||
),
|
||||
),
|
||||
onChanged: (value) => setState(
|
||||
() => _captionQuery = value.trim().toLowerCase(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
IconButton(
|
||||
key: const ValueKey('caption-wrap-toggle'),
|
||||
tooltip: _wrapCaptions
|
||||
? context.l10n.captionSingleLine
|
||||
: context.l10n.captionWrapLines,
|
||||
isSelected: _wrapCaptions,
|
||||
color: _wrapCaptions
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: null,
|
||||
icon: const Icon(Icons.wrap_text, size: 16),
|
||||
padding: EdgeInsets.zero,
|
||||
style: IconButton.styleFrom(
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
visualDensity: VisualDensity.standard,
|
||||
),
|
||||
constraints: const BoxConstraints.tightFor(
|
||||
width: 28,
|
||||
height: 28,
|
||||
),
|
||||
onPressed: () =>
|
||||
setState(() => _wrapCaptions = !_wrapCaptions),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: matches.isEmpty
|
||||
? Center(
|
||||
child: Text(
|
||||
context.l10n.noMatchingCaptions,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
)
|
||||
: ScrollEdgeFadeBuilder(
|
||||
key: const ValueKey('caption-scroll-fade'),
|
||||
builder: (controller) => ListView(
|
||||
key: const ValueKey('caption-scroll-list'),
|
||||
controller: controller,
|
||||
padding: EdgeInsets.zero,
|
||||
physics: const ClampingScrollPhysics(),
|
||||
children: [
|
||||
for (final (index, cue) in matches)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.panelContentHorizontal,
|
||||
vertical: AppSpacing.hairline,
|
||||
),
|
||||
child: Material(
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppRadius.menuItem,
|
||||
),
|
||||
color: cue.id == widget.clipId
|
||||
? Theme.of(context).colorScheme.onSurface
|
||||
.withValues(alpha: .05)
|
||||
: Colors.transparent,
|
||||
child: InkWell(
|
||||
key: ValueKey('caption-list-${cue.id}'),
|
||||
onTap: () => _selectCue(cue.id),
|
||||
borderRadius: BorderRadius.circular(
|
||||
AppRadius.menuItem,
|
||||
),
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(
|
||||
minHeight: 28,
|
||||
),
|
||||
child: Padding(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width:
|
||||
cues.length.toString().length * 8.0,
|
||||
child: Text(
|
||||
'${index + 1}',
|
||||
key: ValueKey(
|
||||
'caption-number-${cue.id}',
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodySmall,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 6),
|
||||
Expanded(
|
||||
child: Text(
|
||||
cue.text,
|
||||
key: ValueKey(
|
||||
'caption-content-${cue.id}',
|
||||
),
|
||||
style: Theme.of(context)
|
||||
.textTheme
|
||||
.bodyMedium,
|
||||
maxLines: _wrapCaptions ? null : 1,
|
||||
softWrap: _wrapCaptions,
|
||||
overflow: _wrapCaptions
|
||||
? TextOverflow.visible
|
||||
: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
SizedBox(
|
||||
width: 28,
|
||||
height: 28,
|
||||
child: IconButton(
|
||||
key: ValueKey(
|
||||
'caption-action-${cue.id}',
|
||||
),
|
||||
tooltip: context.l10n.select,
|
||||
padding: EdgeInsets.zero,
|
||||
constraints:
|
||||
const BoxConstraints.tightFor(
|
||||
width: 28,
|
||||
height: 28,
|
||||
),
|
||||
icon: const Icon(
|
||||
Icons.chevron_right,
|
||||
size: 14,
|
||||
),
|
||||
onPressed: () => _selectCue(cue.id),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: widget.session,
|
||||
builder: (context, _) {
|
||||
final q = widget.session.persistence
|
||||
.timeline(widget.sequence)
|
||||
.current
|
||||
.query();
|
||||
final handle = q.elementById(ElementId(widget.clipId));
|
||||
if (handle == null) return Text(context.l10n.captionDeleted);
|
||||
final clip = q.element(handle);
|
||||
final isRole = clip.containerStoryline != null;
|
||||
final role = isRole
|
||||
? handle
|
||||
: widget.session.captionRole(widget.sequence);
|
||||
final child = role == null ? null : q.element(role).containerStoryline;
|
||||
final cues = <({String id, String text})>[
|
||||
if (child != null)
|
||||
for (final cue in q.storylineElements(child))
|
||||
if (q.element(cue).payloadRef case final payload?)
|
||||
if (widget.session.payloadFor(payload)?.type == 'caption')
|
||||
(
|
||||
id: q.element(cue).id.value,
|
||||
text: widget.session
|
||||
.caption(widget.sequence, q.element(cue).id.value)
|
||||
.text,
|
||||
),
|
||||
];
|
||||
final categories = [
|
||||
_CaptionPropertyCategory.captions,
|
||||
if (!isRole) _CaptionPropertyCategory.text,
|
||||
];
|
||||
final selected = isRole ? _CaptionPropertyCategory.captions : _selected;
|
||||
Widget panel(Widget content) => WorkspacePanel(
|
||||
paintBackground: false,
|
||||
headerHeight: CompactPanelTabs.height,
|
||||
headerPadding: EdgeInsets.zero,
|
||||
showHeaderDivider: false,
|
||||
controls: CompactPanelTabs<_CaptionPropertyCategory>(
|
||||
values: categories,
|
||||
selected: selected,
|
||||
labelBuilder: (category) => category.label(context),
|
||||
tabKeyBuilder: (category) =>
|
||||
ValueKey('caption-property-tab-${category.name}'),
|
||||
onSelected: (category) => setState(() => _selected = category),
|
||||
),
|
||||
child: content,
|
||||
);
|
||||
if (selected == _CaptionPropertyCategory.captions) {
|
||||
return panel(_captionList(context, cues));
|
||||
}
|
||||
|
||||
final caption = widget.session.caption(widget.sequence, widget.clipId);
|
||||
final version = widget.session.version;
|
||||
final start = RationalTime.timelineTicks(q.localContext(handle).start)
|
||||
.seconds;
|
||||
final duration = RationalTime.timelineTicks(clip.duration).seconds;
|
||||
double shown(String field, double value) =>
|
||||
_scrubField == field ? _scrubTimeline ?? value : value;
|
||||
|
||||
Widget number({
|
||||
required String field,
|
||||
required String label,
|
||||
required double value,
|
||||
required double min,
|
||||
required double max,
|
||||
required double scale,
|
||||
String? unit,
|
||||
int decimalPlaces = 2,
|
||||
required SetCaption Function(double, String) command,
|
||||
}) => PropertyNumberInput(
|
||||
key: ValueKey('caption-$field'),
|
||||
label: label,
|
||||
unit: unit,
|
||||
decimalPlaces: decimalPlaces,
|
||||
value: shown(field, value),
|
||||
enabled: true,
|
||||
readOnly: _scrubField != null,
|
||||
scrubbing: _scrubField == field,
|
||||
editContext: (widget.clipId, version),
|
||||
submit: (next) async {
|
||||
if (!next.isFinite || next < min || next > max) return false;
|
||||
return _save(command(next, version));
|
||||
},
|
||||
onScrubStart: () => _startScrub(field, value, scale),
|
||||
onScrubUpdate: (distance) => _updateScrub(distance, min, max),
|
||||
onScrubEnd: _endScrub,
|
||||
onScrubCancel: _cancelScrub,
|
||||
);
|
||||
|
||||
return panel(
|
||||
ScrollEdgeFadeBuilder(
|
||||
key: const ValueKey('caption-detail-scroll-fade'),
|
||||
builder: (controller) => ListView(
|
||||
controller: controller,
|
||||
padding: const EdgeInsets.symmetric(vertical: AppSpacing.small),
|
||||
children:
|
||||
[
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.textClip,
|
||||
style: AppTheme.propertySectionTitleStyle(
|
||||
context,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: context.l10n.deleteCaption,
|
||||
icon: const Icon(Icons.delete_outline),
|
||||
onPressed: () {
|
||||
try {
|
||||
widget.session.commands.applyEdit(
|
||||
widget.sequence,
|
||||
DeleteClip(
|
||||
widget.clipId,
|
||||
expectedVersion: version,
|
||||
),
|
||||
);
|
||||
} on CommandRejected {
|
||||
ScaffoldMessenger.maybeOf(
|
||||
context,
|
||||
)?.showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.captionChanged),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(
|
||||
context.l10n.content,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
_CaptionTextInput(
|
||||
key: ValueKey(('caption-text', widget.clipId)),
|
||||
value: caption.text,
|
||||
maxLines: 3,
|
||||
onSubmit: (text) => _save(
|
||||
SetCaption(
|
||||
captionId: widget.clipId,
|
||||
text: text,
|
||||
expectedVersion: version,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
number(
|
||||
field: 'fontSize',
|
||||
label: context.l10n.fontSize,
|
||||
value: caption.fontSize,
|
||||
min: 1,
|
||||
max: 1024,
|
||||
scale: .2,
|
||||
unit: 'px',
|
||||
command: (value, expected) => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
fontSize: value,
|
||||
expectedVersion: expected,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
_CaptionColorInput(
|
||||
key: ValueKey(('caption-color', widget.clipId)),
|
||||
value: caption.color,
|
||||
label: context.l10n.color,
|
||||
onSubmit: (color) => _save(
|
||||
SetCaption(
|
||||
captionId: widget.clipId,
|
||||
color: color,
|
||||
expectedVersion: version,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
_CaptionColorInput(
|
||||
key: ValueKey(('caption-strokeColor', widget.clipId)),
|
||||
value: caption.strokeColor,
|
||||
label: context.l10n.outlineColor,
|
||||
onSubmit: (color) => _save(
|
||||
SetCaption(
|
||||
captionId: widget.clipId,
|
||||
strokeColor: color,
|
||||
expectedVersion: version,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
number(
|
||||
field: 'strokeWidth',
|
||||
label: context.l10n.outlineWidth,
|
||||
value: caption.strokeWidth,
|
||||
min: 0,
|
||||
max: caption.fontSize,
|
||||
scale: .05,
|
||||
unit: 'px',
|
||||
command: (value, expected) => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
strokeWidth: value,
|
||||
expectedVersion: expected,
|
||||
),
|
||||
),
|
||||
if (widget.transformProperties case final transform?) ...[
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
const Divider(height: 1),
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
Text(
|
||||
context.l10n.transform,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
transform,
|
||||
],
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
Text(
|
||||
context.l10n.captionBaseline,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
number(
|
||||
field: 'positionY',
|
||||
label: context.l10n.vertical,
|
||||
value: caption.positionY,
|
||||
min: -.5,
|
||||
max: .5,
|
||||
scale: .002,
|
||||
decimalPlaces: 3,
|
||||
command: (value, expected) => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
positionY: value,
|
||||
expectedVersion: expected,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
Text(
|
||||
context.l10n.time,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
Widget startField() => number(
|
||||
field: 'start',
|
||||
label: context.l10n.start,
|
||||
value: start,
|
||||
min: 0,
|
||||
max: _maximumCommandSeconds,
|
||||
scale: .01,
|
||||
unit: context.l10n.seconds,
|
||||
decimalPlaces: 3,
|
||||
command: (value, expected) => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
start: _seconds(value),
|
||||
expectedVersion: expected,
|
||||
),
|
||||
);
|
||||
Widget durationField() => number(
|
||||
field: 'duration',
|
||||
label: context.l10n.duration,
|
||||
value: duration,
|
||||
min: .001,
|
||||
max: _maximumCommandSeconds,
|
||||
scale: .01,
|
||||
unit: context.l10n.seconds,
|
||||
decimalPlaces: 3,
|
||||
command: (value, expected) => SetCaption(
|
||||
captionId: widget.clipId,
|
||||
duration: _seconds(value),
|
||||
expectedVersion: expected,
|
||||
),
|
||||
);
|
||||
if (constraints.maxWidth < 240) {
|
||||
return Column(
|
||||
children: [
|
||||
startField(),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
durationField(),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(child: startField()),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
Expanded(child: durationField()),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
]
|
||||
.map(
|
||||
(item) =>
|
||||
item is SizedBox ||
|
||||
identical(item, widget.transformProperties)
|
||||
? item
|
||||
: Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.panelContentHorizontal,
|
||||
),
|
||||
child: item,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _CaptionTextInput extends StatefulWidget {
|
||||
const _CaptionTextInput({
|
||||
super.key,
|
||||
required this.value,
|
||||
required this.onSubmit,
|
||||
this.label,
|
||||
this.maxLines = 1,
|
||||
});
|
||||
final String value;
|
||||
final String? label;
|
||||
final int maxLines;
|
||||
final bool Function(String) onSubmit;
|
||||
|
||||
@override
|
||||
State<_CaptionTextInput> createState() => _CaptionTextInputState();
|
||||
}
|
||||
|
||||
class _CaptionTextInputState extends State<_CaptionTextInput> {
|
||||
late final _controller = TextEditingController(text: widget.value);
|
||||
final _focus = FocusNode();
|
||||
bool _dirty = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focus.addListener(_handleFocus);
|
||||
}
|
||||
|
||||
void _handleFocus() {
|
||||
if (!_focus.hasFocus) _submit();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
if (!_dirty) return;
|
||||
final accepted = widget.onSubmit(_controller.text);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_dirty = false;
|
||||
_error = accepted ? null : context.l10n.notApplied;
|
||||
if (!accepted) _controller.text = widget.value;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant _CaptionTextInput oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (!_dirty && _controller.text != widget.value) {
|
||||
_controller.text = widget.value;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focus.removeListener(_handleFocus);
|
||||
_focus.dispose();
|
||||
_controller.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => AppTextField(
|
||||
controller: _controller,
|
||||
focusNode: _focus,
|
||||
label: widget.label,
|
||||
minLines: widget.maxLines,
|
||||
maxLines: widget.maxLines,
|
||||
textInputAction: TextInputAction.done,
|
||||
errorText: _error,
|
||||
onChanged: (_) {
|
||||
_dirty = true;
|
||||
if (_error != null) setState(() => _error = null);
|
||||
},
|
||||
onEditingComplete: () {},
|
||||
onSubmitted: (_) => _submit(),
|
||||
onTapOutside: (_) => _focus.unfocus(),
|
||||
);
|
||||
}
|
||||
|
||||
class _CaptionColorInput extends StatelessWidget {
|
||||
const _CaptionColorInput({
|
||||
super.key,
|
||||
required this.value,
|
||||
required this.label,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final String value;
|
||||
final String label;
|
||||
final bool Function(String) onSubmit;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 20,
|
||||
height: 20,
|
||||
decoration: BoxDecoration(
|
||||
color: Color(int.parse('FF${value.substring(1)}', radix: 16)),
|
||||
border: Border.all(color: Theme.of(context).colorScheme.outline),
|
||||
borderRadius: BorderRadius.circular(AppRadius.extraSmall),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
Expanded(
|
||||
child: _CaptionTextInput(
|
||||
value: value,
|
||||
label: label,
|
||||
onSubmit: onSubmit,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/media_color_interpretation.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import '../preview/preview_panel.dart';
|
||||
|
||||
class ColorInterpretationProperties extends ConsumerWidget {
|
||||
const ColorInterpretationProperties({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
required this.session,
|
||||
required this.assetId,
|
||||
required this.trackIndex,
|
||||
});
|
||||
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
final EditorTimelineSession session;
|
||||
final String assetId;
|
||||
final int trackIndex;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final preview = ref
|
||||
.watch(editorPreviewProvider(projectId, timelineId))
|
||||
.asData
|
||||
?.value;
|
||||
Widget contents() {
|
||||
final selected = session.mediaColorInterpretation(assetId, trackIndex);
|
||||
final colors = preview?.videoColorSpaces(assetId);
|
||||
final detected = colors?.elementAtOrNull(trackIndex);
|
||||
final reported =
|
||||
colors != null && trackIndex >= 0 && trackIndex < colors.length;
|
||||
final status = selected != null
|
||||
? context.l10n.manualColorSpace(selected.label(context.l10n))
|
||||
: detected != null
|
||||
? context.l10n.detectedColorSpace(detected.label(context.l10n))
|
||||
: reported
|
||||
? context.l10n.unknownColorSpace
|
||||
: context.l10n.colorInfoNotLoaded;
|
||||
return Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
spacing: AppSpacing.gap,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.mediaColorSpace,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
Flexible(
|
||||
child: AppSelect<String>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
key: const Key('media-color-menu'),
|
||||
outlined: false,
|
||||
label: context.l10n.mediaColorInterpretation,
|
||||
value: selected?.name ?? 'auto',
|
||||
onChanged: !reported
|
||||
? null
|
||||
: (value) => session.commands.setMediaColor(
|
||||
assetId,
|
||||
trackIndex,
|
||||
value == 'auto'
|
||||
? null
|
||||
: MediaColorSpace.values.byName(value),
|
||||
),
|
||||
options: [
|
||||
AppSelectOption('auto', context.l10n.auto),
|
||||
for (final color in RenderColorSpace.values)
|
||||
AppSelectOption(color.name, color.label(context.l10n)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
Text(
|
||||
status,
|
||||
key: const Key('media-color-status'),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([session, ?preview]),
|
||||
builder: (_, _) => contents(),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,579 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/features/properties/animation_labels.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../preview/preview_panel.dart';
|
||||
import 'property_number_input.dart';
|
||||
|
||||
class MaskProperties extends ConsumerStatefulWidget {
|
||||
const MaskProperties({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
required this.element,
|
||||
});
|
||||
final String projectId, timelineId;
|
||||
final ElementId element;
|
||||
@override
|
||||
ConsumerState<MaskProperties> createState() => _MaskPropertiesState();
|
||||
}
|
||||
|
||||
class _MaskPropertiesState extends ConsumerState<MaskProperties> {
|
||||
PreviewController? _preview;
|
||||
ElementId? _boundElement;
|
||||
String? _error;
|
||||
int? _gestureGeneration;
|
||||
String? _scrubField;
|
||||
ClipMask Function(double)? _scrubChange;
|
||||
double _scrubValue = 0;
|
||||
Future<bool>? _pendingValueCommit;
|
||||
@override
|
||||
void dispose() {
|
||||
final preview = _preview;
|
||||
scheduleMicrotask(() => preview?.releaseMaskEditing(this));
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
bool _apply(PreviewController preview, ClipMask mask) {
|
||||
try {
|
||||
preview.applyMask(mask);
|
||||
setState(() => _error = null);
|
||||
return true;
|
||||
} catch (_) {
|
||||
setState(() => _error = context.l10n.updateMaskFailed);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> _submitValue(
|
||||
PreviewController preview,
|
||||
double value,
|
||||
double min,
|
||||
double max,
|
||||
ClipMask Function(double) change,
|
||||
) {
|
||||
final operation = Future<bool>.sync(
|
||||
() =>
|
||||
value.isFinite &&
|
||||
value >= min &&
|
||||
value <= max &&
|
||||
_apply(preview, change(value)),
|
||||
);
|
||||
_pendingValueCommit = operation;
|
||||
return operation.whenComplete(() {
|
||||
if (identical(_pendingValueCommit, operation)) _pendingValueCommit = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _editKeys(PreviewController preview, List<String> ids) async {
|
||||
final element = widget.element;
|
||||
final maskId = preview.selectedMaskId;
|
||||
final tick = preview.positionTick;
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
FocusManager.instance.applyFocusChangesIfNeeded();
|
||||
final pending = _pendingValueCommit;
|
||||
if (pending != null && !await pending) return;
|
||||
if (!mounted ||
|
||||
widget.element != element ||
|
||||
_preview != preview ||
|
||||
preview.maskEditingElement != element ||
|
||||
preview.selectedMaskId != maskId ||
|
||||
preview.positionTick != tick ||
|
||||
_scrubField != null) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
preview.toggleMaskKeys(ids);
|
||||
} catch (_) {
|
||||
setState(() => _error = context.l10n.updateKeyframesFailed);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final preview = ref
|
||||
.watch(editorPreviewProvider(widget.projectId, widget.timelineId))
|
||||
.value;
|
||||
if (preview == null) return const SizedBox.shrink();
|
||||
if (_preview != preview || _boundElement != widget.element) {
|
||||
final previous = _preview;
|
||||
if (previous != null && previous != preview) {
|
||||
scheduleMicrotask(() => previous.releaseMaskEditing(this));
|
||||
}
|
||||
_preview = preview;
|
||||
_boundElement = widget.element;
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (mounted && identical(_preview, preview)) {
|
||||
preview.setMaskEditing(widget.element, owner: this);
|
||||
}
|
||||
});
|
||||
}
|
||||
return ListenableBuilder(
|
||||
listenable: preview,
|
||||
builder: (context, _) {
|
||||
final mask = preview.maskFor(widget.element);
|
||||
final animation = preview.maskAnimation(widget.element);
|
||||
final stack = preview.maskStackFor(widget.element);
|
||||
final layers =
|
||||
preview.maskStackFor(widget.element)?.layers ?? <ClipMaskLayer>[];
|
||||
final selectedId = preview.selectedMaskId;
|
||||
final initialId = layers.where((e) => e.enabled).firstOrNull?.id;
|
||||
final enabled =
|
||||
preview.canPlay &&
|
||||
stack != null &&
|
||||
preview.maskEditingElement == widget.element;
|
||||
Widget key(String label) {
|
||||
final ids = localizedMaskChannels(context)[label]!;
|
||||
return IconButton(
|
||||
key: ValueKey('mask-key-$label'),
|
||||
tooltip: context.l10n.keyframeLabel(label),
|
||||
isSelected: animation?.keyed(ids) == true,
|
||||
onPressed: enabled && _scrubField == null && animation != null
|
||||
? () => _editKeys(preview, ids)
|
||||
: null,
|
||||
icon: Transform.rotate(
|
||||
angle: math.pi / 4,
|
||||
child: Icon(
|
||||
animation?.keyed(ids) == true
|
||||
? Icons.square
|
||||
: Icons.crop_square,
|
||||
size: 12,
|
||||
color: animation?.keyed(ids) == true
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget field(
|
||||
String label,
|
||||
double value,
|
||||
double min,
|
||||
double max,
|
||||
ClipMask Function(double) change, {
|
||||
String? unit,
|
||||
bool wrapRotation = false,
|
||||
}) => PropertyNumberInput(
|
||||
key: ValueKey((selectedId, label)),
|
||||
label: label,
|
||||
unit: unit,
|
||||
value: value,
|
||||
enabled: enabled,
|
||||
readOnly: _scrubField != null,
|
||||
scrubbing: _scrubField == label,
|
||||
editContext: (
|
||||
widget.element,
|
||||
selectedId,
|
||||
stack?.record,
|
||||
stack?.localTick,
|
||||
),
|
||||
submit: (v) => _submitValue(preview, v, min, max, change),
|
||||
onScrubStart: () {
|
||||
if (_scrubField != null) return false;
|
||||
final preparing = preview.beginMaskEdit();
|
||||
final generation = _gestureGeneration = preview.maskEditGeneration;
|
||||
_scrubChange = change;
|
||||
_scrubValue = value;
|
||||
setState(() => _scrubField = label);
|
||||
unawaited(
|
||||
preparing
|
||||
.then((ready) {
|
||||
if (!ready && generation == preview.maskEditGeneration) {
|
||||
preview.cancelMaskEdit();
|
||||
if (mounted) setState(() => _scrubField = null);
|
||||
}
|
||||
})
|
||||
.catchError((Object error) {
|
||||
if (generation == preview.maskEditGeneration) {
|
||||
preview.cancelMaskEdit();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_scrubField = null;
|
||||
_error = context.l10n.maskPreviewFailed;
|
||||
});
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
return true;
|
||||
},
|
||||
onScrubUpdate: (distance) {
|
||||
if (_gestureGeneration == preview.maskEditGeneration) {
|
||||
preview.updateMask(
|
||||
_scrubChange!(
|
||||
wrapRotation
|
||||
? normalizeRotationDegrees(_scrubValue + distance)
|
||||
: (_scrubValue + distance).clamp(min, max),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
onScrubEnd: () {
|
||||
if (_gestureGeneration == preview.maskEditGeneration) {
|
||||
preview.endMaskEdit();
|
||||
}
|
||||
if (mounted) setState(() => _scrubField = null);
|
||||
},
|
||||
onScrubCancel: () {
|
||||
if (_gestureGeneration == preview.maskEditGeneration) {
|
||||
preview.cancelMaskEdit();
|
||||
}
|
||||
if (mounted) setState(() => _scrubField = null);
|
||||
},
|
||||
);
|
||||
Widget axes(String label, Widget first, Widget second) => LayoutBuilder(
|
||||
builder: (context, constraints) => Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: constraints.maxWidth < 240
|
||||
? Column(
|
||||
children: [
|
||||
first,
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
second,
|
||||
],
|
||||
)
|
||||
: Row(
|
||||
children: [
|
||||
Expanded(child: first),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
Expanded(child: second),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
key(label),
|
||||
],
|
||||
),
|
||||
);
|
||||
Widget singleField(String label, Widget input) => Row(
|
||||
children: [
|
||||
Expanded(child: input),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
key(label),
|
||||
],
|
||||
);
|
||||
Widget heading(String label) => Padding(
|
||||
padding: const EdgeInsets.only(bottom: AppSpacing.small),
|
||||
child: Text(
|
||||
label,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
);
|
||||
Widget section(List<Widget> children) => Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: children,
|
||||
),
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
section([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.mask,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: context.l10n.moveMaskUp,
|
||||
icon: const Icon(Icons.arrow_upward, size: 18),
|
||||
onPressed:
|
||||
enabled &&
|
||||
layers.indexWhere((e) => e.id == selectedId) > 0
|
||||
? () {
|
||||
final ids = layers.map((e) => e.id).toList();
|
||||
final i = ids.indexOf(selectedId!);
|
||||
ids.insert(i - 1, ids.removeAt(i));
|
||||
preview.reorderMasks(ids);
|
||||
}
|
||||
: null,
|
||||
),
|
||||
IconButton(
|
||||
tooltip: context.l10n.moveMaskDown,
|
||||
icon: const Icon(Icons.arrow_downward, size: 18),
|
||||
onPressed:
|
||||
enabled &&
|
||||
selectedId != null &&
|
||||
layers.lastOrNull?.id != selectedId
|
||||
? () {
|
||||
final ids = layers.map((e) => e.id).toList();
|
||||
final i = ids.indexOf(selectedId);
|
||||
ids.insert(i + 1, ids.removeAt(i));
|
||||
preview.reorderMasks(ids);
|
||||
}
|
||||
: null,
|
||||
),
|
||||
AppDropdownMenu(
|
||||
enabled: enabled,
|
||||
items: [
|
||||
AppMenuItem(
|
||||
label: context.l10n.rectangle,
|
||||
onPressed: () =>
|
||||
preview.addMask(ClipMaskShape.rectangle),
|
||||
),
|
||||
AppMenuItem(
|
||||
label: context.l10n.ellipse,
|
||||
onPressed: () => preview.addMask(ClipMaskShape.ellipse),
|
||||
),
|
||||
],
|
||||
builder: (context, toggle, focusNode) => IconButton(
|
||||
focusNode: focusNode,
|
||||
tooltip: context.l10n.addMask,
|
||||
icon: const Icon(Icons.add),
|
||||
onPressed: toggle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]),
|
||||
section([
|
||||
AppItemGroup(
|
||||
children: [
|
||||
for (var i = 0; i < layers.length; i++)
|
||||
AppItem(
|
||||
key: ValueKey('mask-row-${layers[i].id}'),
|
||||
selected: layers[i].id == selectedId,
|
||||
onPressed: () => preview.selectMask(layers[i].id),
|
||||
leading: IconButton(
|
||||
tooltip: layers[i].enabled
|
||||
? context.l10n.disableMask
|
||||
: context.l10n.enableMask,
|
||||
icon: Icon(
|
||||
layers[i].enabled
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
size: 18,
|
||||
),
|
||||
onPressed: enabled
|
||||
? () => preview.configureMask(
|
||||
layers[i].id,
|
||||
enabled: !layers[i].enabled,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
actions: [
|
||||
AppDropdownMenu(
|
||||
enabled: enabled && layers[i].id != initialId,
|
||||
items: [
|
||||
for (final mode in ClipMaskMode.values)
|
||||
AppMenuItem(
|
||||
label: [
|
||||
context.l10n.add,
|
||||
context.l10n.intersect,
|
||||
context.l10n.subtract,
|
||||
][mode.index],
|
||||
selected: layers[i].mode == mode,
|
||||
onPressed: () => preview.configureMask(
|
||||
layers[i].id,
|
||||
mode: mode,
|
||||
),
|
||||
),
|
||||
],
|
||||
builder: (context, toggle, focusNode) => IconButton(
|
||||
focusNode: focusNode,
|
||||
tooltip: layers[i].id == initialId
|
||||
? context.l10n.initialRegion
|
||||
: context.l10n.maskMode(
|
||||
[
|
||||
context.l10n.add,
|
||||
context.l10n.intersect,
|
||||
context.l10n.subtract,
|
||||
][layers[i].mode.index],
|
||||
),
|
||||
icon: Icon(
|
||||
layers[i].id == initialId
|
||||
? Icons.crop_free
|
||||
: switch (layers[i].mode) {
|
||||
ClipMaskMode.add => Icons.add,
|
||||
ClipMaskMode.intersect =>
|
||||
Icons.filter_center_focus,
|
||||
ClipMaskMode.subtract => Icons.remove,
|
||||
},
|
||||
size: AppIconSize.standard,
|
||||
),
|
||||
onPressed: toggle,
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
tooltip: context.l10n.deleteMask,
|
||||
icon: const Icon(Icons.delete_outline, size: 18),
|
||||
onPressed: enabled
|
||||
? () => preview.removeMask(layers[i].id)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
child: Text(
|
||||
'${[context.l10n.rectangle, context.l10n.ellipse][layers[i].mask.shape.index]} ${i + 1}',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
]),
|
||||
if (mask != null && animation != null) ...[
|
||||
section([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: AppButtonGroup(
|
||||
expanded: true,
|
||||
label: context.l10n.mask,
|
||||
children: [
|
||||
for (final entry in [
|
||||
(
|
||||
ClipMaskShape.rectangle,
|
||||
Icons.crop_square,
|
||||
context.l10n.rectangle,
|
||||
),
|
||||
(
|
||||
ClipMaskShape.ellipse,
|
||||
Icons.circle_outlined,
|
||||
context.l10n.ellipse,
|
||||
),
|
||||
])
|
||||
IconButton(
|
||||
key: ValueKey('mask-shape-${entry.$1.name}'),
|
||||
tooltip: entry.$3,
|
||||
isSelected: mask.shape == entry.$1,
|
||||
onPressed: enabled
|
||||
? () => _apply(
|
||||
preview,
|
||||
mask.copyWith(shape: entry.$1),
|
||||
)
|
||||
: null,
|
||||
icon: Icon(entry.$2),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
IconButton(
|
||||
tooltip: context.l10n.resetMask,
|
||||
onPressed: enabled
|
||||
? () => _apply(preview, ClipMask(shape: mask.shape))
|
||||
: null,
|
||||
icon: const Icon(Icons.restart_alt),
|
||||
),
|
||||
],
|
||||
),
|
||||
]),
|
||||
section([
|
||||
heading(context.l10n.position),
|
||||
axes(
|
||||
context.l10n.position,
|
||||
field(
|
||||
'X',
|
||||
mask.x * 100,
|
||||
ClipMask.minPosition * 100,
|
||||
ClipMask.maxPosition * 100,
|
||||
(v) => mask.copyWith(x: v / 100),
|
||||
unit: '%',
|
||||
),
|
||||
field(
|
||||
'Y',
|
||||
mask.y * 100,
|
||||
ClipMask.minPosition * 100,
|
||||
ClipMask.maxPosition * 100,
|
||||
(v) => mask.copyWith(y: v / 100),
|
||||
unit: '%',
|
||||
),
|
||||
),
|
||||
]),
|
||||
section([
|
||||
singleField(
|
||||
context.l10n.rotation,
|
||||
field(
|
||||
context.l10n.rotation,
|
||||
mask.rotation,
|
||||
-180,
|
||||
180,
|
||||
(v) => mask.copyWith(rotation: v),
|
||||
unit: '°',
|
||||
wrapRotation: true,
|
||||
),
|
||||
),
|
||||
]),
|
||||
section([
|
||||
heading(context.l10n.size),
|
||||
axes(
|
||||
context.l10n.size,
|
||||
field(
|
||||
'W',
|
||||
mask.width * 100,
|
||||
ClipMask.minExtent * 100,
|
||||
ClipMask.maxExtent * 100,
|
||||
(v) => mask.copyWith(width: v / 100),
|
||||
unit: '%',
|
||||
),
|
||||
field(
|
||||
'H',
|
||||
mask.height * 100,
|
||||
ClipMask.minExtent * 100,
|
||||
ClipMask.maxExtent * 100,
|
||||
(v) => mask.copyWith(height: v / 100),
|
||||
unit: '%',
|
||||
),
|
||||
),
|
||||
]),
|
||||
section([
|
||||
singleField(
|
||||
context.l10n.feather,
|
||||
field(
|
||||
context.l10n.feather,
|
||||
mask.feather * 100,
|
||||
0,
|
||||
100,
|
||||
(v) => mask.copyWith(feather: v / 100),
|
||||
unit: '%',
|
||||
),
|
||||
),
|
||||
]),
|
||||
section([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.invert,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
AppSwitch(
|
||||
value: mask.inverted,
|
||||
onChanged: enabled
|
||||
? (v) => _apply(preview, mask.copyWith(inverted: v))
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
]),
|
||||
],
|
||||
if (_error != null)
|
||||
section([
|
||||
Text(
|
||||
_error!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
]),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
part 'picture_edits.g.dart';
|
||||
part 'picture_edits.freezed.dart';
|
||||
|
||||
enum PictureEditFailure { keyframes, alignment, invalidTransform, transform }
|
||||
|
||||
@freezed
|
||||
abstract class PictureEditTarget with _$PictureEditTarget {
|
||||
const factory PictureEditTarget({
|
||||
required TimelineVersion version,
|
||||
required int tick,
|
||||
}) = _PictureEditTarget;
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class PictureEditException
|
||||
with _$PictureEditException
|
||||
implements Exception {
|
||||
const factory PictureEditException(PictureEditFailure failure) =
|
||||
_PictureEditException;
|
||||
}
|
||||
|
||||
@riverpod
|
||||
class PictureEdits extends _$PictureEdits {
|
||||
Future<bool>? _pending;
|
||||
@override
|
||||
AsyncValue<void> build(
|
||||
EditorTimelineSession session,
|
||||
SequenceId sequence,
|
||||
ElementId clip,
|
||||
) => const AsyncData(null);
|
||||
|
||||
PictureEditTarget _capture() {
|
||||
final view = session.view(sequence);
|
||||
return PictureEditTarget(
|
||||
version: view.version.kernelVersion,
|
||||
tick: view.playheadTick,
|
||||
);
|
||||
}
|
||||
|
||||
bool _valid(
|
||||
PictureEditTarget target,
|
||||
bool Function() isCurrent,
|
||||
PreviewController? preview,
|
||||
) {
|
||||
if (!ref.mounted ||
|
||||
!isCurrent() ||
|
||||
session.activeSequenceId != sequence ||
|
||||
preview?.transforms.hasPending == true) {
|
||||
return false;
|
||||
}
|
||||
final view = session.view(sequence);
|
||||
return target.tick == view.playheadTick &&
|
||||
identical(target.version, view.version.kernelVersion);
|
||||
}
|
||||
|
||||
ClipAnimation? animation() {
|
||||
final view = session.view(sequence);
|
||||
final query = view.version.kernelVersion.query();
|
||||
final handle = query.elementById(clip);
|
||||
return handle == null
|
||||
? null
|
||||
: ClipAnimation.at(
|
||||
query,
|
||||
handle,
|
||||
view.playheadTick,
|
||||
TimelineClock.standard.toTicks(
|
||||
session.persistence.timeline(sequence).format.frameDuration,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<bool> commit(
|
||||
PreviewController? preview,
|
||||
ClipTransform Function(ClipTransform) change, {
|
||||
required bool Function() isCurrent,
|
||||
}) {
|
||||
if (state.isLoading || preview?.transforms.hasPending == true) {
|
||||
return Future.value(false);
|
||||
}
|
||||
final target = _capture();
|
||||
final work = _run(PictureEditFailure.transform, () async {
|
||||
await preview?.pauseForCanvasInteraction();
|
||||
if (!_valid(target, isCurrent, preview)) return false;
|
||||
final current = animation()?.value;
|
||||
if (current == null) return false;
|
||||
final value = change(current);
|
||||
if (!value.isValid) {
|
||||
throw const PictureEditException(PictureEditFailure.invalidTransform);
|
||||
}
|
||||
if (value.x == current.x &&
|
||||
value.y == current.y &&
|
||||
value.scale == current.scale &&
|
||||
value.scaleY == current.scaleY &&
|
||||
value.rotation == current.rotation) {
|
||||
return true;
|
||||
}
|
||||
session.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
tick: target.tick,
|
||||
change: (_) => value,
|
||||
);
|
||||
return true;
|
||||
});
|
||||
_pending = work;
|
||||
return work.whenComplete(() {
|
||||
if (identical(_pending, work)) _pending = null;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> editKeys(
|
||||
PreviewController? preview,
|
||||
TransformChannel channel, {
|
||||
KeyframeAction? action,
|
||||
ParameterInterpolation? interpolation,
|
||||
required bool Function() isCurrent,
|
||||
}) async {
|
||||
final pending = _pending;
|
||||
if (pending != null && !await pending) return;
|
||||
if (!ref.mounted ||
|
||||
!isCurrent() ||
|
||||
state.isLoading ||
|
||||
preview?.transforms.hasPending == true) {
|
||||
return;
|
||||
}
|
||||
final target = _capture();
|
||||
await _run(PictureEditFailure.keyframes, () async {
|
||||
await preview?.pauseForCanvasInteraction();
|
||||
if (!_valid(target, isCurrent, preview)) return false;
|
||||
session.commands.editKeyframeChannel(
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
tick: target.tick,
|
||||
parameterIds: channel.ids,
|
||||
action: action,
|
||||
interpolation: interpolation,
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> align(
|
||||
PreviewController preview,
|
||||
CanvasAlignment alignment, {
|
||||
required bool Function() isCurrent,
|
||||
}) async {
|
||||
if (state.isLoading || preview.transforms.hasPending) return;
|
||||
final target = _capture();
|
||||
final current = animation();
|
||||
if (current == null) return;
|
||||
final command = AlignClip(
|
||||
clipId: clip.value,
|
||||
at: CommandTime(
|
||||
current.start + current.localTick,
|
||||
TimelineClock.ticksPerSecond,
|
||||
),
|
||||
alignment: alignment,
|
||||
expectedVersion: session.version,
|
||||
);
|
||||
await _run(PictureEditFailure.alignment, () async {
|
||||
await preview.pauseForCanvasInteraction();
|
||||
await session.alignClip(
|
||||
sequence,
|
||||
command,
|
||||
isCancelled: () => !_valid(target, isCurrent, preview),
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
Future<bool> _run(
|
||||
PictureEditFailure failure,
|
||||
Future<bool> Function() action,
|
||||
) async {
|
||||
final lease = ref.keepAlive();
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
final applied = await session.runEditAsync(
|
||||
switch (failure) {
|
||||
PictureEditFailure.keyframes => 'editKeyframes',
|
||||
PictureEditFailure.alignment => 'alignClip',
|
||||
_ => 'setTransform',
|
||||
},
|
||||
sequence,
|
||||
action,
|
||||
context: {
|
||||
'clipIds': [clip.value],
|
||||
'entryPoint': 'property',
|
||||
'playheadTick': session.view(sequence).playheadTick,
|
||||
},
|
||||
);
|
||||
if (ref.mounted) state = const AsyncData(null);
|
||||
return applied;
|
||||
} catch (error, stack) {
|
||||
if (ref.mounted) {
|
||||
state = AsyncError(
|
||||
error is PictureEditException ? error : PictureEditException(failure),
|
||||
stack,
|
||||
);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
lease.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,627 @@
|
||||
// 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 'picture_edits.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$PictureEditTarget {
|
||||
TimelineVersion get version;
|
||||
int get tick;
|
||||
|
||||
/// Create a copy of PictureEditTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$PictureEditTargetCopyWith<PictureEditTarget> get copyWith =>
|
||||
_$PictureEditTargetCopyWithImpl<PictureEditTarget>(
|
||||
this as PictureEditTarget,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as PictureEditTarget;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is PictureEditTarget &&
|
||||
(identical(other.version, _this.version) ||
|
||||
other.version == _this.version) &&
|
||||
(identical(other.tick, _this.tick) || other.tick == _this.tick));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as PictureEditTarget;
|
||||
return Object.hash(runtimeType, _this.version, _this.tick);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as PictureEditTarget;
|
||||
return 'PictureEditTarget(version: ${_this.version}, tick: ${_this.tick})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $PictureEditTargetCopyWith<$Res> {
|
||||
factory $PictureEditTargetCopyWith(
|
||||
PictureEditTarget value,
|
||||
$Res Function(PictureEditTarget) _then,
|
||||
) = _$PictureEditTargetCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({TimelineVersion version, int tick});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$PictureEditTargetCopyWithImpl<$Res>
|
||||
implements $PictureEditTargetCopyWith<$Res> {
|
||||
_$PictureEditTargetCopyWithImpl(this._self, this._then);
|
||||
|
||||
final PictureEditTarget _self;
|
||||
final $Res Function(PictureEditTarget) _then;
|
||||
|
||||
/// Create a copy of PictureEditTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? version = null, Object? tick = null}) {
|
||||
return _then(
|
||||
PictureEditTarget(
|
||||
version: null == version
|
||||
? _self.version
|
||||
: version // ignore: cast_nullable_to_non_nullable
|
||||
as TimelineVersion,
|
||||
tick: null == tick
|
||||
? _self.tick
|
||||
: tick // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [PictureEditTarget].
|
||||
extension PictureEditTargetPatterns on PictureEditTarget {
|
||||
/// 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(_PictureEditTarget value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditTarget() 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(_PictureEditTarget value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditTarget():
|
||||
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(_PictureEditTarget value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditTarget() 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(TimelineVersion version, int tick)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditTarget() when $default != null:
|
||||
return $default(_that.version, _that.tick);
|
||||
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(TimelineVersion version, int tick) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditTarget():
|
||||
return $default(_that.version, _that.tick);
|
||||
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(TimelineVersion version, int tick)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditTarget() when $default != null:
|
||||
return $default(_that.version, _that.tick);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _PictureEditTarget implements PictureEditTarget {
|
||||
const _PictureEditTarget({required this.version, required this.tick});
|
||||
|
||||
@override
|
||||
final TimelineVersion version;
|
||||
@override
|
||||
final int tick;
|
||||
|
||||
/// Create a copy of PictureEditTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$PictureEditTargetCopyWith<_PictureEditTarget> get copyWith =>
|
||||
__$PictureEditTargetCopyWithImpl<_PictureEditTarget>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _PictureEditTarget &&
|
||||
(identical(other.version, version) || other.version == version) &&
|
||||
(identical(other.tick, tick) || other.tick == tick));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, version, tick);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'PictureEditTarget(version: $version, tick: $tick)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$PictureEditTargetCopyWith<$Res>
|
||||
implements $PictureEditTargetCopyWith<$Res> {
|
||||
factory _$PictureEditTargetCopyWith(
|
||||
_PictureEditTarget value,
|
||||
$Res Function(_PictureEditTarget) _then,
|
||||
) = __$PictureEditTargetCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({TimelineVersion version, int tick});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$PictureEditTargetCopyWithImpl<$Res>
|
||||
implements _$PictureEditTargetCopyWith<$Res> {
|
||||
__$PictureEditTargetCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _PictureEditTarget _self;
|
||||
final $Res Function(_PictureEditTarget) _then;
|
||||
|
||||
/// Create a copy of PictureEditTarget
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? version = null, Object? tick = null}) {
|
||||
return _then(
|
||||
_PictureEditTarget(
|
||||
version: null == version
|
||||
? _self.version
|
||||
: version // ignore: cast_nullable_to_non_nullable
|
||||
as TimelineVersion,
|
||||
tick: null == tick
|
||||
? _self.tick
|
||||
: tick // ignore: cast_nullable_to_non_nullable
|
||||
as int,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
mixin _$PictureEditException {
|
||||
PictureEditFailure get failure;
|
||||
|
||||
/// Create a copy of PictureEditException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$PictureEditExceptionCopyWith<PictureEditException> get copyWith =>
|
||||
_$PictureEditExceptionCopyWithImpl<PictureEditException>(
|
||||
this as PictureEditException,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as PictureEditException;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is PictureEditException &&
|
||||
(identical(other.failure, _this.failure) ||
|
||||
other.failure == _this.failure));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as PictureEditException;
|
||||
return Object.hash(runtimeType, _this.failure);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as PictureEditException;
|
||||
return 'PictureEditException(failure: ${_this.failure})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $PictureEditExceptionCopyWith<$Res> {
|
||||
factory $PictureEditExceptionCopyWith(
|
||||
PictureEditException value,
|
||||
$Res Function(PictureEditException) _then,
|
||||
) = _$PictureEditExceptionCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({PictureEditFailure failure});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$PictureEditExceptionCopyWithImpl<$Res>
|
||||
implements $PictureEditExceptionCopyWith<$Res> {
|
||||
_$PictureEditExceptionCopyWithImpl(this._self, this._then);
|
||||
|
||||
final PictureEditException _self;
|
||||
final $Res Function(PictureEditException) _then;
|
||||
|
||||
/// Create a copy of PictureEditException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({Object? failure = null}) {
|
||||
return _then(
|
||||
PictureEditException(
|
||||
null == failure
|
||||
? _self.failure
|
||||
: failure // ignore: cast_nullable_to_non_nullable
|
||||
as PictureEditFailure,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [PictureEditException].
|
||||
extension PictureEditExceptionPatterns on PictureEditException {
|
||||
/// 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(_PictureEditException value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditException() 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(_PictureEditException value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditException():
|
||||
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(_PictureEditException value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditException() 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(PictureEditFailure failure)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditException() when $default != null:
|
||||
return $default(_that.failure);
|
||||
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(PictureEditFailure failure) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditException():
|
||||
return $default(_that.failure);
|
||||
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(PictureEditFailure failure)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _PictureEditException() when $default != null:
|
||||
return $default(_that.failure);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _PictureEditException implements PictureEditException {
|
||||
const _PictureEditException(this.failure);
|
||||
|
||||
@override
|
||||
final PictureEditFailure failure;
|
||||
|
||||
/// Create a copy of PictureEditException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$PictureEditExceptionCopyWith<_PictureEditException> get copyWith =>
|
||||
__$PictureEditExceptionCopyWithImpl<_PictureEditException>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _PictureEditException &&
|
||||
(identical(other.failure, failure) || other.failure == failure));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, failure);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'PictureEditException(failure: $failure)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$PictureEditExceptionCopyWith<$Res>
|
||||
implements $PictureEditExceptionCopyWith<$Res> {
|
||||
factory _$PictureEditExceptionCopyWith(
|
||||
_PictureEditException value,
|
||||
$Res Function(_PictureEditException) _then,
|
||||
) = __$PictureEditExceptionCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({PictureEditFailure failure});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$PictureEditExceptionCopyWithImpl<$Res>
|
||||
implements _$PictureEditExceptionCopyWith<$Res> {
|
||||
__$PictureEditExceptionCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _PictureEditException _self;
|
||||
final $Res Function(_PictureEditException) _then;
|
||||
|
||||
/// Create a copy of PictureEditException
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({Object? failure = null}) {
|
||||
return _then(
|
||||
_PictureEditException(
|
||||
null == failure
|
||||
? _self.failure
|
||||
: failure // ignore: cast_nullable_to_non_nullable
|
||||
as PictureEditFailure,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'picture_edits.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(PictureEdits)
|
||||
final pictureEditsProvider = PictureEditsFamily._();
|
||||
|
||||
final class PictureEditsProvider
|
||||
extends $NotifierProvider<PictureEdits, AsyncValue<void>> {
|
||||
PictureEditsProvider._({
|
||||
required PictureEditsFamily super.from,
|
||||
required (EditorTimelineSession, SequenceId, ElementId) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'pictureEditsProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$pictureEditsHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'pictureEditsProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
PictureEdits create() => PictureEdits();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AsyncValue<void> value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AsyncValue<void>>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is PictureEditsProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$pictureEditsHash() => r'6385f3bd53094d57ed054681d142591e059e8b08';
|
||||
|
||||
final class PictureEditsFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
PictureEdits,
|
||||
AsyncValue<void>,
|
||||
AsyncValue<void>,
|
||||
AsyncValue<void>,
|
||||
(EditorTimelineSession, SequenceId, ElementId)
|
||||
> {
|
||||
PictureEditsFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'pictureEditsProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
PictureEditsProvider call(
|
||||
EditorTimelineSession session,
|
||||
SequenceId sequence,
|
||||
ElementId clip,
|
||||
) => PictureEditsProvider._(argument: (session, sequence, clip), from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'pictureEditsProvider';
|
||||
}
|
||||
|
||||
abstract class _$PictureEdits extends $Notifier<AsyncValue<void>> {
|
||||
late final _$args =
|
||||
ref.$arg as (EditorTimelineSession, SequenceId, ElementId);
|
||||
EditorTimelineSession get session => _$args.$1;
|
||||
SequenceId get sequence => _$args.$2;
|
||||
ElementId get clip => _$args.$3;
|
||||
|
||||
AsyncValue<void> build(
|
||||
EditorTimelineSession session,
|
||||
SequenceId sequence,
|
||||
ElementId clip,
|
||||
);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<void>, AsyncValue<void>>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<void>, AsyncValue<void>>,
|
||||
AsyncValue<void>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(
|
||||
ref,
|
||||
() => build(_$args.$1, _$args.$2, _$args.$3),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,770 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex/features/properties/animation_labels.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/preview.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import '../preview/preview_panel.dart';
|
||||
import 'property_number_input.dart';
|
||||
import 'picture_edits.dart';
|
||||
|
||||
class PictureProperties extends ConsumerStatefulWidget {
|
||||
const PictureProperties({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
required this.session,
|
||||
required this.sequence,
|
||||
required this.clip,
|
||||
this.animationView = false,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
final EditorTimelineSession session;
|
||||
final SequenceId sequence;
|
||||
final ElementRecord clip;
|
||||
final bool animationView;
|
||||
|
||||
@override
|
||||
ConsumerState<PictureProperties> createState() => _PicturePropertiesState();
|
||||
}
|
||||
|
||||
class _PicturePropertiesState extends ConsumerState<PictureProperties> {
|
||||
bool _locked = true;
|
||||
PictureEditsProvider get _editProvider =>
|
||||
pictureEditsProvider(widget.session, widget.sequence, widget.clip.id);
|
||||
PictureEdits get _edits => ref.read(_editProvider.notifier);
|
||||
bool get _saving => ref.read(_editProvider).isLoading;
|
||||
bool Function() _guard() {
|
||||
final session = widget.session;
|
||||
final sequence = widget.sequence;
|
||||
final clip = widget.clip.id;
|
||||
return () =>
|
||||
mounted &&
|
||||
_scrubBase == null &&
|
||||
identical(widget.session, session) &&
|
||||
widget.sequence == sequence &&
|
||||
widget.clip.id == clip;
|
||||
}
|
||||
|
||||
String? get _error => switch (ref.read(_editProvider).error) {
|
||||
PictureEditException(:final failure) => switch (failure) {
|
||||
PictureEditFailure.keyframes => context.l10n.updateKeyframesFailed,
|
||||
PictureEditFailure.alignment => context.l10n.alignClipFailed,
|
||||
PictureEditFailure.invalidTransform => context.l10n.invalidTransform,
|
||||
PictureEditFailure.transform => context.l10n.updatePictureFailed,
|
||||
},
|
||||
_ => null,
|
||||
};
|
||||
PreviewTransformEdit? _scrubEdit;
|
||||
ClipTransform? _scrubBase;
|
||||
ClipTransform? _scrubTimeline;
|
||||
TimelineVersion? _scrubVersion;
|
||||
int? _scrubTick;
|
||||
String? _scrubField;
|
||||
ClipTransform Function(ClipTransform, double)? _scrubChange;
|
||||
|
||||
bool _startScrub(
|
||||
PreviewController? preview,
|
||||
String field,
|
||||
ClipTransform Function(ClipTransform, double) change,
|
||||
) {
|
||||
if (_scrubBase != null ||
|
||||
_saving ||
|
||||
preview?.transforms.hasPending == true ||
|
||||
widget.session.activeSequenceId != widget.sequence) {
|
||||
return false;
|
||||
}
|
||||
final base = _current();
|
||||
if (base == null) return false;
|
||||
_scrubBase = base;
|
||||
_scrubField = field;
|
||||
_scrubChange = change;
|
||||
_scrubVersion = widget.session.view(widget.sequence).version.kernelVersion;
|
||||
_scrubTick = widget.session.view(widget.sequence).playheadTick;
|
||||
if (preview != null) {
|
||||
final visual = preview.visualForProperties(widget.clip.id);
|
||||
if (visual == null ||
|
||||
(_scrubEdit = preview.transforms.begin(visual)) == null) {
|
||||
_scrubBase = null;
|
||||
_scrubField = null;
|
||||
_scrubChange = null;
|
||||
_scrubVersion = null;
|
||||
return false;
|
||||
}
|
||||
_scrubBase = _scrubEdit!.value;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool get _scrubValid =>
|
||||
_scrubBase != null &&
|
||||
_scrubEdit?.released != true &&
|
||||
_scrubTick == widget.session.view(widget.sequence).playheadTick &&
|
||||
widget.session.activeSequenceId == widget.sequence &&
|
||||
identical(
|
||||
_scrubVersion,
|
||||
widget.session.view(widget.sequence).version.kernelVersion,
|
||||
);
|
||||
|
||||
void _updateScrub(double distance) {
|
||||
if (!_scrubValid) {
|
||||
_cancelScrub();
|
||||
return;
|
||||
}
|
||||
final value = _scrubChange!(_scrubBase!, distance);
|
||||
if (!value.isValid) return;
|
||||
setState(() => _scrubTimeline = value);
|
||||
_scrubEdit?.update(value);
|
||||
}
|
||||
|
||||
void _endScrub(PreviewController? preview) {
|
||||
final value = _scrubTimeline;
|
||||
if (!_scrubValid ||
|
||||
value == null ||
|
||||
(value.x == _scrubBase!.x &&
|
||||
value.y == _scrubBase!.y &&
|
||||
value.rotation == _scrubBase!.rotation &&
|
||||
value.scale == _scrubBase!.scale &&
|
||||
value.scaleY == _scrubBase!.scaleY)) {
|
||||
_cancelScrub();
|
||||
return;
|
||||
}
|
||||
final edit = _scrubEdit;
|
||||
_scrubEdit = null;
|
||||
_scrubBase = null;
|
||||
_scrubField = null;
|
||||
_scrubChange = null;
|
||||
_scrubVersion = null;
|
||||
setState(() => _scrubTimeline = null);
|
||||
if (edit != null) {
|
||||
unawaited(edit.end());
|
||||
} else {
|
||||
unawaited(_commit(preview, (_) => value));
|
||||
}
|
||||
}
|
||||
|
||||
void _cancelScrub() {
|
||||
final edit = _scrubEdit;
|
||||
_scrubEdit = null;
|
||||
_scrubBase = null;
|
||||
_scrubField = null;
|
||||
_scrubChange = null;
|
||||
_scrubVersion = null;
|
||||
if (mounted) setState(() => _scrubTimeline = null);
|
||||
edit?.cancel();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
final edit = _scrubEdit;
|
||||
_scrubEdit = null;
|
||||
if (edit != null) scheduleMicrotask(edit.cancel);
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
ClipAnimation? _animation() => _edits.animation();
|
||||
ClipTransform? _current() => _animation()?.value;
|
||||
Future<void> _editKeys(
|
||||
PreviewController? preview,
|
||||
TransformChannel channel, {
|
||||
KeyframeAction? action,
|
||||
ParameterInterpolation? interpolation,
|
||||
}) {
|
||||
FocusManager.instance.primaryFocus?.unfocus();
|
||||
FocusManager.instance.applyFocusChangesIfNeeded();
|
||||
return _edits.editKeys(
|
||||
preview,
|
||||
channel,
|
||||
action: action,
|
||||
interpolation: interpolation,
|
||||
isCurrent: _guard(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _align(PreviewController preview, CanvasAlignment alignment) =>
|
||||
_edits.align(preview, alignment, isCurrent: _guard());
|
||||
Future<bool> _commit(
|
||||
PreviewController? preview,
|
||||
ClipTransform Function(ClipTransform) change,
|
||||
) => _edits.commit(preview, change, isCurrent: _guard());
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
ref.watch(_editProvider);
|
||||
final preview = ref
|
||||
.watch(editorPreviewProvider(widget.projectId, widget.timelineId))
|
||||
.asData
|
||||
?.value;
|
||||
Widget contents() {
|
||||
final animation = _animation();
|
||||
final live = preview?.activeSequence() == widget.sequence
|
||||
? preview?.transforms.valueFor(widget.clip.id)
|
||||
: null;
|
||||
final value =
|
||||
(_scrubValid ? _scrubTimeline : null) ??
|
||||
live ??
|
||||
_current() ??
|
||||
ClipTransform.fromRecord(widget.clip);
|
||||
final locked = preview?.aspectRatioLocked ?? _locked;
|
||||
final canvas = widget.session.canvas;
|
||||
final enabled = !_saving;
|
||||
final canvasDragging =
|
||||
preview?.transforms.hasPending == true && _scrubEdit == null;
|
||||
Widget keyButton(TransformChannel channel) {
|
||||
final keyed = animation?.keyed(channel) == true;
|
||||
final animated = animation?.animated(channel) == true;
|
||||
return IconButton(
|
||||
key: ValueKey('picture-key-${channel.name}'),
|
||||
tooltip: context.l10n.toggleKeyframe(
|
||||
keyed ? context.l10n.delete : context.l10n.addKeyframeAction,
|
||||
channel.label(context),
|
||||
),
|
||||
isSelected: keyed,
|
||||
color: animated ? Theme.of(context).colorScheme.primary : null,
|
||||
icon: Transform.rotate(
|
||||
angle: math.pi / 4,
|
||||
child: Icon(keyed ? Icons.square : Icons.crop_square, size: 12),
|
||||
),
|
||||
onPressed:
|
||||
enabled &&
|
||||
_scrubBase == null &&
|
||||
!canvasDragging &&
|
||||
animation != null
|
||||
? () => _editKeys(preview, channel)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Widget axes(TransformChannel channel, Widget first, Widget second) =>
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) => Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: constraints.maxWidth < 240
|
||||
? Column(
|
||||
children: [
|
||||
first,
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
second,
|
||||
],
|
||||
)
|
||||
: Row(
|
||||
children: [
|
||||
Expanded(child: first),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
Expanded(child: second),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
keyButton(channel),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
Widget keyTools(TransformChannel channel) {
|
||||
if (animation == null || !animation.animated(channel)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
final times = animation.keyTimes(channel);
|
||||
final tick = animation.playhead;
|
||||
final previous = times.where((t) => t < tick).lastOrNull;
|
||||
final next = times.where((t) => t > tick).firstOrNull;
|
||||
final canEdit = enabled && _scrubBase == null && !canvasDragging;
|
||||
Future<void> seek(int target) async {
|
||||
await preview?.pauseForCanvasInteraction();
|
||||
if (mounted && widget.session.activeSequenceId == widget.sequence) {
|
||||
widget.session.view(widget.sequence).seekTo(target);
|
||||
}
|
||||
}
|
||||
|
||||
return SizedBox(
|
||||
height: AppControlSize.standard,
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
context.l10n.keyframeCount(times.length),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const Spacer(),
|
||||
IconButton(
|
||||
key: ValueKey('picture-key-previous-${channel.name}'),
|
||||
tooltip: context.l10n.previousKeyframe(channel.label(context)),
|
||||
onPressed: canEdit && previous != null
|
||||
? () => seek(previous)
|
||||
: null,
|
||||
icon: const Icon(Icons.chevron_left, size: 16),
|
||||
),
|
||||
IconButton(
|
||||
key: ValueKey('picture-key-next-${channel.name}'),
|
||||
tooltip: context.l10n.nextKeyframe(channel.label(context)),
|
||||
onPressed: canEdit && next != null ? () => seek(next) : null,
|
||||
icon: const Icon(Icons.chevron_right, size: 16),
|
||||
),
|
||||
AppDropdownMenu(
|
||||
key: ValueKey('picture-key-menu-${channel.name}'),
|
||||
enabled: canEdit,
|
||||
builder: (context, toggle, focus) => IconButton(
|
||||
tooltip: context.l10n.keyframeSettings(
|
||||
channel.label(context),
|
||||
),
|
||||
focusNode: focus,
|
||||
onPressed: toggle,
|
||||
icon: const Icon(Icons.more_horiz, size: 16),
|
||||
),
|
||||
items: [
|
||||
for (final (mode, label) in [
|
||||
(ParameterInterpolation.linear, context.l10n.linear),
|
||||
(ParameterInterpolation.hold, context.l10n.hold),
|
||||
(ParameterInterpolation.easeIn, context.l10n.easeIn),
|
||||
(ParameterInterpolation.easeOut, context.l10n.easeOut),
|
||||
(ParameterInterpolation.easeInOut, context.l10n.easeInOut),
|
||||
])
|
||||
AppMenuItem(
|
||||
label: label,
|
||||
selected: animation.interpolation(channel) == mode,
|
||||
onPressed: animation.keyed(channel)
|
||||
? () => _editKeys(
|
||||
preview,
|
||||
channel,
|
||||
action: KeyframeAction.set,
|
||||
interpolation: mode,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
const AppMenuSeparator(),
|
||||
AppMenuItem(
|
||||
label: context.l10n.removeAllKeyframes,
|
||||
destructive: true,
|
||||
onPressed: animation.animated(channel)
|
||||
? () => _editKeys(
|
||||
preview,
|
||||
channel,
|
||||
action: KeyframeAction.clear,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget number(
|
||||
String id,
|
||||
String? label,
|
||||
double value,
|
||||
ClipTransform Function(ClipTransform, double) change, {
|
||||
String? unit,
|
||||
double min = double.negativeInfinity,
|
||||
double max = double.infinity,
|
||||
bool wrapRotation = false,
|
||||
}) => PropertyNumberInput(
|
||||
key: ValueKey(id),
|
||||
label: label,
|
||||
unit: unit,
|
||||
value: value,
|
||||
enabled: !_saving,
|
||||
readOnly: _scrubBase != null || preview?.transforms.hasPending == true,
|
||||
submit: (v) => _commit(preview, (current) => change(current, v)),
|
||||
onScrubStart: () => _startScrub(
|
||||
preview,
|
||||
id,
|
||||
(base, distance) => change(
|
||||
base,
|
||||
wrapRotation
|
||||
? normalizeRotationDegrees(value + distance)
|
||||
: (value + distance).clamp(min, max),
|
||||
),
|
||||
),
|
||||
onScrubUpdate: _updateScrub,
|
||||
onScrubEnd: () => _endScrub(preview),
|
||||
onScrubCancel: _cancelScrub,
|
||||
scrubbing: _scrubField == id,
|
||||
editContext: (
|
||||
widget.session.view(widget.sequence).version.kernelVersion,
|
||||
widget.session.view(widget.sequence).playheadTick,
|
||||
),
|
||||
);
|
||||
Widget section(List<Widget> children) => Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: children,
|
||||
),
|
||||
);
|
||||
final content = Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (widget.animationView && animation != null) ...[
|
||||
section([
|
||||
_KeyframeTimeline(
|
||||
animation: animation,
|
||||
enabled: enabled && !canvasDragging && _scrubBase == null,
|
||||
onSeek: (tick) async {
|
||||
await preview?.pauseForCanvasInteraction();
|
||||
if (mounted &&
|
||||
widget.session.activeSequenceId == widget.sequence) {
|
||||
widget.session.view(widget.sequence).seekTo(tick);
|
||||
}
|
||||
},
|
||||
),
|
||||
]),
|
||||
],
|
||||
if (!widget.animationView) ...[
|
||||
section([
|
||||
Text(
|
||||
context.l10n.alignment,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) => Wrap(
|
||||
spacing: AppSpacing.small,
|
||||
runSpacing: AppSpacing.small,
|
||||
children: [
|
||||
for (final group in [
|
||||
[
|
||||
(
|
||||
CanvasAlignment.left,
|
||||
context.l10n.alignLeft,
|
||||
Icons.align_horizontal_left,
|
||||
),
|
||||
(
|
||||
CanvasAlignment.horizontalCenter,
|
||||
context.l10n.alignHorizontalCenter,
|
||||
Icons.align_horizontal_center,
|
||||
),
|
||||
(
|
||||
CanvasAlignment.right,
|
||||
context.l10n.alignRight,
|
||||
Icons.align_horizontal_right,
|
||||
),
|
||||
],
|
||||
[
|
||||
(
|
||||
CanvasAlignment.top,
|
||||
context.l10n.alignTop,
|
||||
Icons.align_vertical_top,
|
||||
),
|
||||
(
|
||||
CanvasAlignment.verticalCenter,
|
||||
context.l10n.alignVerticalCenter,
|
||||
Icons.align_vertical_center,
|
||||
),
|
||||
(
|
||||
CanvasAlignment.bottom,
|
||||
context.l10n.alignBottom,
|
||||
Icons.align_vertical_bottom,
|
||||
),
|
||||
],
|
||||
])
|
||||
SizedBox(
|
||||
width: constraints.maxWidth < 200
|
||||
? constraints.maxWidth
|
||||
: (constraints.maxWidth - AppSpacing.small) / 2,
|
||||
child: AppButtonGroup(
|
||||
expanded: true,
|
||||
label: context.l10n.alignment,
|
||||
children: [
|
||||
for (final (alignment, label, icon) in group)
|
||||
IconButton(
|
||||
key: ValueKey(
|
||||
'picture-align-${alignment.name}',
|
||||
),
|
||||
tooltip: label,
|
||||
icon: Icon(icon, size: AppIconSize.standard),
|
||||
onPressed: () {
|
||||
if (!enabled ||
|
||||
canvasDragging ||
|
||||
preview == null ||
|
||||
preview.busy ||
|
||||
preview.visualForProperties(
|
||||
widget.clip.id,
|
||||
) ==
|
||||
null) {
|
||||
return;
|
||||
}
|
||||
unawaited(_align(preview, alignment));
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
]),
|
||||
],
|
||||
section([
|
||||
Text(
|
||||
context.l10n.position,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
axes(
|
||||
TransformChannel.position,
|
||||
number(
|
||||
'picture-x',
|
||||
'X',
|
||||
value.x * canvas.width,
|
||||
(c, v) => c.copyWith(x: v / canvas.width),
|
||||
),
|
||||
number(
|
||||
'picture-y',
|
||||
'Y',
|
||||
value.y * canvas.height,
|
||||
(c, v) => c.copyWith(y: v / canvas.height),
|
||||
),
|
||||
),
|
||||
keyTools(TransformChannel.position),
|
||||
]),
|
||||
section([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: number(
|
||||
'picture-rotation',
|
||||
context.l10n.rotation,
|
||||
value.rotation,
|
||||
(c, v) => c.copyWith(rotation: v),
|
||||
unit: '°',
|
||||
wrapRotation: true,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
keyButton(TransformChannel.rotation),
|
||||
],
|
||||
),
|
||||
keyTools(TransformChannel.rotation),
|
||||
]),
|
||||
section([
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.scale,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
key: const Key('picture-lock'),
|
||||
tooltip: context.l10n.keepAspectRatio,
|
||||
icon: const Icon(Icons.lock_open_outlined),
|
||||
selectedIcon: const Icon(Icons.lock_outline),
|
||||
isSelected: locked,
|
||||
onPressed: enabled
|
||||
? () {
|
||||
if (preview?.transforms.hasPending == true) return;
|
||||
preview?.setAspectRatioLocked(!locked);
|
||||
setState(() => _locked = !locked);
|
||||
}
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
axes(
|
||||
TransformChannel.scale,
|
||||
number(
|
||||
'picture-scale-x',
|
||||
'W',
|
||||
value.scale * 100,
|
||||
(c, v) => c.copyWith(
|
||||
scale: v / 100,
|
||||
scaleY: locked ? c.scaleY * v / 100 / c.scale : c.scaleY,
|
||||
),
|
||||
unit: '%',
|
||||
min: locked ? math.max(1.0, value.scale / value.scaleY) : 1,
|
||||
max: locked
|
||||
? math.min(10000.0, 10000 * value.scale / value.scaleY)
|
||||
: 10000,
|
||||
),
|
||||
number(
|
||||
'picture-scale-y',
|
||||
'H',
|
||||
value.scaleY * 100,
|
||||
(c, v) => c.copyWith(
|
||||
scaleY: v / 100,
|
||||
scale: locked ? c.scale * v / 100 / c.scaleY : c.scale,
|
||||
),
|
||||
unit: '%',
|
||||
min: locked ? math.max(1.0, value.scaleY / value.scale) : 1,
|
||||
max: locked
|
||||
? math.min(10000.0, 10000 * value.scaleY / value.scale)
|
||||
: 10000,
|
||||
),
|
||||
),
|
||||
keyTools(TransformChannel.scale),
|
||||
]),
|
||||
if (_error != null)
|
||||
section([
|
||||
Text(
|
||||
_error!,
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
]),
|
||||
],
|
||||
);
|
||||
// Canvas gestures own edits temporarily, without changing control colors.
|
||||
return ExcludeFocus(
|
||||
excluding: canvasDragging,
|
||||
child: IgnorePointer(ignoring: canvasDragging, child: content),
|
||||
);
|
||||
}
|
||||
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([
|
||||
widget.session.view(widget.sequence),
|
||||
if (preview != null) ...[preview, preview.transforms],
|
||||
]),
|
||||
builder: (_, _) => contents(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _KeyframeTimeline extends StatelessWidget {
|
||||
const _KeyframeTimeline({
|
||||
required this.animation,
|
||||
required this.enabled,
|
||||
required this.onSeek,
|
||||
});
|
||||
final ClipAnimation animation;
|
||||
final bool enabled;
|
||||
final ValueChanged<int> onSeek;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colors = Theme.of(context).colorScheme;
|
||||
final end = animation.lastTick;
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Text(
|
||||
context.l10n.keyframes,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
const Spacer(),
|
||||
Text(
|
||||
'${(animation.localTick / TimelineClock.ticksPerSecond).toStringAsFixed(2)} s',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
for (final channel in TransformChannel.values)
|
||||
SizedBox(
|
||||
height: 32,
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 36,
|
||||
child: Text(
|
||||
channel.label(context),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final extent = (constraints.maxWidth - 20).clamp(
|
||||
1.0,
|
||||
double.infinity,
|
||||
);
|
||||
double x(int tick) =>
|
||||
10 +
|
||||
(end == 0 ? 0 : (tick - animation.start) / end).clamp(
|
||||
0.0,
|
||||
1.0,
|
||||
) *
|
||||
extent;
|
||||
return GestureDetector(
|
||||
key: ValueKey('picture-key-track-${channel.name}'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onTapDown: !enabled
|
||||
? null
|
||||
: (details) {
|
||||
final fraction =
|
||||
((details.localPosition.dx - 10) / extent)
|
||||
.clamp(0.0, 1.0);
|
||||
final tick =
|
||||
((fraction * end / animation.frameTicks)
|
||||
.round() *
|
||||
animation.frameTicks)
|
||||
.clamp(0, end);
|
||||
onSeek(animation.start + tick);
|
||||
},
|
||||
child: Stack(
|
||||
children: [
|
||||
Positioned(
|
||||
left: 10,
|
||||
right: 10,
|
||||
top: 15,
|
||||
height: 1,
|
||||
child: ColoredBox(color: colors.outlineVariant),
|
||||
),
|
||||
if (animation.containsPlayhead)
|
||||
Positioned(
|
||||
left: x(animation.playhead),
|
||||
top: 3,
|
||||
bottom: 3,
|
||||
width: 1,
|
||||
child: ColoredBox(color: colors.primary),
|
||||
),
|
||||
for (final tick in animation.keyTimes(channel))
|
||||
Positioned(
|
||||
left: x(tick) - AppControlSize.compact / 2,
|
||||
top: 4,
|
||||
width: AppControlSize.compact,
|
||||
height: AppControlSize.compact,
|
||||
child: IconButton(
|
||||
key: ValueKey(
|
||||
'picture-key-marker-${channel.name}-$tick',
|
||||
),
|
||||
tooltip:
|
||||
'${channel.label(context)} ${((tick - animation.start) / TimelineClock.ticksPerSecond).toStringAsFixed(2)} s',
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: enabled
|
||||
? () => onSeek(tick)
|
||||
: null,
|
||||
icon: Transform.rotate(
|
||||
angle: math.pi / 4,
|
||||
child: Icon(
|
||||
Icons.square,
|
||||
size: 9,
|
||||
color: tick == animation.playhead
|
||||
? colors.primary
|
||||
: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/runtime/contracts.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'canvas_presets.dart';
|
||||
import 'project_settings_dialog.dart';
|
||||
|
||||
/// Project information uses the live editing session, including unsaved edits.
|
||||
class ProjectProperties extends StatelessWidget {
|
||||
const ProjectProperties({super.key, required this.session});
|
||||
|
||||
final EditorTimelineSession session;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final sequence = session.activeSequenceId;
|
||||
final timeline = sequence == null
|
||||
? null
|
||||
: session.persistence.timeline(sequence);
|
||||
final duration = sequence == null
|
||||
? 0
|
||||
: session.sequenceDurationTicks(sequence);
|
||||
final frame = timeline?.format.frameDuration;
|
||||
final fps = frame == null ? null : frame.denominator / frame.numerator;
|
||||
final canvas = session.canvas;
|
||||
String number(double value) => value == value.roundToDouble()
|
||||
? value.toStringAsFixed(0)
|
||||
: value.toStringAsFixed(3).replaceFirst(RegExp(r'0+$'), '');
|
||||
|
||||
return WorkspacePanel(
|
||||
paintBackground: false,
|
||||
title: context.l10n.projectProperties,
|
||||
trailing: TextButton(
|
||||
key: const ValueKey('project-settings-edit'),
|
||||
onPressed: () => showAppDialog<void>(
|
||||
context: context,
|
||||
builder: (_) => ProjectSettingsDialog(session: session),
|
||||
),
|
||||
child: Text(context.l10n.modify),
|
||||
),
|
||||
headerHeight: AppControlSize.panelToolbar,
|
||||
headerPadding: const EdgeInsets.symmetric(
|
||||
horizontal: AppSpacing.panelContentHorizontal,
|
||||
),
|
||||
showHeaderDivider: false,
|
||||
child: ScrollEdgeFadeBuilder(
|
||||
builder: (controller) => SingleChildScrollView(
|
||||
controller: controller,
|
||||
physics: const ClampingScrollPhysics(),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_Info(context.l10n.timelineName, session.document.name),
|
||||
_Info(
|
||||
context.l10n.canvasSize,
|
||||
'${number(canvas.width)} × ${number(canvas.height)} px',
|
||||
),
|
||||
_Info(context.l10n.canvasRatio, canvas.label(context)),
|
||||
_Info(
|
||||
context.l10n.projectColorSpace,
|
||||
switch (session.projectColorSpace) {
|
||||
RenderColorSpace.rec2020HLG => 'HDR · Rec.2020 HLG',
|
||||
RenderColorSpace.rec2020PQ => 'HDR · Rec.2020 PQ',
|
||||
_ => 'SDR · Rec.709',
|
||||
},
|
||||
),
|
||||
_Info(
|
||||
context.l10n.currentSequence,
|
||||
timeline?.name ?? context.l10n.none,
|
||||
),
|
||||
_Info(
|
||||
context.l10n.frameRate,
|
||||
fps == null ? '—' : '${number(fps)} fps',
|
||||
),
|
||||
_Info(
|
||||
context.l10n.totalDuration,
|
||||
'${(duration / TimelineClock.ticksPerSecond).toStringAsFixed(2)} ${context.l10n.seconds}',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Info extends StatelessWidget {
|
||||
const _Info(this.label, this.value);
|
||||
|
||||
final String label;
|
||||
final String value;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
spacing: AppSpacing.small,
|
||||
children: [
|
||||
Text(label, style: Theme.of(context).textTheme.bodySmall),
|
||||
Expanded(
|
||||
child: Text(
|
||||
value,
|
||||
textAlign: TextAlign.right,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/editor.dart';
|
||||
import 'package:cutdex_sdk/runtime/contracts.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
class ProjectSettingsDialog extends StatefulWidget {
|
||||
const ProjectSettingsDialog({super.key, required this.session});
|
||||
final EditorTimelineSession session;
|
||||
|
||||
@override
|
||||
State<ProjectSettingsDialog> createState() => _ProjectSettingsDialogState();
|
||||
}
|
||||
|
||||
class _ProjectSettingsDialogState extends State<ProjectSettingsDialog> {
|
||||
static final _rates = <String, RationalTime>{
|
||||
'23.976': RationalTime(1001, 24000),
|
||||
'24': RationalTime(1, 24),
|
||||
'25': RationalTime(1, 25),
|
||||
'29.97': RationalTime(1001, 30000),
|
||||
'30': RationalTime(1, 30),
|
||||
'50': RationalTime(1, 50),
|
||||
'59.94': RationalTime(1001, 60000),
|
||||
'60': RationalTime(1, 60),
|
||||
'120': RationalTime(1, 120),
|
||||
};
|
||||
static const _sizes = <String, (int, int)>{
|
||||
'1920 × 1080': (1920, 1080),
|
||||
'3840 × 2160': (3840, 2160),
|
||||
'1280 × 720': (1280, 720),
|
||||
'1080 × 1920': (1080, 1920),
|
||||
'1080 × 1080': (1080, 1080),
|
||||
};
|
||||
final _form = GlobalKey<FormState>();
|
||||
late final TextEditingController _width;
|
||||
late final TextEditingController _height;
|
||||
late RationalTime _frame;
|
||||
late RenderColorSpace _color;
|
||||
String? _preset;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final canvas = widget.session.canvas;
|
||||
_width = TextEditingController(text: canvas.width.toStringAsFixed(0));
|
||||
_height = TextEditingController(text: canvas.height.toStringAsFixed(0));
|
||||
_frame = widget.session.activeSequenceId == null
|
||||
? TimelineFormat.fps24.frameDuration
|
||||
: widget.session.persistence
|
||||
.timeline(widget.session.activeSequenceId!)
|
||||
.format
|
||||
.frameDuration;
|
||||
_color = widget.session.projectColorSpace;
|
||||
_preset = _sizes.entries
|
||||
.where((e) => e.value.$1 == canvas.width && e.value.$2 == canvas.height)
|
||||
.firstOrNull
|
||||
?.key;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_width.dispose();
|
||||
_height.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _save() {
|
||||
if (!_form.currentState!.validate()) return;
|
||||
widget.session.setProjectProperties(
|
||||
sequence: widget.session.activeSequenceId,
|
||||
canvas: ProjectCanvas(
|
||||
double.parse(_width.text),
|
||||
double.parse(_height.text),
|
||||
),
|
||||
frameDuration: _frame,
|
||||
colorSpace: _color,
|
||||
);
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Widget _dimension(
|
||||
TextEditingController controller,
|
||||
String label,
|
||||
String key,
|
||||
) => FormField<String>(
|
||||
initialValue: controller.text,
|
||||
validator: (_) {
|
||||
final value = int.tryParse(controller.text);
|
||||
return value == null || !ProjectCanvas.isValidDimension(value.toDouble())
|
||||
? context.l10n.projectResolutionInvalid
|
||||
: null;
|
||||
},
|
||||
builder: (field) => AppTextField(
|
||||
key: ValueKey(key),
|
||||
controller: controller,
|
||||
label: label,
|
||||
errorText: field.errorText,
|
||||
keyboardType: TextInputType.number,
|
||||
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
|
||||
onChanged: (value) {
|
||||
field.didChange(value);
|
||||
setState(() => _preset = null);
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final l10n = context.l10n;
|
||||
final rates = {..._rates};
|
||||
if (!rates.values.contains(_frame)) {
|
||||
rates[(_frame.denominator / _frame.numerator).toStringAsFixed(3)] =
|
||||
_frame;
|
||||
}
|
||||
return AppDialog(
|
||||
title: l10n.projectSettings,
|
||||
width: 440,
|
||||
description: l10n.projectSettingsDescription,
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: Text(l10n.cancel),
|
||||
),
|
||||
FilledButton(
|
||||
key: const ValueKey('project-settings-save'),
|
||||
onPressed: _save,
|
||||
child: Text(l10n.save),
|
||||
),
|
||||
],
|
||||
child: SingleChildScrollView(
|
||||
child: Form(
|
||||
key: _form,
|
||||
child: AppFieldGroup(
|
||||
children: [
|
||||
AppField(
|
||||
label: l10n.canvasSize,
|
||||
child: AppFieldGroup(
|
||||
children: [
|
||||
AppSelect<String>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
key: const ValueKey('project-resolution'),
|
||||
value: _preset ?? 'custom',
|
||||
label: l10n.canvasSize,
|
||||
options: [
|
||||
for (final name in _sizes.keys)
|
||||
AppSelectOption(name, name),
|
||||
AppSelectOption('custom', l10n.custom),
|
||||
],
|
||||
onChanged: (value) => setState(() {
|
||||
_preset = value == 'custom' ? null : value;
|
||||
final size = _sizes[value];
|
||||
if (size != null) {
|
||||
_width.text = '${size.$1}';
|
||||
_height.text = '${size.$2}';
|
||||
}
|
||||
}),
|
||||
),
|
||||
Row(
|
||||
spacing: AppSpacing.compact,
|
||||
children: [
|
||||
Expanded(
|
||||
child: _dimension(
|
||||
_width,
|
||||
l10n.projectWidth,
|
||||
'project-width',
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: _dimension(
|
||||
_height,
|
||||
l10n.projectHeight,
|
||||
'project-height',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
AppField(
|
||||
label: l10n.frameRate,
|
||||
child: AppSelect<RationalTime>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
key: const ValueKey('project-frame-rate'),
|
||||
value: _frame,
|
||||
label: l10n.frameRate,
|
||||
options: [
|
||||
for (final rate in rates.entries)
|
||||
AppSelectOption(rate.value, '${rate.key} fps'),
|
||||
],
|
||||
onChanged: (value) => setState(() => _frame = value),
|
||||
),
|
||||
),
|
||||
AppField(
|
||||
label: l10n.projectColorSpace,
|
||||
child: AppSelect<RenderColorSpace>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
key: const ValueKey('project-color-space'),
|
||||
value: _color,
|
||||
label: l10n.projectColorSpace,
|
||||
options: const [
|
||||
AppSelectOption(RenderColorSpace.rec709, 'SDR · Rec.709'),
|
||||
AppSelectOption(
|
||||
RenderColorSpace.rec2020HLG,
|
||||
'HDR · Rec.2020 HLG',
|
||||
),
|
||||
AppSelectOption(
|
||||
RenderColorSpace.rec2020PQ,
|
||||
'HDR · Rec.2020 PQ',
|
||||
),
|
||||
],
|
||||
onChanged: (value) => setState(() => _color = value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
|
||||
import 'properties_inspector_controller.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'audio_properties.dart';
|
||||
import 'caption_properties.dart';
|
||||
import 'color_interpretation_properties.dart';
|
||||
import 'mask_properties.dart';
|
||||
import 'picture_properties.dart';
|
||||
import 'project_properties.dart';
|
||||
import 'properties_presentation_state.dart';
|
||||
import 'speed_properties.dart';
|
||||
|
||||
export 'properties_presentation_state.dart';
|
||||
|
||||
typedef PropertyCategoryControls = Widget Function(
|
||||
BuildContext context,
|
||||
List<PropertyCategory> categories,
|
||||
PropertyCategory selected,
|
||||
ValueChanged<PropertyCategory> onSelected,
|
||||
);
|
||||
|
||||
class PropertiesContent extends ConsumerWidget {
|
||||
const PropertiesContent({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
required this.categoryControls,
|
||||
required this.categoryHeaderHeight,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
final PropertyCategoryControls categoryControls;
|
||||
final double categoryHeaderHeight;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final state = ref.watch(editorTimelineProvider(projectId, timelineId));
|
||||
final content = state.when(
|
||||
error: (_, _) => WorkspacePanel(
|
||||
paintBackground: false,
|
||||
child: _Message(context.l10n.loadClipPropertiesFailed),
|
||||
),
|
||||
data: (session) {
|
||||
final inspector = ref.watch(
|
||||
propertiesInspectorProvider((projectId, timelineId)),
|
||||
);
|
||||
if (inspector == null) return const SizedBox.shrink();
|
||||
return ListenableBuilder(
|
||||
listenable: inspector,
|
||||
builder: (context, _) => _selection(context, inspector, ref),
|
||||
);
|
||||
},
|
||||
loading: () => const WorkspacePanel(
|
||||
key: Key('properties-pending'),
|
||||
paintBackground: false,
|
||||
child: SizedBox.expand(),
|
||||
),
|
||||
);
|
||||
return Theme(
|
||||
data: AppTheme.propertiesPanelTheme(Theme.of(context)),
|
||||
child: content,
|
||||
);
|
||||
}
|
||||
|
||||
Widget _selection(
|
||||
BuildContext context,
|
||||
PropertiesInspectorController inspector,
|
||||
WidgetRef ref,
|
||||
) {
|
||||
final session = inspector.session;
|
||||
final sequence = inspector.sequence;
|
||||
final clips = inspector.selectedClips;
|
||||
if (sequence == null || clips.isEmpty) {
|
||||
return ProjectProperties(session: session);
|
||||
}
|
||||
if (clips.length > 1) {
|
||||
return WorkspacePanel(
|
||||
paintBackground: false,
|
||||
child: _Message(context.l10n.selectedClipsHint(clips.length)),
|
||||
);
|
||||
}
|
||||
final clip = clips.single;
|
||||
final payload = clip.payloadRef == null
|
||||
? null
|
||||
: session.payloadFor(clip.payloadRef!);
|
||||
final binding = clip.payloadRef == null
|
||||
? null
|
||||
: session.mediaBinding(clip.payloadRef!);
|
||||
final hasAudio = binding?.audioSelection != null;
|
||||
if (payload?.type == 'caption' || payload?.type == 'caption-role') {
|
||||
return CaptionProperties(
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clipId: clip.id.value,
|
||||
transformProperties: payload?.type == 'caption'
|
||||
? PictureProperties(
|
||||
key: ValueKey((sequence, clip.id, 'caption-transform')),
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
return _ClipProperties(
|
||||
key: ValueKey((sequence, clip.id)),
|
||||
categoryControls: categoryControls,
|
||||
categoryHeaderHeight: categoryHeaderHeight,
|
||||
category: ref.watch(
|
||||
propertyCategoryProvider((
|
||||
projectId,
|
||||
timelineId,
|
||||
'${sequence.value}/${clip.id.value}',
|
||||
)),
|
||||
),
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
mask: MaskProperties(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
element: clip.id,
|
||||
),
|
||||
speed: SpeedProperties(
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clip.id,
|
||||
),
|
||||
audio: AudioProperties(
|
||||
key: ValueKey((sequence, clip.id, 'audio')),
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
hasAudio: hasAudio,
|
||||
),
|
||||
picture: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
if (payload?.type == 'video' && binding?.videoTrackIndex != null)
|
||||
ColorInterpretationProperties(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
session: session,
|
||||
assetId: payload!.assetIds.single,
|
||||
trackIndex: binding!.videoTrackIndex!,
|
||||
),
|
||||
PictureProperties(
|
||||
key: ValueKey((sequence, clip.id)),
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
),
|
||||
],
|
||||
),
|
||||
animation: PictureProperties(
|
||||
key: ValueKey((sequence, clip.id, 'animation')),
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
session: session,
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
animationView: true,
|
||||
),
|
||||
type: payload?.type,
|
||||
hasAudio: hasAudio,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ClipProperties extends StatefulWidget {
|
||||
const _ClipProperties({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.sequence,
|
||||
required this.clip,
|
||||
required this.picture,
|
||||
required this.mask,
|
||||
required this.audio,
|
||||
required this.speed,
|
||||
required this.animation,
|
||||
required this.type,
|
||||
required this.hasAudio,
|
||||
required this.categoryControls,
|
||||
required this.categoryHeaderHeight,
|
||||
required this.category,
|
||||
});
|
||||
final EditorTimelineSession session;
|
||||
final SequenceId sequence;
|
||||
final ElementRecord clip;
|
||||
final Widget picture;
|
||||
final Widget mask;
|
||||
final Widget audio;
|
||||
final Widget speed;
|
||||
final Widget animation;
|
||||
final String? type;
|
||||
final bool hasAudio;
|
||||
final PropertyCategoryControls categoryControls;
|
||||
final double categoryHeaderHeight;
|
||||
final ValueNotifier<PropertyCategory?> category;
|
||||
@override
|
||||
State<_ClipProperties> createState() => _ClipPropertiesState();
|
||||
}
|
||||
|
||||
class _ClipPropertiesState extends State<_ClipProperties> {
|
||||
PropertyCategory get _selected {
|
||||
final categories = categoriesForClip(widget.clip, widget.type);
|
||||
return categories.contains(widget.category.value)
|
||||
? widget.category.value!
|
||||
: categories.first;
|
||||
}
|
||||
|
||||
void _selectCategory(PropertyCategory category) =>
|
||||
widget.category.value = category;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => ListenableBuilder(
|
||||
listenable: widget.category,
|
||||
builder: (context, _) => _buildProperties(context),
|
||||
);
|
||||
|
||||
Widget _buildProperties(BuildContext context) {
|
||||
final clip = widget.clip;
|
||||
return WorkspacePanel(
|
||||
paintBackground: false,
|
||||
headerHeight: widget.categoryHeaderHeight,
|
||||
headerPadding: EdgeInsets.zero,
|
||||
showHeaderDivider: false,
|
||||
controls: widget.categoryControls(
|
||||
context,
|
||||
categoriesForClip(clip, widget.type),
|
||||
_selected,
|
||||
_selectCategory,
|
||||
),
|
||||
child: ScrollEdgeFadeBuilder(
|
||||
key: PageStorageKey((clip.id, _selected)),
|
||||
builder: (controller) => SingleChildScrollView(
|
||||
controller: controller,
|
||||
// Inspector controls stop at their bounds; macOS's default elastic
|
||||
// physics repeatedly displaces the content during edge scrolling.
|
||||
physics: const ClampingScrollPhysics(),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
...switch (_selected) {
|
||||
PropertyCategory.picture => [widget.picture],
|
||||
PropertyCategory.mask => [widget.mask],
|
||||
PropertyCategory.audio => [widget.audio],
|
||||
PropertyCategory.speed => [widget.speed],
|
||||
PropertyCategory.animation => [widget.animation],
|
||||
PropertyCategory.basic => [
|
||||
_Property(context.l10n.type, switch (clip.structure) {
|
||||
ElementStructure.gap => context.l10n.gap,
|
||||
ElementStructure.container => context.l10n.compoundClip,
|
||||
ElementStructure.content =>
|
||||
widget.type ?? context.l10n.unboundMedia,
|
||||
}),
|
||||
_Property(
|
||||
context.l10n.status,
|
||||
clip.enabled ? context.l10n.enable : context.l10n.disable,
|
||||
),
|
||||
],
|
||||
},
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _Property extends StatelessWidget {
|
||||
const _Property(this.label, this.value);
|
||||
final String label;
|
||||
final String value;
|
||||
@override
|
||||
Widget build(BuildContext context) => Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
spacing: AppSpacing.small,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
value,
|
||||
textAlign: TextAlign.right,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _Message extends StatelessWidget {
|
||||
const _Message(this.text);
|
||||
final String text;
|
||||
@override
|
||||
Widget build(BuildContext context) => Center(
|
||||
child: Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Text(
|
||||
text,
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'properties_content.dart';
|
||||
|
||||
class PropertiesEditorPage extends StatelessWidget {
|
||||
const PropertiesEditorPage({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
@override
|
||||
Widget build(BuildContext context) => PropertiesContent(
|
||||
key: const Key('properties-editor-page'),
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
categoryHeaderHeight: 48,
|
||||
categoryControls: (context, categories, selected, onSelected) => Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: DropdownButton<PropertyCategory>(
|
||||
key: const Key('property-category-picker'),
|
||||
isExpanded: true,
|
||||
underline: const SizedBox.shrink(),
|
||||
value: selected,
|
||||
items: [
|
||||
for (final category in categories)
|
||||
DropdownMenuItem(
|
||||
value: category,
|
||||
child: Text(category.label(context)),
|
||||
),
|
||||
],
|
||||
onChanged: (category) {
|
||||
if (category != null) onSelected(category);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class PropertiesToolPanel extends StatelessWidget {
|
||||
const PropertiesToolPanel({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
@override
|
||||
Widget build(BuildContext context) => PropertiesContent(
|
||||
key: const Key('properties-tool-panel'),
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
categoryHeaderHeight: 48,
|
||||
categoryControls: (context, categories, selected, onSelected) =>
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
for (final category in categories)
|
||||
TextButton(
|
||||
key: ValueKey('property-tab-${category.name}'),
|
||||
style: TextButton.styleFrom(
|
||||
minimumSize: const Size(64, 48),
|
||||
foregroundColor: selected == category
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
onPressed: () => onSelected(category),
|
||||
child: Text(category.label(context)),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import 'package:cutdex_sdk/timeline/engine.dart';
|
||||
import 'package:cutdex_sdk/timeline/layout.dart';
|
||||
import 'package:cutdex_sdk/timeline/model.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../workspace/timeline_provider.dart';
|
||||
import '../../workspace/timeline_session.dart';
|
||||
import 'properties_presentation_state.dart';
|
||||
|
||||
final propertiesInspectorProvider = Provider.autoDispose
|
||||
.family<PropertiesInspectorController?, (String, String)>((ref, identity) {
|
||||
final session = ref
|
||||
.watch(editorTimelineProvider(identity.$1, identity.$2))
|
||||
.value;
|
||||
if (session == null) return null;
|
||||
final controller = PropertiesInspectorController(session);
|
||||
ref.onDispose(controller.dispose);
|
||||
return controller;
|
||||
});
|
||||
|
||||
/// Resolves the shared editing selection without prescribing a device layout.
|
||||
class PropertiesInspectorController extends ChangeNotifier {
|
||||
PropertiesInspectorController(this.session) {
|
||||
session.addListener(_sessionChanged);
|
||||
_bindView();
|
||||
}
|
||||
final EditorTimelineSession session;
|
||||
Listenable? _editingChanges;
|
||||
SequenceId? get sequence => session.activeSequenceId;
|
||||
|
||||
void _bindView() {
|
||||
final id = sequence;
|
||||
final next = id == null ? null : session.view(id).editingChanges;
|
||||
if (identical(next, _editingChanges)) return;
|
||||
_editingChanges?.removeListener(notifyListeners);
|
||||
_editingChanges = next;
|
||||
_editingChanges?.addListener(notifyListeners);
|
||||
}
|
||||
|
||||
void _sessionChanged() {
|
||||
_bindView();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
List<ElementRecord> get selectedClips {
|
||||
final id = sequence;
|
||||
if (id == null) return const [];
|
||||
final view = session.view(id);
|
||||
final query = view.version.kernelVersion.query();
|
||||
final handles = <ElementHandle>{};
|
||||
for (final identity in view.selectedIdentities) {
|
||||
final handle = switch (identity) {
|
||||
ElementHandle handle => handle,
|
||||
LayoutBodyId body => view.elementForIdentity(body),
|
||||
_ => null,
|
||||
};
|
||||
if (handle != null && query.ownerOf(handle) != null) handles.add(handle);
|
||||
}
|
||||
final clips = [for (final handle in handles) query.element(handle)];
|
||||
return clips.any((clip) => clip.structure != ElementStructure.gap)
|
||||
? clips
|
||||
: const [];
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
session.removeListener(_sessionChanged);
|
||||
_editingChanges?.removeListener(notifyListeners);
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
List<PropertyCategory> categoriesForClip(ElementRecord clip, String? type) {
|
||||
if (clip.structure != ElementStructure.content) {
|
||||
return [PropertyCategory.basic];
|
||||
}
|
||||
return switch (type) {
|
||||
'video' => [
|
||||
PropertyCategory.picture,
|
||||
PropertyCategory.mask,
|
||||
PropertyCategory.audio,
|
||||
PropertyCategory.speed,
|
||||
PropertyCategory.animation,
|
||||
],
|
||||
'audio' => [PropertyCategory.audio, PropertyCategory.speed],
|
||||
'image' => [
|
||||
PropertyCategory.picture,
|
||||
PropertyCategory.mask,
|
||||
PropertyCategory.animation,
|
||||
],
|
||||
_ => [PropertyCategory.basic],
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import 'properties_content.dart';
|
||||
export 'properties_presentation_state.dart';
|
||||
|
||||
/// Desktop inspector uses compact category tabs over shared property editors.
|
||||
class EditorPropertiesPanel extends StatelessWidget {
|
||||
const EditorPropertiesPanel({
|
||||
super.key,
|
||||
required this.projectId,
|
||||
required this.timelineId,
|
||||
});
|
||||
final String projectId;
|
||||
final String timelineId;
|
||||
@override
|
||||
Widget build(BuildContext context) => PropertiesContent(
|
||||
projectId: projectId,
|
||||
timelineId: timelineId,
|
||||
categoryHeaderHeight: CompactPanelTabs.height,
|
||||
categoryControls: (context, categories, selected, onSelected) =>
|
||||
CompactPanelTabs<PropertyCategory>(
|
||||
values: categories,
|
||||
selected: selected,
|
||||
labelBuilder: (category) => category.label(context),
|
||||
tabKeyBuilder: (category) =>
|
||||
ValueKey('property-tab-${category.name}'),
|
||||
onSelected: onSelected,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
final propertyCategoryProvider =
|
||||
Provider.family<ValueNotifier<PropertyCategory?>, (String, String, String)>(
|
||||
(ref, identity) {
|
||||
final category = ValueNotifier<PropertyCategory?>(null);
|
||||
ref.onDispose(category.dispose);
|
||||
return category;
|
||||
},
|
||||
);
|
||||
|
||||
enum PropertyCategory {
|
||||
picture,
|
||||
mask,
|
||||
audio,
|
||||
speed,
|
||||
animation,
|
||||
basic;
|
||||
|
||||
String label(BuildContext context) => switch (this) {
|
||||
picture => context.l10n.pictureProperties,
|
||||
mask => context.l10n.mask,
|
||||
audio => context.l10n.audio,
|
||||
speed => context.l10n.speedChange,
|
||||
animation => context.l10n.animation,
|
||||
basic => context.l10n.basic,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,152 @@
|
||||
import 'package:cutdex/l10n/l10n.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
class PropertyNumberInput extends StatefulWidget {
|
||||
const PropertyNumberInput({
|
||||
super.key,
|
||||
required this.label,
|
||||
required this.value,
|
||||
required this.enabled,
|
||||
required this.readOnly,
|
||||
required this.submit,
|
||||
this.unit,
|
||||
this.decimalPlaces = 2,
|
||||
this.onScrubStart,
|
||||
required this.onScrubUpdate,
|
||||
required this.onScrubEnd,
|
||||
required this.onScrubCancel,
|
||||
required this.scrubbing,
|
||||
required this.editContext,
|
||||
}) : assert(decimalPlaces >= 0 && decimalPlaces <= 20);
|
||||
final String? label;
|
||||
final String? unit;
|
||||
final int decimalPlaces;
|
||||
final bool Function()? onScrubStart;
|
||||
final ValueChanged<double> onScrubUpdate;
|
||||
final VoidCallback onScrubEnd;
|
||||
final VoidCallback onScrubCancel;
|
||||
final bool scrubbing;
|
||||
final Object editContext;
|
||||
final double value;
|
||||
final bool enabled;
|
||||
final bool readOnly;
|
||||
final Future<bool> Function(double) submit;
|
||||
@override
|
||||
State<PropertyNumberInput> createState() => _PropertyNumberInputState();
|
||||
}
|
||||
|
||||
class _PropertyNumberInputState extends State<PropertyNumberInput> {
|
||||
late final _text = TextEditingController(text: _format(widget.value));
|
||||
final _focus = FocusNode();
|
||||
bool _dirty = false;
|
||||
String? _error;
|
||||
String _format(double value) {
|
||||
var text = value.toStringAsFixed(widget.decimalPlaces);
|
||||
if (text.contains('.')) text = text.replaceFirst(RegExp(r'\.?0+$'), '');
|
||||
return text == '-0' ? '0' : text;
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_focus.addListener(_blur);
|
||||
}
|
||||
|
||||
void _blur() {
|
||||
if (!_focus.hasFocus) _submit();
|
||||
}
|
||||
|
||||
Future<void> _submit() async {
|
||||
if (!_dirty || !widget.enabled || widget.readOnly) return;
|
||||
final value = double.tryParse(_text.text);
|
||||
if (value == null || !value.isFinite) {
|
||||
setState(() => _error = context.l10n.invalidNumber);
|
||||
return;
|
||||
}
|
||||
_dirty = false;
|
||||
final accepted = await widget.submit(value);
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_error = accepted ? null : context.l10n.notApplied;
|
||||
_text.text = _format(widget.value);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant PropertyNumberInput oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if ((oldWidget.enabled && !widget.enabled) ||
|
||||
oldWidget.editContext != widget.editContext ||
|
||||
(!oldWidget.readOnly && widget.readOnly)) {
|
||||
_dirty = false;
|
||||
_error = null;
|
||||
}
|
||||
final text = _format(widget.value);
|
||||
// A no-op assignment still resets selection and asks EditableText to
|
||||
// reveal its caret, competing with the user's scroll on preview updates.
|
||||
if (!_dirty && _text.text != text) _text.text = text;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_focus.removeListener(_blur);
|
||||
_focus.dispose();
|
||||
_text.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Focus(
|
||||
onKeyEvent: (_, event) {
|
||||
if (event is KeyDownEvent &&
|
||||
event.logicalKey == LogicalKeyboardKey.escape) {
|
||||
setState(() {
|
||||
_dirty = false;
|
||||
_error = null;
|
||||
_text.text = _format(widget.value);
|
||||
});
|
||||
_focus.unfocus();
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
},
|
||||
child: AppTextField(
|
||||
controller: _text,
|
||||
focusNode: _focus,
|
||||
enabled: widget.enabled,
|
||||
readOnly: widget.readOnly,
|
||||
canRequestFocus: widget.enabled && !widget.readOnly,
|
||||
keyboardType: const TextInputType.numberWithOptions(
|
||||
decimal: true,
|
||||
signed: true,
|
||||
),
|
||||
label: widget.label,
|
||||
leading: widget.onScrubStart == null
|
||||
? null
|
||||
: AppScrubLabel(
|
||||
label: widget.label!,
|
||||
enabled: widget.enabled && (!widget.readOnly || widget.scrubbing),
|
||||
onStart: () {
|
||||
_dirty = false;
|
||||
_error = null;
|
||||
_text.text = _format(widget.value);
|
||||
return widget.onScrubStart!();
|
||||
},
|
||||
onUpdate: widget.onScrubUpdate,
|
||||
onEnd: widget.onScrubEnd,
|
||||
onCancel: widget.onScrubCancel,
|
||||
),
|
||||
unit: widget.unit,
|
||||
errorText: _error,
|
||||
onChanged: (_) {
|
||||
_dirty = true;
|
||||
if (_error != null) setState(() => _error = null);
|
||||
},
|
||||
onEditingComplete: () {},
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
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:flutter/material.dart';
|
||||
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import '../../workspace/timeline_session.dart';
|
||||
|
||||
class SpeedProperties extends StatefulWidget {
|
||||
const SpeedProperties({
|
||||
super.key,
|
||||
required this.session,
|
||||
required this.sequence,
|
||||
required this.clip,
|
||||
});
|
||||
final EditorTimelineSession session;
|
||||
final SequenceId sequence;
|
||||
final ElementId clip;
|
||||
|
||||
@override
|
||||
State<SpeedProperties> createState() => _SpeedPropertiesState();
|
||||
}
|
||||
|
||||
class _SpeedPropertiesState extends State<SpeedProperties> {
|
||||
double? _timeline;
|
||||
TimelineVersion? _version;
|
||||
LayoutConnectionEditPreview? _preview;
|
||||
double? _previewSpeed;
|
||||
(Object, StackTrace)? _previewFailure;
|
||||
|
||||
double _speed(double position) =>
|
||||
(math.pow(10, position * 3 - 1).toDouble() * 100).round() / 100;
|
||||
|
||||
void _updatePreview(double speed) {
|
||||
final view = widget.session.view(widget.sequence);
|
||||
_preview?.cancel();
|
||||
_preview = null;
|
||||
_previewSpeed = null;
|
||||
_previewFailure = null;
|
||||
try {
|
||||
final preview = widget.session.previewClipSpeed(
|
||||
widget.sequence,
|
||||
widget.clip,
|
||||
speed,
|
||||
);
|
||||
_preview = preview;
|
||||
_previewSpeed = preview == null ? null : speed;
|
||||
if (preview == null) {
|
||||
view.clearLayoutPreview();
|
||||
} else {
|
||||
view.showLayoutPreview(preview.result.version);
|
||||
}
|
||||
} catch (error, stack) {
|
||||
_previewFailure = (error, stack);
|
||||
view.clearLayoutPreview();
|
||||
_showError(error);
|
||||
}
|
||||
}
|
||||
|
||||
void _commit(double speed) {
|
||||
final view = widget.session.view(widget.sequence);
|
||||
if (widget.session.activeSequenceId == widget.sequence &&
|
||||
(_version == null || identical(_version, view.version.kernelVersion))) {
|
||||
try {
|
||||
widget.session.runEdit(
|
||||
'setSpeed',
|
||||
widget.sequence,
|
||||
() {
|
||||
if (_previewSpeed != speed) _updatePreview(speed);
|
||||
final preview = _preview;
|
||||
final failure = _previewFailure;
|
||||
_preview = null;
|
||||
_previewSpeed = null;
|
||||
_previewFailure = null;
|
||||
if (preview == null) {
|
||||
view.clearLayoutPreview();
|
||||
if (failure != null) {
|
||||
widget.session.reportEditFailure(failure.$1, failure.$2);
|
||||
}
|
||||
} else {
|
||||
widget.session.commitClipSpeedPreview(widget.sequence, preview);
|
||||
}
|
||||
},
|
||||
context: {
|
||||
'clipIds': [widget.clip.value],
|
||||
'entryPoint': 'property',
|
||||
'playheadTick': view.playheadTick,
|
||||
},
|
||||
);
|
||||
} catch (error) {
|
||||
_preview?.cancel();
|
||||
_preview = null;
|
||||
_previewSpeed = null;
|
||||
view.clearLayoutPreview();
|
||||
_showError(error);
|
||||
}
|
||||
} else {
|
||||
_discardPreview();
|
||||
}
|
||||
setState(() {
|
||||
_timeline = null;
|
||||
_version = null;
|
||||
});
|
||||
}
|
||||
|
||||
void _discardPreview() {
|
||||
_preview?.cancel();
|
||||
_preview = null;
|
||||
_previewSpeed = null;
|
||||
_previewFailure = null;
|
||||
widget.session.view(widget.sequence).clearLayoutPreview();
|
||||
}
|
||||
|
||||
void _showError(Object error) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error))));
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_discardPreview();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final view = widget.session.view(widget.sequence);
|
||||
return ListenableBuilder(
|
||||
listenable: Listenable.merge([view, widget.session]),
|
||||
builder: (context, _) {
|
||||
final query = view.version.kernelVersion.query();
|
||||
final handle = query.elementById(widget.clip);
|
||||
final record = handle == null ? null : query.element(handle);
|
||||
final segments = record == null
|
||||
? null
|
||||
: widget.session.clipSpeedSegments(record);
|
||||
final saved = segments?.length == 1 ? segments!.single.speed : null;
|
||||
final enabled =
|
||||
saved != null && widget.session.acceptsEdits && !view.isDragging;
|
||||
final canReset =
|
||||
segments != null && widget.session.acceptsEdits && !view.isDragging;
|
||||
final localPlayhead = handle == null
|
||||
? 0
|
||||
: view.playheadTick - query.absoluteStart(handle);
|
||||
final custom = widget.session.isCustomSpeedEnabled(
|
||||
widget.sequence,
|
||||
widget.clip,
|
||||
);
|
||||
final canSplit =
|
||||
custom &&
|
||||
segments != null &&
|
||||
localPlayhead > 0 &&
|
||||
localPlayhead < (record?.duration ?? 0) &&
|
||||
!segments.any((segment) => segment.projectStart == localPlayhead) &&
|
||||
widget.session.acceptsEdits &&
|
||||
!view.isDragging;
|
||||
final value =
|
||||
_version == null || identical(_version, view.version.kernelVersion)
|
||||
? _timeline ?? saved ?? 1
|
||||
: saved ?? 1;
|
||||
return Padding(
|
||||
padding: AppSpacing.panelSection,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.speed,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
saved == null && segments != null
|
||||
? context.l10n.segmentedSpeed
|
||||
: '${value.toStringAsFixed(2)}×',
|
||||
key: const Key('clip-speed-value'),
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: AppSpacing.small),
|
||||
TextButton(
|
||||
onPressed: canReset
|
||||
? () {
|
||||
_version = null;
|
||||
_commit(1);
|
||||
}
|
||||
: null,
|
||||
child: const Text('1×'),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (saved != null) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
AppSlider(
|
||||
key: const Key('clip-speed-slider'),
|
||||
value: ((math.log(value.clamp(0.1, 100)) / math.ln10 + 1) / 3)
|
||||
.clamp(0, 1),
|
||||
semanticFormatterCallback: (position) =>
|
||||
'${_speed(position).toStringAsFixed(2)}×',
|
||||
onChangeStart: enabled
|
||||
? (_) {
|
||||
_discardPreview();
|
||||
_version = view.version.kernelVersion;
|
||||
}
|
||||
: null,
|
||||
onChanged: enabled
|
||||
? (position) {
|
||||
if (_version != null &&
|
||||
!identical(
|
||||
_version,
|
||||
view.version.kernelVersion,
|
||||
)) {
|
||||
_discardPreview();
|
||||
setState(() => _timeline = null);
|
||||
return;
|
||||
}
|
||||
final speed = _speed(position);
|
||||
setState(() => _timeline = speed);
|
||||
_updatePreview(speed);
|
||||
}
|
||||
: null,
|
||||
onChangeEnd: enabled
|
||||
? (position) => _commit(_speed(position))
|
||||
: null,
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('0.1×', style: Theme.of(context).textTheme.bodySmall),
|
||||
Text('100×', style: Theme.of(context).textTheme.bodySmall),
|
||||
],
|
||||
),
|
||||
] else if (segments != null)
|
||||
Text(
|
||||
context.l10n.speedSegmentCount(segments.length),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
context.l10n.custom,
|
||||
style: AppTheme.propertySectionTitleStyle(context),
|
||||
),
|
||||
),
|
||||
AppSwitch(
|
||||
key: const Key('clip-custom-speed-toggle'),
|
||||
value: custom,
|
||||
semanticLabel: context.l10n.custom,
|
||||
onChanged: canReset
|
||||
? (value) {
|
||||
_discardPreview();
|
||||
setState(() {
|
||||
_timeline = null;
|
||||
_version = null;
|
||||
});
|
||||
widget.session.setCustomSpeedEnabled(
|
||||
widget.sequence,
|
||||
widget.clip,
|
||||
value,
|
||||
);
|
||||
}
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
height: AppControlSize.propertyControl,
|
||||
child: OutlinedButton.icon(
|
||||
key: const Key('split-speed-segment'),
|
||||
onPressed: canSplit
|
||||
? () {
|
||||
try {
|
||||
widget.session.splitClipSpeedAt(
|
||||
widget.sequence,
|
||||
widget.clip,
|
||||
localPlayhead,
|
||||
);
|
||||
} catch (error) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(context.l10n.errorMessage(error)),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
: null,
|
||||
icon: const Icon(Icons.content_cut),
|
||||
label: Text(context.l10n.splitSpeedAtPlayhead),
|
||||
),
|
||||
),
|
||||
if (segments == null)
|
||||
Text(
|
||||
context.l10n.speedNotAvailable,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,760 @@
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../integrations/agent/agent_settings.dart';
|
||||
import '../../integrations/agent/agent_models.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
|
||||
import 'package:cutdex_ui/theme.dart';
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
|
||||
import 'settings_layout.dart';
|
||||
import '../../settings/settings_operation.dart';
|
||||
|
||||
part 'agent_settings_panel.freezed.dart';
|
||||
|
||||
class AgentSettingsPanel extends ConsumerStatefulWidget {
|
||||
const AgentSettingsPanel({super.key, this.contentPadding = EdgeInsets.zero});
|
||||
|
||||
final EdgeInsets contentPadding;
|
||||
|
||||
@override
|
||||
ConsumerState<AgentSettingsPanel> createState() => _AgentSettingsPanelState();
|
||||
}
|
||||
|
||||
class _AgentSettingsPanelState extends ConsumerState<AgentSettingsPanel>
|
||||
with SingleTickerProviderStateMixin {
|
||||
late final AnimationController _pageFade = AnimationController(
|
||||
vsync: this,
|
||||
duration: const Duration(milliseconds: 140),
|
||||
value: 1,
|
||||
);
|
||||
bool _showingProviderEditor = false;
|
||||
AgentProviderSettings? _editingProvider;
|
||||
bool _transitioning = false;
|
||||
bool get _saving =>
|
||||
ref.read(settingsOperationProvider('agent-save')).isLoading;
|
||||
final _scroll = ScrollController();
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pageFade.dispose();
|
||||
_scroll.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _showProviderForm(
|
||||
bool adding, {
|
||||
AgentProviderSettings? provider,
|
||||
}) async {
|
||||
if (_transitioning || _saving || _showingProviderEditor == adding) return;
|
||||
setState(() => _transitioning = true);
|
||||
await _pageFade.reverse();
|
||||
if (!mounted) return;
|
||||
if (_scroll.hasClients) _scroll.jumpTo(0);
|
||||
setState(() {
|
||||
_showingProviderEditor = adding;
|
||||
_editingProvider = adding ? provider : null;
|
||||
});
|
||||
await _pageFade.forward();
|
||||
if (mounted) setState(() => _transitioning = false);
|
||||
}
|
||||
|
||||
Future<void> _saveProvider(_ProviderFormValue result) async {
|
||||
if (_saving) return;
|
||||
final saved = await ref
|
||||
.read(settingsOperationProvider('agent-save').notifier)
|
||||
.run(
|
||||
() => ref
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.upsertProvider(
|
||||
id: _editingProvider?.id,
|
||||
name: result.name,
|
||||
apiType: result.apiType,
|
||||
baseUrl: result.baseUrl,
|
||||
models: result.models,
|
||||
apiKey: result.apiKey,
|
||||
clearApiKey: result.clearApiKey,
|
||||
),
|
||||
);
|
||||
if (!mounted) return;
|
||||
if (saved) {
|
||||
await _showProviderForm(false);
|
||||
} else {
|
||||
_showSaveError();
|
||||
}
|
||||
}
|
||||
|
||||
void _showSaveError() => ScaffoldMessenger.of(
|
||||
context,
|
||||
).showSnackBar(SnackBar(content: Text(context.l10n.agentSaveSettingsFailed)));
|
||||
|
||||
Future<void> _setProviderEnabled(
|
||||
AgentProviderSettings provider,
|
||||
bool enabled,
|
||||
) async {
|
||||
if (_transitioning) return;
|
||||
final operation = settingsOperationProvider('agent-enable-${provider.id}');
|
||||
if (ref.read(operation).isLoading) return;
|
||||
final saved = await ref
|
||||
.read(operation.notifier)
|
||||
.run(
|
||||
() => ref
|
||||
.read(agentSettingsProvider.notifier)
|
||||
.setProviderEnabled(provider.id, enabled),
|
||||
);
|
||||
if (!saved && mounted) _showSaveError();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Theme(
|
||||
data: AppTheme.settingsContentTheme(Theme.of(context)),
|
||||
child: Builder(builder: _buildContent),
|
||||
);
|
||||
|
||||
Widget _buildContent(BuildContext context) {
|
||||
ref.watch(settingsOperationProvider('agent-save'));
|
||||
final settings = ref.watch(agentSettingsProvider);
|
||||
return ScrollConfiguration(
|
||||
behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),
|
||||
child: Scrollbar(
|
||||
controller: _scroll,
|
||||
thumbVisibility: true,
|
||||
child: SingleChildScrollView(
|
||||
key: const Key('agent-settings-scroll'),
|
||||
controller: _scroll,
|
||||
primary: false,
|
||||
padding: widget.contentPadding,
|
||||
physics: const ClampingScrollPhysics(),
|
||||
child: FadeTransition(
|
||||
key: const Key('agent-provider-page-transition'),
|
||||
opacity: _pageFade,
|
||||
child: IgnorePointer(
|
||||
ignoring: _transitioning,
|
||||
child: _showingProviderEditor
|
||||
? _ProviderEditor(
|
||||
key: const Key('agent-provider-editor'),
|
||||
saving: _saving,
|
||||
provider: _editingProvider,
|
||||
onBack: () => _showProviderForm(false),
|
||||
onSave: _saveProvider,
|
||||
)
|
||||
: SettingsPageSection(
|
||||
key: const Key('agent-provider-list'),
|
||||
title: context.l10n.agentSettings,
|
||||
icon: Icons.auto_awesome_outlined,
|
||||
action: OutlinedButton.icon(
|
||||
onPressed: settings.asData == null
|
||||
? null
|
||||
: () => _showProviderForm(true),
|
||||
icon: const Icon(Icons.add),
|
||||
label: Text(context.l10n.agentAddProvider),
|
||||
),
|
||||
children: [
|
||||
for (final provider
|
||||
in settings.asData?.value.providers ??
|
||||
const <AgentProviderSettings>[])
|
||||
_ProviderCard(
|
||||
key: ValueKey('agent-provider-${provider.id}'),
|
||||
provider: provider,
|
||||
onEdit: () =>
|
||||
_showProviderForm(true, provider: provider),
|
||||
onEnabledChanged: (value) =>
|
||||
_setProviderEnabled(provider, value),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProviderCard extends StatelessWidget {
|
||||
const _ProviderCard({
|
||||
super.key,
|
||||
required this.provider,
|
||||
required this.onEdit,
|
||||
required this.onEnabledChanged,
|
||||
});
|
||||
|
||||
final AgentProviderSettings provider;
|
||||
final VoidCallback onEdit;
|
||||
final ValueChanged<bool> onEnabledChanged;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colors = theme.colorScheme;
|
||||
final icon = switch (provider.apiType) {
|
||||
'anthropicMessages' => Icons.auto_awesome_outlined,
|
||||
'openAiResponses' => Icons.bolt_outlined,
|
||||
_ => Icons.forum_outlined,
|
||||
};
|
||||
return Container(
|
||||
padding: EdgeInsets.zero,
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: AppIconSize.header, color: colors.onSurfaceVariant),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
provider.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
provider.models.map((model) => model.id).join(' · '),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colors.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
IconButton(
|
||||
key: ValueKey('agent-provider-edit-${provider.id}'),
|
||||
tooltip: context.l10n.agentEditProvider,
|
||||
onPressed: onEdit,
|
||||
icon: const Icon(Icons.edit_outlined, size: AppIconSize.header),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
AppSwitch(
|
||||
key: ValueKey('agent-provider-enabled-${provider.id}'),
|
||||
value: provider.enabled,
|
||||
semanticLabel: context.l10n.agentEnableProvider,
|
||||
onChanged: onEnabledChanged,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
TextStyle _providerInputStyle(BuildContext context) =>
|
||||
Theme.of(context).textTheme.bodyMedium!;
|
||||
|
||||
InputDecoration _providerInputDecoration(
|
||||
BuildContext context, {
|
||||
String? hintText,
|
||||
}) => InputDecoration(
|
||||
hintText: hintText,
|
||||
hintStyle: _providerInputStyle(context)
|
||||
.copyWith(color: Theme.of(context).colorScheme.onSurfaceVariant),
|
||||
);
|
||||
|
||||
class _ProviderEditor extends StatefulWidget {
|
||||
const _ProviderEditor({
|
||||
super.key,
|
||||
required this.onBack,
|
||||
required this.onSave,
|
||||
required this.saving,
|
||||
this.provider,
|
||||
});
|
||||
|
||||
final VoidCallback onBack;
|
||||
final ValueChanged<_ProviderFormValue> onSave;
|
||||
final bool saving;
|
||||
final AgentProviderSettings? provider;
|
||||
|
||||
@override
|
||||
State<_ProviderEditor> createState() => _ProviderEditorState();
|
||||
}
|
||||
|
||||
class _ProviderEditorState extends State<_ProviderEditor> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
late final TextEditingController _name;
|
||||
late final TextEditingController _baseUrl;
|
||||
late final TextEditingController _apiKey;
|
||||
late List<_ModelControllers> _models;
|
||||
AgentApiType _apiType = AgentApiType.openAiChatCompletions;
|
||||
String? _formError;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
final provider = widget.provider;
|
||||
_name = TextEditingController(text: provider?.name);
|
||||
_baseUrl = TextEditingController(text: provider?.baseUrl);
|
||||
_apiKey = TextEditingController();
|
||||
_apiType =
|
||||
AgentApiType.values
|
||||
.where((type) => type.name == provider?.apiType)
|
||||
.firstOrNull ??
|
||||
AgentApiType.openAiChatCompletions;
|
||||
_models = provider == null || provider.models.isEmpty
|
||||
? [_ModelControllers()]
|
||||
: [for (final model in provider.models) _ModelControllers(model)];
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_name.dispose();
|
||||
_baseUrl.dispose();
|
||||
_apiKey.dispose();
|
||||
for (final model in _models) {
|
||||
model.dispose();
|
||||
}
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _submit() {
|
||||
if (!_formKey.currentState!.validate()) return;
|
||||
final modelIds = _models.map((model) => model.id.text.trim()).toList();
|
||||
if (modelIds.toSet().length != modelIds.length) {
|
||||
setState(() => _formError = context.l10n.agentModelIdsUnique);
|
||||
return;
|
||||
}
|
||||
widget.onSave(
|
||||
_ProviderFormValue(
|
||||
name: _name.text.trim(),
|
||||
apiType: _apiType,
|
||||
baseUrl: _baseUrl.text.trim(),
|
||||
apiKey: _apiKey.text.isEmpty ? null : _apiKey.text,
|
||||
clearApiKey: false,
|
||||
models: [for (final model in _models) model.toData()],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
TextButton.icon(
|
||||
key: const Key('agent-provider-back'),
|
||||
onPressed: widget.saving ? null : widget.onBack,
|
||||
icon: const Icon(Icons.arrow_back, size: 16),
|
||||
label: Text(context.l10n.agentBackToProviders),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: AppSpacing.large),
|
||||
Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
_ConfigurationCard(
|
||||
title: context.l10n.agentProviderConfiguration,
|
||||
child: AppFieldGroup(
|
||||
children: [
|
||||
_ProviderIdentityRow(
|
||||
children: [
|
||||
AppField(
|
||||
label: context.l10n.name,
|
||||
child: TextFormField(
|
||||
style: _providerInputStyle(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
cursorHeight: 18,
|
||||
cursorWidth: 1.5,
|
||||
strutStyle: StrutStyle.fromTextStyle(
|
||||
_providerInputStyle(context),
|
||||
),
|
||||
key: const Key('agent-provider-name'),
|
||||
controller: _name,
|
||||
decoration: _providerInputDecoration(
|
||||
context,
|
||||
hintText: context.l10n.agentProviderNameHint,
|
||||
),
|
||||
validator: (value) => _required(context, value),
|
||||
),
|
||||
),
|
||||
AppField(
|
||||
label: context.l10n.agentApiType,
|
||||
child: AppSelect<AgentApiType>(
|
||||
emptyLabel: context.l10n.noMatchingOptions,
|
||||
controlHeight: AppSettingsMetrics.inputHeight,
|
||||
textStyle: _providerInputStyle(context),
|
||||
value: _apiType,
|
||||
label: context.l10n.agentApiType,
|
||||
options: [
|
||||
for (final value in AgentApiType.values)
|
||||
AppSelectOption(
|
||||
value,
|
||||
_apiTypeLabel(context, value),
|
||||
),
|
||||
],
|
||||
onChanged: (value) =>
|
||||
setState(() => _apiType = value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
AppField(
|
||||
label: context.l10n.agentBaseUrl,
|
||||
child: TextFormField(
|
||||
style: _providerInputStyle(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
cursorHeight: 18,
|
||||
cursorWidth: 1.5,
|
||||
strutStyle: StrutStyle.fromTextStyle(
|
||||
_providerInputStyle(context),
|
||||
),
|
||||
key: const Key('agent-provider-base-url'),
|
||||
controller: _baseUrl,
|
||||
keyboardType: TextInputType.url,
|
||||
decoration: _providerInputDecoration(
|
||||
context,
|
||||
hintText: _apiType == AgentApiType.anthropicMessages
|
||||
? 'https://api.anthropic.com/v1'
|
||||
: 'https://api.openai.com/v1',
|
||||
),
|
||||
validator: (value) => _validateUrl(context, value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.large),
|
||||
_ConfigurationCard(
|
||||
title: context.l10n.agentAuthenticationAndModels,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
AppField(
|
||||
label: context.l10n.agentApiKey,
|
||||
child: TextFormField(
|
||||
style: _providerInputStyle(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
cursorHeight: 18,
|
||||
cursorWidth: 1.5,
|
||||
strutStyle: StrutStyle.fromTextStyle(
|
||||
_providerInputStyle(context),
|
||||
),
|
||||
key: const Key('agent-provider-api-key'),
|
||||
controller: _apiKey,
|
||||
obscureText: true,
|
||||
decoration: _providerInputDecoration(
|
||||
context,
|
||||
hintText: context.l10n.agentOptional,
|
||||
),
|
||||
validator: (value) =>
|
||||
value != null &&
|
||||
(value.contains('\n') || value.contains('\r'))
|
||||
? context.l10n.agentApiKeyOneLine
|
||||
: null,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(
|
||||
widget.provider?.credentialId != null
|
||||
? context.l10n.agentApiKeyKeep
|
||||
: context.l10n.agentApiKeyOptional,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.extraLarge),
|
||||
if (_formError != null) ...[
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
Text(
|
||||
_formError!,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: AppSpacing.small),
|
||||
for (var index = 0; index < _models.length; index++)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: AppSpacing.medium),
|
||||
child: _ModelFields(
|
||||
index: index,
|
||||
controllers: _models[index],
|
||||
canDelete: _models.length > 1,
|
||||
onDelete: () {
|
||||
final removed = _models[index];
|
||||
setState(
|
||||
() => _models = [..._models]..removeAt(index),
|
||||
);
|
||||
removed.dispose();
|
||||
},
|
||||
),
|
||||
),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: () => setState(
|
||||
() => _models = [..._models, _ModelControllers()],
|
||||
),
|
||||
icon: const Icon(Icons.add, size: AppIconSize.header),
|
||||
label: Text(context.l10n.agentAddModel),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: AppSpacing.large),
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: FilledButton(
|
||||
onPressed: widget.saving ? null : _submit,
|
||||
child: Text(context.l10n.agentSaveProvider),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
|
||||
static String? _required(BuildContext context, String? value) =>
|
||||
value == null || value.trim().isEmpty
|
||||
? context.l10n.agentRequiredField
|
||||
: null;
|
||||
|
||||
static String? _validateUrl(BuildContext context, String? value) {
|
||||
final uri = Uri.tryParse(value?.trim() ?? '');
|
||||
return uri == null ||
|
||||
!uri.hasAuthority ||
|
||||
!['http', 'https'].contains(uri.scheme) ||
|
||||
uri.userInfo.isNotEmpty ||
|
||||
uri.hasQuery ||
|
||||
uri.hasFragment
|
||||
? context.l10n.agentInvalidBaseUrl
|
||||
: null;
|
||||
}
|
||||
|
||||
static String _apiTypeLabel(BuildContext context, AgentApiType value) =>
|
||||
switch (value) {
|
||||
AgentApiType.openAiChatCompletions =>
|
||||
context.l10n.agentOpenAiChatCompletions,
|
||||
AgentApiType.openAiResponses => 'OpenAI Responses',
|
||||
AgentApiType.anthropicMessages => 'Anthropic Messages',
|
||||
};
|
||||
}
|
||||
|
||||
class _ConfigurationCard extends StatelessWidget {
|
||||
const _ConfigurationCard({required this.title, required this.child});
|
||||
|
||||
final String title;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(title, style: theme.textTheme.labelLarge),
|
||||
const SizedBox(height: AppSpacing.medium),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(AppSpacing.medium),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainer,
|
||||
borderRadius: BorderRadius.circular(AppSettingsMetrics.cardRadius),
|
||||
border: Border.all(color: theme.colorScheme.outlineVariant),
|
||||
),
|
||||
child: child,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProviderIdentityRow extends StatelessWidget {
|
||||
const _ProviderIdentityRow({required this.children});
|
||||
final List<Widget> children;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => LayoutBuilder(
|
||||
builder: (context, constraints) => constraints.maxWidth < 520
|
||||
? AppFieldGroup(children: children)
|
||||
: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(child: children[0]),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(child: children[1]),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _ModelFields extends StatelessWidget {
|
||||
const _ModelFields({
|
||||
required this.index,
|
||||
required this.controllers,
|
||||
required this.canDelete,
|
||||
required this.onDelete,
|
||||
});
|
||||
|
||||
final int index;
|
||||
final _ModelControllers controllers;
|
||||
final bool canDelete;
|
||||
final VoidCallback onDelete;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final fields = <Widget>[
|
||||
AppField(
|
||||
label: context.l10n.agentModelId,
|
||||
child: TextFormField(
|
||||
style: _providerInputStyle(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
cursorHeight: 18,
|
||||
cursorWidth: 1.5,
|
||||
strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)),
|
||||
key: Key('agent-model-id-$index'),
|
||||
controller: controllers.id,
|
||||
decoration: _providerInputDecoration(
|
||||
context,
|
||||
hintText: 'my-model-id',
|
||||
),
|
||||
validator: (value) => _ProviderEditorState._required(context, value),
|
||||
),
|
||||
),
|
||||
AppField(
|
||||
label: context.l10n.agentContextWindow,
|
||||
child: TextFormField(
|
||||
style: _providerInputStyle(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
cursorHeight: 18,
|
||||
cursorWidth: 1.5,
|
||||
strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)),
|
||||
key: Key('agent-model-context-$index'),
|
||||
controller: controllers.contextWindow,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: _providerInputDecoration(context, hintText: '512000'),
|
||||
validator: (value) => _optionalPositiveInteger(context, value),
|
||||
),
|
||||
),
|
||||
AppField(
|
||||
label: context.l10n.agentMaxOutputTokens,
|
||||
child: TextFormField(
|
||||
style: _providerInputStyle(context),
|
||||
textAlignVertical: TextAlignVertical.center,
|
||||
cursorHeight: 18,
|
||||
cursorWidth: 1.5,
|
||||
strutStyle: StrutStyle.fromTextStyle(_providerInputStyle(context)),
|
||||
key: Key('agent-model-output-$index'),
|
||||
controller: controllers.maxOutputTokens,
|
||||
keyboardType: TextInputType.number,
|
||||
decoration: _providerInputDecoration(context, hintText: '4096'),
|
||||
validator: (value) {
|
||||
final basic = _optionalPositiveInteger(context, value);
|
||||
if (basic != null) return basic;
|
||||
final contextWindow = int.tryParse(controllers.contextWindow.text);
|
||||
final model = AgentModelSettings(
|
||||
id: controllers.id.text,
|
||||
contextWindow: contextWindow,
|
||||
maxOutputTokens: int.tryParse(value ?? ''),
|
||||
);
|
||||
if (!model.hasValidTokenBudget) {
|
||||
return context.l10n.agentMaxOutputBelowContext;
|
||||
}
|
||||
return model.hasInstructionBudget
|
||||
? null
|
||||
: context.l10n.agentContextBudgetTooSmall;
|
||||
},
|
||||
),
|
||||
),
|
||||
];
|
||||
final removeButton = SizedBox.square(
|
||||
dimension: AppSettingsMetrics.inputHeight,
|
||||
child: IconButton(
|
||||
style: IconButton.styleFrom(
|
||||
padding: EdgeInsets.zero,
|
||||
minimumSize: const Size.square(AppSettingsMetrics.inputHeight),
|
||||
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
|
||||
),
|
||||
tooltip: context.l10n.agentDeleteModel,
|
||||
onPressed: canDelete ? onDelete : null,
|
||||
icon: const Icon(Icons.delete_outline, size: AppIconSize.header),
|
||||
),
|
||||
);
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
if (constraints.maxWidth < 520) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
spacing: AppSpacing.compact,
|
||||
children: [
|
||||
...fields,
|
||||
Align(
|
||||
alignment: AlignmentDirectional.centerEnd,
|
||||
child: removeButton,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
return Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
spacing: AppSpacing.small,
|
||||
children: [
|
||||
for (var i = 0; i < fields.length; i++)
|
||||
Expanded(flex: i == 0 ? 2 : 1, child: fields[i]),
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 26),
|
||||
child: removeButton,
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
static String? _optionalPositiveInteger(BuildContext context, String? value) {
|
||||
if (value == null || value.trim().isEmpty) return null;
|
||||
final parsed = int.tryParse(value);
|
||||
return parsed == null || parsed <= 0
|
||||
? context.l10n.agentPositiveInteger
|
||||
: null;
|
||||
}
|
||||
}
|
||||
|
||||
class _ModelControllers {
|
||||
_ModelControllers([AgentModelSettings? model])
|
||||
: id = TextEditingController(text: model?.id),
|
||||
contextWindow = TextEditingController(
|
||||
text: model?.contextWindow?.toString(),
|
||||
),
|
||||
maxOutputTokens = TextEditingController(
|
||||
text: model?.maxOutputTokens?.toString(),
|
||||
);
|
||||
|
||||
final TextEditingController id;
|
||||
final TextEditingController contextWindow;
|
||||
final TextEditingController maxOutputTokens;
|
||||
|
||||
AgentModelSettings toData() => AgentModelSettings(
|
||||
id: id.text.trim(),
|
||||
contextWindow: int.tryParse(contextWindow.text),
|
||||
maxOutputTokens: int.tryParse(maxOutputTokens.text),
|
||||
);
|
||||
|
||||
void dispose() {
|
||||
id.dispose();
|
||||
contextWindow.dispose();
|
||||
maxOutputTokens.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
@freezed
|
||||
abstract class _ProviderFormValue with _$ProviderFormValue {
|
||||
const factory _ProviderFormValue({
|
||||
required String name,
|
||||
required AgentApiType apiType,
|
||||
required String baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
required String? apiKey,
|
||||
required bool clearApiKey,
|
||||
}) = _ProviderFormData;
|
||||
}
|
||||
@@ -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 'agent_settings_panel.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$ProviderFormValue {
|
||||
String get name;
|
||||
AgentApiType get apiType;
|
||||
String get baseUrl;
|
||||
List<AgentModelSettings> get models;
|
||||
String? get apiKey;
|
||||
bool get clearApiKey;
|
||||
|
||||
/// Create a copy of _ProviderFormValue
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ProviderFormValueCopyWith<_ProviderFormValue> get copyWith =>
|
||||
__$ProviderFormValueCopyWithImpl<_ProviderFormValue>(
|
||||
this as _ProviderFormValue,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as _ProviderFormValue;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ProviderFormValue &&
|
||||
(identical(other.name, _this.name) || other.name == _this.name) &&
|
||||
(identical(other.apiType, _this.apiType) ||
|
||||
other.apiType == _this.apiType) &&
|
||||
(identical(other.baseUrl, _this.baseUrl) ||
|
||||
other.baseUrl == _this.baseUrl) &&
|
||||
const DeepCollectionEquality().equals(other.models, _this.models) &&
|
||||
(identical(other.apiKey, _this.apiKey) ||
|
||||
other.apiKey == _this.apiKey) &&
|
||||
(identical(other.clearApiKey, _this.clearApiKey) ||
|
||||
other.clearApiKey == _this.clearApiKey));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as _ProviderFormValue;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.name,
|
||||
_this.apiType,
|
||||
_this.baseUrl,
|
||||
const DeepCollectionEquality().hash(_this.models),
|
||||
_this.apiKey,
|
||||
_this.clearApiKey,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as _ProviderFormValue;
|
||||
return '_ProviderFormValue(name: ${_this.name}, apiType: ${_this.apiType}, baseUrl: ${_this.baseUrl}, models: ${_this.models}, apiKey: ${_this.apiKey}, clearApiKey: ${_this.clearApiKey})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ProviderFormValueCopyWith<$Res> {
|
||||
factory _$ProviderFormValueCopyWith(
|
||||
_ProviderFormValue value,
|
||||
$Res Function(_ProviderFormValue) _then,
|
||||
) = __$ProviderFormValueCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String name,
|
||||
AgentApiType apiType,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ProviderFormValueCopyWithImpl<$Res>
|
||||
implements _$ProviderFormValueCopyWith<$Res> {
|
||||
__$ProviderFormValueCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ProviderFormValue _self;
|
||||
final $Res Function(_ProviderFormValue) _then;
|
||||
|
||||
/// Create a copy of _ProviderFormValue
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? name = null,
|
||||
Object? apiType = null,
|
||||
Object? baseUrl = null,
|
||||
Object? models = null,
|
||||
Object? apiKey = freezed,
|
||||
Object? clearApiKey = null,
|
||||
}) {
|
||||
return _then(
|
||||
_ProviderFormValue(
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
apiType: null == apiType
|
||||
? _self.apiType
|
||||
: apiType // ignore: cast_nullable_to_non_nullable
|
||||
as AgentApiType,
|
||||
baseUrl: null == baseUrl
|
||||
? _self.baseUrl
|
||||
: baseUrl // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
models: null == models
|
||||
? _self.models
|
||||
: models // ignore: cast_nullable_to_non_nullable
|
||||
as List<AgentModelSettings>,
|
||||
apiKey: freezed == apiKey
|
||||
? _self.apiKey
|
||||
: apiKey // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
clearApiKey: null == clearApiKey
|
||||
? _self.clearApiKey
|
||||
: clearApiKey // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [_ProviderFormValue].
|
||||
extension _ProviderFormValuePatterns on _ProviderFormValue {
|
||||
/// 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(_ProviderFormData value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProviderFormData() 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(_ProviderFormData value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProviderFormData():
|
||||
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(_ProviderFormData value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProviderFormData() 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 name,
|
||||
AgentApiType apiType,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProviderFormData() when $default != null:
|
||||
return $default(
|
||||
_that.name,
|
||||
_that.apiType,
|
||||
_that.baseUrl,
|
||||
_that.models,
|
||||
_that.apiKey,
|
||||
_that.clearApiKey,
|
||||
);
|
||||
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 name,
|
||||
AgentApiType apiType,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProviderFormData():
|
||||
return $default(
|
||||
_that.name,
|
||||
_that.apiType,
|
||||
_that.baseUrl,
|
||||
_that.models,
|
||||
_that.apiKey,
|
||||
_that.clearApiKey,
|
||||
);
|
||||
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 name,
|
||||
AgentApiType apiType,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _ProviderFormData() when $default != null:
|
||||
return $default(
|
||||
_that.name,
|
||||
_that.apiType,
|
||||
_that.baseUrl,
|
||||
_that.models,
|
||||
_that.apiKey,
|
||||
_that.clearApiKey,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _ProviderFormData implements _ProviderFormValue {
|
||||
const _ProviderFormData({
|
||||
required this.name,
|
||||
required this.apiType,
|
||||
required this.baseUrl,
|
||||
required List<AgentModelSettings> models,
|
||||
required this.apiKey,
|
||||
required this.clearApiKey,
|
||||
}) : _models = models;
|
||||
|
||||
@override
|
||||
final String name;
|
||||
@override
|
||||
final AgentApiType apiType;
|
||||
@override
|
||||
final String baseUrl;
|
||||
final List<AgentModelSettings> _models;
|
||||
@override
|
||||
List<AgentModelSettings> get models {
|
||||
if (_models is EqualUnmodifiableListView) return _models;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_models);
|
||||
}
|
||||
|
||||
@override
|
||||
final String? apiKey;
|
||||
@override
|
||||
final bool clearApiKey;
|
||||
|
||||
/// Create a copy of _ProviderFormValue
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$ProviderFormDataCopyWith<_ProviderFormData> get copyWith =>
|
||||
__$ProviderFormDataCopyWithImpl<_ProviderFormData>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _ProviderFormData &&
|
||||
(identical(other.name, name) || other.name == name) &&
|
||||
(identical(other.apiType, apiType) || other.apiType == apiType) &&
|
||||
(identical(other.baseUrl, baseUrl) || other.baseUrl == baseUrl) &&
|
||||
const DeepCollectionEquality().equals(other.models, _models) &&
|
||||
(identical(other.apiKey, apiKey) || other.apiKey == apiKey) &&
|
||||
(identical(other.clearApiKey, clearApiKey) ||
|
||||
other.clearApiKey == clearApiKey));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
name,
|
||||
apiType,
|
||||
baseUrl,
|
||||
const DeepCollectionEquality().hash(_models),
|
||||
apiKey,
|
||||
clearApiKey,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return '_ProviderFormValue(name: $name, apiType: $apiType, baseUrl: $baseUrl, models: $models, apiKey: $apiKey, clearApiKey: $clearApiKey)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$ProviderFormDataCopyWith<$Res>
|
||||
implements _$ProviderFormValueCopyWith<$Res> {
|
||||
factory _$ProviderFormDataCopyWith(
|
||||
_ProviderFormData value,
|
||||
$Res Function(_ProviderFormData) _then,
|
||||
) = __$ProviderFormDataCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
String name,
|
||||
AgentApiType apiType,
|
||||
String baseUrl,
|
||||
List<AgentModelSettings> models,
|
||||
String? apiKey,
|
||||
bool clearApiKey,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$ProviderFormDataCopyWithImpl<$Res>
|
||||
implements _$ProviderFormDataCopyWith<$Res> {
|
||||
__$ProviderFormDataCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _ProviderFormData _self;
|
||||
final $Res Function(_ProviderFormData) _then;
|
||||
|
||||
/// Create a copy of _ProviderFormValue
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? name = null,
|
||||
Object? apiType = null,
|
||||
Object? baseUrl = null,
|
||||
Object? models = null,
|
||||
Object? apiKey = freezed,
|
||||
Object? clearApiKey = null,
|
||||
}) {
|
||||
return _then(
|
||||
_ProviderFormData(
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
apiType: null == apiType
|
||||
? _self.apiType
|
||||
: apiType // ignore: cast_nullable_to_non_nullable
|
||||
as AgentApiType,
|
||||
baseUrl: null == baseUrl
|
||||
? _self.baseUrl
|
||||
: baseUrl // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
models: null == models
|
||||
? _self._models
|
||||
: models // ignore: cast_nullable_to_non_nullable
|
||||
as List<AgentModelSettings>,
|
||||
apiKey: freezed == apiKey
|
||||
? _self.apiKey
|
||||
: apiKey // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
clearApiKey: null == clearApiKey
|
||||
? _self.clearApiKey
|
||||
: clearApiKey // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../persistence/settings/appearance_settings_repository.dart';
|
||||
import '../../settings/appearance.dart';
|
||||
import '../../settings/settings_write_queue.dart';
|
||||
|
||||
export '../../settings/appearance.dart';
|
||||
|
||||
part 'appearance_settings.g.dart';
|
||||
|
||||
extension AppAppearanceTheme on AppAppearance {
|
||||
ThemeMode get themeMode => switch (this) {
|
||||
AppAppearance.system => ThemeMode.system,
|
||||
AppAppearance.penLight => ThemeMode.light,
|
||||
AppAppearance.penDark => ThemeMode.dark,
|
||||
};
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class AppearanceSettings extends _$AppearanceSettings {
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
Future<AppAppearance> build() =>
|
||||
ref.watch(appearanceSettingsRepositoryProvider).load();
|
||||
|
||||
Future<void> setMode(AppAppearance appearance) => _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
await future;
|
||||
if (!ref.mounted) return;
|
||||
await ref.read(appearanceSettingsRepositoryProvider).save(appearance);
|
||||
if (ref.mounted) state = AsyncData(appearance);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'appearance_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(AppearanceSettings)
|
||||
final appearanceSettingsProvider = AppearanceSettingsProvider._();
|
||||
|
||||
final class AppearanceSettingsProvider
|
||||
extends $AsyncNotifierProvider<AppearanceSettings, AppAppearance> {
|
||||
AppearanceSettingsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'appearanceSettingsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$appearanceSettingsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
AppearanceSettings create() => AppearanceSettings();
|
||||
}
|
||||
|
||||
String _$appearanceSettingsHash() =>
|
||||
r'df889bcd3ec16a726ebc1bccd98b9e7033989a69';
|
||||
|
||||
abstract class _$AppearanceSettings extends $AsyncNotifier<AppAppearance> {
|
||||
FutureOr<AppAppearance> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<AppAppearance>, AppAppearance>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<AppAppearance>, AppAppearance>,
|
||||
AsyncValue<AppAppearance>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_ui/widgets.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
|
||||
import '../../diagnostics/app_diagnostics.dart';
|
||||
import '../../integrations/platform/file_picker.dart';
|
||||
import '../../l10n/l10n.dart';
|
||||
import '../../settings/settings_operation.dart';
|
||||
|
||||
class DiagnosticSettings extends ConsumerStatefulWidget {
|
||||
const DiagnosticSettings({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<DiagnosticSettings> createState() => _DiagnosticSettingsState();
|
||||
}
|
||||
|
||||
class _DiagnosticSettingsState extends ConsumerState<DiagnosticSettings> {
|
||||
bool _exported = false;
|
||||
|
||||
Future<void> _export() async {
|
||||
setState(() => _exported = false);
|
||||
final picker = ref.read(filePickerProvider);
|
||||
await ref.read(settingsOperationProvider('diagnosticsExport').notifier).run(
|
||||
() async {
|
||||
final selected = await picker.pickDirectory();
|
||||
if (selected == null) return;
|
||||
final diagnostics =
|
||||
AppDiagnostics.instance ?? await AppDiagnostics.initialize();
|
||||
await diagnostics.export(Directory(selected));
|
||||
if (mounted) setState(() => _exported = true);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final operation = ref.watch(settingsOperationProvider('diagnosticsExport'));
|
||||
return AppField(
|
||||
label: context.l10n.diagnostics,
|
||||
orientation: AppFieldOrientation.horizontal,
|
||||
error: operation.hasError ? context.l10n.exportDiagnosticsFailed : null,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
OutlinedButton(
|
||||
key: const Key('export-diagnostics'),
|
||||
onPressed: operation.isLoading ? null : _export,
|
||||
child: Text(context.l10n.exportDiagnostics),
|
||||
),
|
||||
if (_exported) Text(context.l10n.exportDiagnosticsSucceeded),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../persistence/settings/language_settings_repository.dart';
|
||||
import '../../settings/language.dart';
|
||||
import '../../settings/settings_write_queue.dart';
|
||||
|
||||
export '../../settings/language.dart';
|
||||
|
||||
part 'language_settings.g.dart';
|
||||
|
||||
extension AppLanguagePresentation on AppLanguage {
|
||||
Locale? get locale => switch (this) {
|
||||
AppLanguage.system => null,
|
||||
AppLanguage.english => const Locale('en'),
|
||||
AppLanguage.simplifiedChinese => const Locale.fromSubtags(
|
||||
languageCode: 'zh',
|
||||
scriptCode: 'Hans',
|
||||
),
|
||||
AppLanguage.traditionalChinese => const Locale.fromSubtags(
|
||||
languageCode: 'zh',
|
||||
scriptCode: 'Hant',
|
||||
),
|
||||
AppLanguage.japanese => const Locale('ja'),
|
||||
AppLanguage.korean => const Locale('ko'),
|
||||
AppLanguage.french => const Locale('fr'),
|
||||
AppLanguage.german => const Locale('de'),
|
||||
AppLanguage.spanish => const Locale('es'),
|
||||
AppLanguage.portuguese => const Locale('pt'),
|
||||
AppLanguage.italian => const Locale('it'),
|
||||
AppLanguage.russian => const Locale('ru'),
|
||||
};
|
||||
|
||||
String get nativeName => switch (this) {
|
||||
AppLanguage.system => '',
|
||||
AppLanguage.english => 'English',
|
||||
AppLanguage.simplifiedChinese => '简体中文',
|
||||
AppLanguage.traditionalChinese => '繁體中文',
|
||||
AppLanguage.japanese => '日本語',
|
||||
AppLanguage.korean => '한국어',
|
||||
AppLanguage.french => 'Français',
|
||||
AppLanguage.german => 'Deutsch',
|
||||
AppLanguage.spanish => 'Español',
|
||||
AppLanguage.portuguese => 'Português',
|
||||
AppLanguage.italian => 'Italiano',
|
||||
AppLanguage.russian => 'Русский',
|
||||
};
|
||||
}
|
||||
|
||||
/// Select a supported language in device preference order, resolving Chinese
|
||||
/// scripts explicitly when the operating system supplies only a region.
|
||||
Locale resolveAppLocale(
|
||||
List<Locale>? preferredLocales,
|
||||
Iterable<Locale> supportedLocales,
|
||||
) {
|
||||
for (final preferred in preferredLocales ?? const <Locale>[]) {
|
||||
if (preferred.languageCode == 'zh') {
|
||||
final script =
|
||||
preferred.scriptCode ??
|
||||
(const {'TW', 'HK', 'MO'}.contains(preferred.countryCode)
|
||||
? 'Hant'
|
||||
: 'Hans');
|
||||
final match = supportedLocales
|
||||
.where(
|
||||
(locale) =>
|
||||
locale.languageCode == 'zh' && locale.scriptCode == script,
|
||||
)
|
||||
.firstOrNull;
|
||||
if (match != null) return match;
|
||||
}
|
||||
final match = supportedLocales
|
||||
.where((locale) => locale.languageCode == preferred.languageCode)
|
||||
.firstOrNull;
|
||||
if (match != null) return match;
|
||||
}
|
||||
return supportedLocales
|
||||
.where((locale) => locale.languageCode == 'en')
|
||||
.firstOrNull ??
|
||||
supportedLocales.first;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class LanguageSettings extends _$LanguageSettings {
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
Future<AppLanguage> build() =>
|
||||
ref.watch(languageSettingsRepositoryProvider).load();
|
||||
|
||||
Future<void> setLanguage(AppLanguage language) => _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
await future;
|
||||
if (!ref.mounted) return;
|
||||
await ref.read(languageSettingsRepositoryProvider).save(language);
|
||||
if (ref.mounted) state = AsyncData(language);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'language_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(LanguageSettings)
|
||||
final languageSettingsProvider = LanguageSettingsProvider._();
|
||||
|
||||
final class LanguageSettingsProvider
|
||||
extends $AsyncNotifierProvider<LanguageSettings, AppLanguage> {
|
||||
LanguageSettingsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'languageSettingsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$languageSettingsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
LanguageSettings create() => LanguageSettings();
|
||||
}
|
||||
|
||||
String _$languageSettingsHash() => r'fcd5bb7f010ea5bb09f9743d9023cd1668214f43';
|
||||
|
||||
abstract class _$LanguageSettings extends $AsyncNotifier<AppLanguage> {
|
||||
FutureOr<AppLanguage> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
WhenComplete runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<AppLanguage>, AppLanguage>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<AppLanguage>, AppLanguage>,
|
||||
AsyncValue<AppLanguage>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
return element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
import '../../integrations/runtime/processing_resource_repository.dart';
|
||||
import '../../persistence/settings/location_settings_repositories.dart';
|
||||
import '../../settings/settings_write_queue.dart';
|
||||
import '../../workspace/persistence/project_location_directory.dart';
|
||||
|
||||
part 'location_settings.g.dart';
|
||||
part 'location_settings.freezed.dart';
|
||||
|
||||
enum LocationSettingsError { load, save }
|
||||
|
||||
@freezed
|
||||
abstract class LocationSettingsState with _$LocationSettingsState {
|
||||
const factory LocationSettingsState({
|
||||
String? directory,
|
||||
ProjectLocationStatus? status,
|
||||
@Default(true) bool loading,
|
||||
@Default(false) bool saving,
|
||||
LocationSettingsError? error,
|
||||
}) = _LocationSettingsState;
|
||||
}
|
||||
|
||||
@riverpod
|
||||
ProjectLocationDirectory projectLocationDirectory(Ref ref) =>
|
||||
const ProjectLocationDirectory();
|
||||
|
||||
@riverpod
|
||||
class ProjectLocationSettings extends _$ProjectLocationSettings {
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
LocationSettingsState build() {
|
||||
final repository = ref.watch(projectLocationSettingsRepositoryProvider);
|
||||
final directory = ref.watch(projectLocationDirectoryProvider);
|
||||
unawaited(_writes.run(() => _load(repository, directory)));
|
||||
return const LocationSettingsState();
|
||||
}
|
||||
|
||||
Future<void> reload() => _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
await _load(
|
||||
ref.read(projectLocationSettingsRepositoryProvider),
|
||||
ref.read(projectLocationDirectoryProvider),
|
||||
);
|
||||
});
|
||||
|
||||
Future<void> _load(
|
||||
ProjectLocationSettingsRepository repository,
|
||||
ProjectLocationDirectory inspector,
|
||||
) async {
|
||||
if (!ref.mounted) return;
|
||||
state = state.copyWith(loading: true, error: null, status: null);
|
||||
try {
|
||||
final directory = await repository.load();
|
||||
if (!ref.mounted) return;
|
||||
state = state.copyWith(directory: directory);
|
||||
final status = directory == null
|
||||
? null
|
||||
: await inspector.inspect(directory);
|
||||
if (ref.mounted) state = state.copyWith(status: status);
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(error: LocationSettingsError.load);
|
||||
}
|
||||
} finally {
|
||||
if (ref.mounted) state = state.copyWith(loading: false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> save(String directory) => _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
final keepAlive = ref.keepAlive();
|
||||
state = state.copyWith(saving: true, error: null);
|
||||
final repository = ref.read(projectLocationSettingsRepositoryProvider);
|
||||
final inspector = ref.read(projectLocationDirectoryProvider);
|
||||
try {
|
||||
await repository.save(directory);
|
||||
if (ref.mounted) await _load(repository, inspector);
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(error: LocationSettingsError.save);
|
||||
}
|
||||
} finally {
|
||||
if (ref.mounted) state = state.copyWith(saving: false);
|
||||
keepAlive.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@riverpod
|
||||
class ResourceLocationSettings extends _$ResourceLocationSettings {
|
||||
final _writes = SettingsWriteQueue();
|
||||
|
||||
@override
|
||||
LocationSettingsState build() {
|
||||
final repository = ref.watch(resourceLocationSettingsRepositoryProvider);
|
||||
unawaited(_writes.run(() => _load(repository)));
|
||||
return const LocationSettingsState();
|
||||
}
|
||||
|
||||
Future<void> _load(ResourceLocationSettingsRepository repository) async {
|
||||
if (!ref.mounted) return;
|
||||
try {
|
||||
final directory = await repository.load();
|
||||
if (ref.mounted) state = state.copyWith(directory: directory);
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(error: LocationSettingsError.load);
|
||||
}
|
||||
} finally {
|
||||
if (ref.mounted) state = state.copyWith(loading: false);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> save(String directory) => _writes.run(() async {
|
||||
if (!ref.mounted) return;
|
||||
final keepAlive = ref.keepAlive();
|
||||
state = state.copyWith(saving: true, error: null);
|
||||
try {
|
||||
await ref
|
||||
.read(resourceLocationSettingsRepositoryProvider)
|
||||
.save(directory);
|
||||
if (!ref.mounted) return;
|
||||
ref.invalidate(processingResourceRepositoryProvider);
|
||||
state = state.copyWith(directory: directory);
|
||||
} catch (_) {
|
||||
if (ref.mounted) {
|
||||
state = state.copyWith(error: LocationSettingsError.save);
|
||||
}
|
||||
} finally {
|
||||
if (ref.mounted) state = state.copyWith(saving: false);
|
||||
keepAlive.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,450 @@
|
||||
// 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 'location_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// FreezedGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$LocationSettingsState {
|
||||
String? get directory;
|
||||
ProjectLocationStatus? get status;
|
||||
bool get loading;
|
||||
bool get saving;
|
||||
LocationSettingsError? get error;
|
||||
|
||||
/// Create a copy of LocationSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$LocationSettingsStateCopyWith<LocationSettingsState> get copyWith =>
|
||||
_$LocationSettingsStateCopyWithImpl<LocationSettingsState>(
|
||||
this as LocationSettingsState,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
final _this = this as LocationSettingsState;
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is LocationSettingsState &&
|
||||
(identical(other.directory, _this.directory) ||
|
||||
other.directory == _this.directory) &&
|
||||
(identical(other.status, _this.status) ||
|
||||
other.status == _this.status) &&
|
||||
(identical(other.loading, _this.loading) ||
|
||||
other.loading == _this.loading) &&
|
||||
(identical(other.saving, _this.saving) ||
|
||||
other.saving == _this.saving) &&
|
||||
(identical(other.error, _this.error) ||
|
||||
other.error == _this.error));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
final _this = this as LocationSettingsState;
|
||||
return Object.hash(
|
||||
runtimeType,
|
||||
_this.directory,
|
||||
_this.status,
|
||||
_this.loading,
|
||||
_this.saving,
|
||||
_this.error,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final _this = this as LocationSettingsState;
|
||||
return 'LocationSettingsState(directory: ${_this.directory}, status: ${_this.status}, loading: ${_this.loading}, saving: ${_this.saving}, error: ${_this.error})';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $LocationSettingsStateCopyWith<$Res> {
|
||||
factory $LocationSettingsStateCopyWith(
|
||||
LocationSettingsState value,
|
||||
$Res Function(LocationSettingsState) _then,
|
||||
) = _$LocationSettingsStateCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String? directory,
|
||||
ProjectLocationStatus? status,
|
||||
bool loading,
|
||||
bool saving,
|
||||
LocationSettingsError? error,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class _$LocationSettingsStateCopyWithImpl<$Res>
|
||||
implements $LocationSettingsStateCopyWith<$Res> {
|
||||
_$LocationSettingsStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final LocationSettingsState _self;
|
||||
final $Res Function(LocationSettingsState) _then;
|
||||
|
||||
/// Create a copy of LocationSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? directory = freezed,
|
||||
Object? status = freezed,
|
||||
Object? loading = null,
|
||||
Object? saving = null,
|
||||
Object? error = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
LocationSettingsState(
|
||||
directory: freezed == directory
|
||||
? _self.directory
|
||||
: directory // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
status: freezed == status
|
||||
? _self.status
|
||||
: status // ignore: cast_nullable_to_non_nullable
|
||||
as ProjectLocationStatus?,
|
||||
loading: null == loading
|
||||
? _self.loading
|
||||
: loading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
saving: null == saving
|
||||
? _self.saving
|
||||
: saving // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
error: freezed == error
|
||||
? _self.error
|
||||
: error // ignore: cast_nullable_to_non_nullable
|
||||
as LocationSettingsError?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds pattern-matching-related methods to [LocationSettingsState].
|
||||
extension LocationSettingsStatePatterns on LocationSettingsState {
|
||||
/// 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(_LocationSettingsState value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LocationSettingsState() 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(_LocationSettingsState value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LocationSettingsState():
|
||||
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(_LocationSettingsState value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LocationSettingsState() 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? directory,
|
||||
ProjectLocationStatus? status,
|
||||
bool loading,
|
||||
bool saving,
|
||||
LocationSettingsError? error,
|
||||
)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LocationSettingsState() when $default != null:
|
||||
return $default(
|
||||
_that.directory,
|
||||
_that.status,
|
||||
_that.loading,
|
||||
_that.saving,
|
||||
_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?>(
|
||||
TResult Function(
|
||||
String? directory,
|
||||
ProjectLocationStatus? status,
|
||||
bool loading,
|
||||
bool saving,
|
||||
LocationSettingsError? error,
|
||||
)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LocationSettingsState():
|
||||
return $default(
|
||||
_that.directory,
|
||||
_that.status,
|
||||
_that.loading,
|
||||
_that.saving,
|
||||
_that.error,
|
||||
);
|
||||
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? directory,
|
||||
ProjectLocationStatus? status,
|
||||
bool loading,
|
||||
bool saving,
|
||||
LocationSettingsError? error,
|
||||
)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LocationSettingsState() when $default != null:
|
||||
return $default(
|
||||
_that.directory,
|
||||
_that.status,
|
||||
_that.loading,
|
||||
_that.saving,
|
||||
_that.error,
|
||||
);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
|
||||
class _LocationSettingsState implements LocationSettingsState {
|
||||
const _LocationSettingsState({
|
||||
this.directory,
|
||||
this.status,
|
||||
this.loading = true,
|
||||
this.saving = false,
|
||||
this.error,
|
||||
});
|
||||
|
||||
@override
|
||||
final String? directory;
|
||||
@override
|
||||
final ProjectLocationStatus? status;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool loading;
|
||||
@override
|
||||
@JsonKey()
|
||||
final bool saving;
|
||||
@override
|
||||
final LocationSettingsError? error;
|
||||
|
||||
/// Create a copy of LocationSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$LocationSettingsStateCopyWith<_LocationSettingsState> get copyWith =>
|
||||
__$LocationSettingsStateCopyWithImpl<_LocationSettingsState>(
|
||||
this,
|
||||
_$identity,
|
||||
);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _LocationSettingsState &&
|
||||
(identical(other.directory, directory) ||
|
||||
other.directory == directory) &&
|
||||
(identical(other.status, status) || other.status == status) &&
|
||||
(identical(other.loading, loading) || other.loading == loading) &&
|
||||
(identical(other.saving, saving) || other.saving == saving) &&
|
||||
(identical(other.error, error) || other.error == error));
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, directory, status, loading, saving, error);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'LocationSettingsState(directory: $directory, status: $status, loading: $loading, saving: $saving, error: $error)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$LocationSettingsStateCopyWith<$Res>
|
||||
implements $LocationSettingsStateCopyWith<$Res> {
|
||||
factory _$LocationSettingsStateCopyWith(
|
||||
_LocationSettingsState value,
|
||||
$Res Function(_LocationSettingsState) _then,
|
||||
) = __$LocationSettingsStateCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call({
|
||||
String? directory,
|
||||
ProjectLocationStatus? status,
|
||||
bool loading,
|
||||
bool saving,
|
||||
LocationSettingsError? error,
|
||||
});
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
class __$LocationSettingsStateCopyWithImpl<$Res>
|
||||
implements _$LocationSettingsStateCopyWith<$Res> {
|
||||
__$LocationSettingsStateCopyWithImpl(this._self, this._then);
|
||||
|
||||
final _LocationSettingsState _self;
|
||||
final $Res Function(_LocationSettingsState) _then;
|
||||
|
||||
/// Create a copy of LocationSettingsState
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? directory = freezed,
|
||||
Object? status = freezed,
|
||||
Object? loading = null,
|
||||
Object? saving = null,
|
||||
Object? error = freezed,
|
||||
}) {
|
||||
return _then(
|
||||
_LocationSettingsState(
|
||||
directory: freezed == directory
|
||||
? _self.directory
|
||||
: directory // ignore: cast_nullable_to_non_nullable
|
||||
as String?,
|
||||
status: freezed == status
|
||||
? _self.status
|
||||
: status // ignore: cast_nullable_to_non_nullable
|
||||
as ProjectLocationStatus?,
|
||||
loading: null == loading
|
||||
? _self.loading
|
||||
: loading // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
saving: null == saving
|
||||
? _self.saving
|
||||
: saving // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
error: freezed == error
|
||||
? _self.error
|
||||
: error // ignore: cast_nullable_to_non_nullable
|
||||
as LocationSettingsError?,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 718 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user