feat: initial Cutdex application

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

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

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

No files matched your search

@@ -0,0 +1,16 @@
import 'package:flutter/foundation.dart';
/// Desktop split preferences outlive the desktop shell when a window narrows.
class DesktopWorkspaceController extends ChangeNotifier {
double? _agentWidth;
bool _editorCollapsedByAgent = false;
double? get agentWidth => _agentWidth;
bool get editorCollapsedByAgent => _editorCollapsedByAgent;
void setSplit(double? width, {required bool editorCollapsed}) {
_agentWidth = width;
_editorCollapsedByAgent = editorCollapsed;
notifyListeners();
}
}
@@ -0,0 +1,78 @@
import 'dart:math' as math;
import '../../workspace/workspace_mode.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
/// Spatial rules used within a device experience; never selects a device shell.
abstract final class WorkspaceLayoutPolicy {
static bool desktopNavigationFits(double width) =>
width >=
WorkspaceLayoutMetrics.sidebarMinimumWidth +
WorkspaceLayoutMetrics.contentMinimumWidth +
1;
static bool showAgentBesideEditor(double width) =>
width >= WorkspaceLayoutMetrics.dualPaneMinimumWidth;
}
/// Desktop geometry is resolved without mutating preferences during build.
final class DesktopWorkspaceGeometry {
const DesktopWorkspaceGeometry({
required this.sidebarWidth,
required this.agentWidth,
required this.editorHidden,
});
static const editorCollapseWidth = 480.0;
static const editorCollapseDragBuffer = editorCollapseWidth / 3;
static const editorRestoreWidth = 560.0;
final double sidebarWidth;
final double agentWidth;
final bool editorHidden;
static double sidebarMaximum(double width, WorkspaceMode mode) =>
WorkspaceLayoutMetrics.sidebarMaximumWidth(
width - (mode == WorkspaceMode.agent ? 221 : 0),
);
factory DesktopWorkspaceGeometry.resolve({
required double width,
required WorkspaceMode mode,
required bool sidebarCollapsed,
double? sidebarWidth,
double? agentWidth,
bool editorCollapsedByAgent = false,
}) {
final navigationWidth =
(sidebarWidth ?? WorkspaceLayoutMetrics.sidebarDefaultWidth)
.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
sidebarMaximum(width, mode),
)
.toDouble();
final navigationSpace = sidebarCollapsed ? 0.0 : navigationWidth;
final requestedAgentWidth = mode == WorkspaceMode.agent
? (agentWidth ?? (width * .25).clamp(260.0, 320.0))
.clamp(220.0, math.max(220.0, width - navigationSpace - 1))
.toDouble()
: 0.0;
final remaining = width - navigationSpace - requestedAgentWidth - 1;
final hidden =
mode == WorkspaceMode.agent &&
(width - navigationSpace - 1 < 220 + editorCollapseWidth ||
(editorCollapsedByAgent && remaining < editorRestoreWidth) ||
remaining <= editorCollapseWidth - editorCollapseDragBuffer);
return DesktopWorkspaceGeometry(
sidebarWidth: navigationWidth,
agentWidth: hidden
? width - navigationSpace
: mode == WorkspaceMode.agent
? requestedAgentWidth
.clamp(220.0, width - navigationSpace - editorCollapseWidth - 1)
.toDouble()
: 0,
editorHidden: hidden,
);
}
}
+37
View File
@@ -0,0 +1,37 @@
import 'package:cutdex/app/editor_theme.dart';
import '../l10n/app_localizations.dart';
import '../features/settings/language_settings.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'router/app_router.dart';
import '../integrations/app_updates.dart';
import '../integrations/editor_tools.dart';
import '../features/settings/appearance_settings.dart';
class CutdexApp extends ConsumerWidget {
const CutdexApp({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ref.watch(applicationMcpConnectionProvider);
ref.watch(appUpdateLifecycleProvider);
final appearance =
ref.watch(appearanceSettingsProvider).asData?.value ??
AppAppearance.system;
return MaterialApp.router(
title: 'Cutdex',
locale: ref.watch(languageSettingsProvider).asData?.value.locale,
localizationsDelegates: AppLocalizations.localizationsDelegates,
supportedLocales: AppLocalizations.supportedLocales,
localeListResolutionCallback: resolveAppLocale,
debugShowCheckedModeBanner: false,
theme: EditorTheme.penLight,
darkTheme: EditorTheme.penDark,
themeMode: appearance.themeMode,
routerConfig: ref.watch(appRouterProvider),
);
}
}
+72
View File
@@ -0,0 +1,72 @@
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/material.dart';
/// Connects the application palette to the SDK timeline presentation.
abstract final class EditorTheme {
static ThemeData get penLight => adapt(AppTheme.penLight);
static ThemeData get penDark => adapt(AppTheme.penDark);
static ThemeData adapt(ThemeData theme) {
final palette = theme.brightness == Brightness.dark
? AppColors.penDark
: AppColors.penLight;
final dark = theme.brightness == Brightness.dark;
final text = theme.textTheme;
final timelineBorder = palette.divider;
final timelineSecondary = dark
? palette.foreground.withValues(alpha: .71)
: palette.mutedForeground;
final timelineTertiary = dark
? palette.foreground.withValues(alpha: .498)
: palette.mutedForeground.withValues(alpha: .8);
return theme.copyWith(
extensions: [
...theme.extensions.values,
const TimelineThemeData.dark().copyWith(
backgroundColor: palette.background,
primaryLaneBackgroundColor: palette.sidebar,
visualClipColor: palette.visualClip,
audioClipColor: palette.popover,
audioAccentColor: timelineSecondary,
gapColor: timelineBorder,
gapBorderColor: timelineBorder,
containerAccentColor: timelineSecondary,
transitionColor: timelineTertiary,
connectionLineColor: timelineBorder,
connectionLineWidth: 3,
clipBorderColor: timelineBorder,
clipBorderWidth: 1,
selectionOutlineColor: palette.foreground,
selectionOutlineWidth: 2,
keyframeColor: timelineSecondary,
keyframeBorderColor: palette.background,
keyframeInvalidColor: palette.destructive,
disabledOverlayColor: palette.background.withValues(alpha: 0.5),
outsideSourceRangeOverlayColor: palette.background.withValues(
alpha: 0.65,
),
clipCornerRadius: AppRadius.small,
clipHeaderHeight: 16,
clipHeaderPadding: 2,
clipNameTextStyle: text.bodySmall!.copyWith(
color: palette.foreground,
fontSize: 10,
height: 1.4,
),
rulerHeight: 20,
rulerBackgroundColor: palette.background,
rulerTickColor: timelineTertiary,
rulerTextStyle: text.bodySmall!.copyWith(
height: 16 / 12,
color: timelineSecondary,
),
playheadColor: palette.foreground,
scrollbarThickness: AppSpacing.compact,
scrollbarTrackColor: Colors.transparent,
scrollbarThumbColor: palette.foreground.withValues(alpha: .084),
),
],
);
}
}
+28
View File
@@ -0,0 +1,28 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../features/projects/projects_page.dart';
part 'app_router.g.dart';
// The router is an application resource, independent of editor state changes.
@Riverpod(keepAlive: true)
GoRouter appRouter(Ref ref) {
final router = GoRouter(
routes: [
GoRoute(path: '/', builder: (context, state) => const EditingPage()),
],
errorBuilder: (context, state) => Scaffold(
body: Center(
child: FilledButton(
onPressed: () => context.go('/'),
child: Text(context.l10n.backToProjects),
),
),
),
);
ref.onDispose(router.dispose);
return router;
}
+51
View File
@@ -0,0 +1,51 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'app_router.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(appRouter)
final appRouterProvider = AppRouterProvider._();
final class AppRouterProvider
extends $FunctionalProvider<GoRouter, GoRouter, GoRouter>
with $Provider<GoRouter> {
AppRouterProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'appRouterProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$appRouterHash();
@$internal
@override
$ProviderElement<GoRouter> $createElement($ProviderPointer pointer) =>
$ProviderElement(pointer);
@override
GoRouter create(Ref ref) {
return appRouter(ref);
}
/// {@macro riverpod.override_with_value}
Override overrideWithValue(GoRouter value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<GoRouter>(value),
);
}
}
String _$appRouterHash() => r'ebb3f9239a43568767def98552081806bd614bb4';
+276
View File
@@ -0,0 +1,276 @@
import '../adaptive/desktop_workspace_controller.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import '../../workspace/workspace_mode.dart';
import '../../shared/layout/workspace_layout_metrics.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../adaptive/workspace_layout_policy.dart';
typedef WorkspaceSidebarBuilder = Widget Function(
DesktopWorkspaceGeometry geometry,
VoidCallback expandEditor,
);
/// Arranges slots and handles splitters; it does not own editing sessions.
class DesktopWorkspaceShell extends StatefulWidget {
const DesktopWorkspaceShell({
super.key,
required this.mode,
required this.controller,
required this.sidebarCollapsed,
required this.sidebarWidth,
required this.onSidebarCollapsedChanged,
required this.onSidebarWidthChanged,
required this.sidebarBuilder,
required this.editor,
required this.scaffoldKey,
required this.navigationDrawer,
});
final WorkspaceMode mode;
final DesktopWorkspaceController controller;
final bool sidebarCollapsed;
final double? sidebarWidth;
final ValueChanged<bool> onSidebarCollapsedChanged;
final ValueChanged<double> onSidebarWidthChanged;
final WorkspaceSidebarBuilder sidebarBuilder;
final Widget editor;
final GlobalKey<ScaffoldState> scaffoldKey;
final Widget navigationDrawer;
@override
State<DesktopWorkspaceShell> createState() => _DesktopWorkspaceShellState();
}
class _DesktopWorkspaceShellState extends State<DesktopWorkspaceShell> {
double? get _agentWidth => widget.controller.agentWidth;
bool get _editorCollapsedByAgent => widget.controller.editorCollapsedByAgent;
@override
void initState() {
super.initState();
widget.controller.addListener(_changed);
}
void _changed() => setState(() {});
@override
void didUpdateWidget(covariant DesktopWorkspaceShell oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
oldWidget.controller.removeListener(_changed);
widget.controller.addListener(_changed);
}
}
@override
void dispose() {
widget.controller.removeListener(_changed);
super.dispose();
}
double? _sidebarDragStart;
double _sidebarDragWidth = 0;
double? _agentDragStart;
double _agentDragWidth = 0;
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final width = constraints.maxWidth;
final geometry = DesktopWorkspaceGeometry.resolve(
width: width,
mode: widget.mode,
sidebarCollapsed: widget.sidebarCollapsed,
sidebarWidth: widget.sidebarWidth,
agentWidth: _agentWidth,
editorCollapsedByAgent: _editorCollapsedByAgent,
);
final navigationSpace = widget.sidebarCollapsed
? 0.0
: geometry.sidebarWidth;
void expandEditor() {
final collapseNavigation = width - navigationSpace - 1 < 780;
if (collapseNavigation) widget.onSidebarCollapsedChanged(true);
widget.controller.setSplit(
width -
(collapseNavigation ? 0 : navigationSpace) -
DesktopWorkspaceGeometry.editorRestoreWidth -
1,
editorCollapsed: false,
);
}
return Scaffold(
key: widget.scaffoldKey,
drawer: Drawer(
width: 320,
child: SafeArea(child: widget.navigationDrawer),
),
body: Stack(
key: const Key('desktop-workspace-shell'),
fit: StackFit.expand,
children: [
Row(
children: [
if (!widget.sidebarCollapsed ||
widget.mode == WorkspaceMode.agent)
SizedBox(
width: navigationSpace + geometry.agentWidth,
child: widget.sidebarBuilder(geometry, expandEditor),
),
if (!widget.sidebarCollapsed && !geometry.editorHidden)
SizedBox(
width: 1,
height: double.infinity,
child: ColoredBox(
key: const Key('project-sidebar-separator'),
color: AppTheme.sidebarDividerColor(context),
),
),
Expanded(
child: Offstage(
key: const Key('editor-auto-collapse'),
offstage: geometry.editorHidden,
child: TickerMode(
enabled: !geometry.editorHidden,
child: OverflowBox(
alignment: Alignment.topLeft,
minWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth
: null,
maxWidth: geometry.editorHidden
? DesktopWorkspaceGeometry.editorRestoreWidth
: null,
child: WindowHeaderPane(
offset: Offset(
navigationSpace +
geometry.agentWidth +
(!widget.sidebarCollapsed &&
!geometry.editorHidden
? 1
: 0),
0,
),
child: widget.editor,
),
),
),
),
),
],
),
if (!widget.sidebarCollapsed)
Positioned(
key: const Key('project-sidebar-divider'),
top: AppControlSize.panelHeader,
bottom: 0,
left: geometry.sidebarWidth - 4,
width: 8,
child: MouseRegion(
cursor: SystemMouseCursors.resizeColumn,
child: GestureDetector(
key: const Key('project-sidebar-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: (details) {
_sidebarDragStart = details.globalPosition.dx;
_sidebarDragWidth = geometry.sidebarWidth;
},
onHorizontalDragUpdate: (details) {
final start = _sidebarDragStart;
if (start == null) return;
widget.onSidebarWidthChanged(
(_sidebarDragWidth + details.globalPosition.dx - start)
.clamp(
WorkspaceLayoutMetrics.sidebarMinimumWidth,
DesktopWorkspaceGeometry.sidebarMaximum(
width,
widget.mode,
),
)
.toDouble(),
);
},
onHorizontalDragEnd: (_) => _sidebarDragStart = null,
onHorizontalDragCancel: () => _sidebarDragStart = null,
child: const SizedBox.expand(),
),
),
),
if (widget.mode == WorkspaceMode.agent &&
width - navigationSpace - 1 >= 220)
Positioned(
top: 0,
bottom: 0,
left:
navigationSpace +
geometry.agentWidth -
(geometry.editorHidden ? 8 : 4),
width: 8,
child: MouseRegion(
cursor: SystemMouseCursors.resizeColumn,
child: GestureDetector(
key: const Key('agent-panel-resize'),
behavior: HitTestBehavior.opaque,
dragStartBehavior: DragStartBehavior.down,
onHorizontalDragStart: (details) {
_agentDragStart = details.globalPosition.dx;
_agentDragWidth = geometry.agentWidth;
},
onHorizontalDragUpdate: (details) {
final start = _agentDragStart;
if (start == null) return;
final agentWidth =
(_agentDragWidth + details.globalPosition.dx - start)
.clamp(220.0, width - navigationSpace - 1);
final remaining =
width - navigationSpace - agentWidth - 1;
widget.controller.setSplit(
agentWidth,
editorCollapsed: geometry.editorHidden
? remaining <
DesktopWorkspaceGeometry.editorRestoreWidth
: remaining <=
DesktopWorkspaceGeometry.editorCollapseWidth -
DesktopWorkspaceGeometry
.editorCollapseDragBuffer,
);
},
onHorizontalDragEnd: (_) {
_agentDragStart = null;
if (!_editorCollapsedByAgent &&
_agentWidth != null &&
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1 >=
220) {
widget.controller.setSplit(
_agentWidth!.clamp(
220.0,
width -
navigationSpace -
DesktopWorkspaceGeometry.editorCollapseWidth -
1,
),
editorCollapsed: false,
);
}
},
onHorizontalDragCancel: () => _agentDragStart = null,
child: const SizedBox.expand(),
),
),
),
],
),
);
},
);
}
+58
View File
@@ -0,0 +1,58 @@
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/workspace_mode.dart';
import 'workspace_frame.dart';
/// A focused surface; hidden features keep their state in workspace controllers.
class PhoneWorkspaceShell extends StatelessWidget {
const PhoneWorkspaceShell({
super.key,
required this.mode,
required this.onModeChanged,
required this.navigation,
required this.headerActions,
required this.title,
required this.integratedTitlebar,
required this.agent,
required this.editor,
});
final WorkspaceMode mode;
final ValueChanged<WorkspaceMode> onModeChanged;
final Widget navigation;
final Widget headerActions;
final String title;
final bool integratedTitlebar;
final Widget agent;
final Widget editor;
@override
Widget build(BuildContext context) => WorkspaceFrame(
key: const Key('phone-workspace-shell'),
navigation: navigation,
headerActions: headerActions,
title: title,
integratedTitlebar: integratedTitlebar,
bottomNavigationBar: NavigationBar(
height: 64,
selectedIndex: mode == WorkspaceMode.agent ? 0 : 1,
onDestinationSelected: (index) =>
onModeChanged(index == 0 ? WorkspaceMode.agent : WorkspaceMode.cut),
destinations: [
NavigationDestination(
key: const Key('workspace-agent-destination'),
icon: const Icon(Icons.chat_bubble_outline),
label: context.l10n.workspaceAgent,
),
NavigationDestination(
key: const Key('workspace-cut-destination'),
icon: const Icon(Icons.movie_outlined),
label: context.l10n.workspaceCut,
),
],
),
child: mode == WorkspaceMode.agent ? agent : editor,
);
}
@@ -0,0 +1,99 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/workspace_mode.dart';
import '../adaptive/workspace_layout_policy.dart';
import 'workspace_frame.dart';
/// Two working surfaces when space permits, with project navigation on demand.
class TabletWorkspaceShell extends StatelessWidget {
const TabletWorkspaceShell({
super.key,
required this.mode,
required this.onModeChanged,
required this.navigation,
required this.headerActions,
required this.title,
required this.integratedTitlebar,
required this.agent,
required this.editor,
});
final WorkspaceMode mode;
final ValueChanged<WorkspaceMode> onModeChanged;
final Widget navigation;
final Widget headerActions;
final String title;
final bool integratedTitlebar;
final Widget agent;
final Widget editor;
@override
Widget build(BuildContext context) => WorkspaceFrame(
key: const Key('tablet-workspace-shell'),
navigation: navigation,
headerActions: headerActions,
title: title,
integratedTitlebar: integratedTitlebar,
child: Row(
children: [
SizedBox(
width: 72,
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
child: SizedBox(
height: math.max(240, constraints.maxHeight),
child: NavigationRail(
selectedIndex: mode == WorkspaceMode.agent ? 0 : 1,
labelType: NavigationRailLabelType.all,
onDestinationSelected: (index) => onModeChanged(
index == 0 ? WorkspaceMode.agent : WorkspaceMode.cut,
),
destinations: [
NavigationRailDestination(
icon: const Icon(
Icons.chat_bubble_outline,
key: Key('workspace-agent-destination'),
),
label: Text(context.l10n.workspaceAgent),
),
NavigationRailDestination(
icon: const Icon(
Icons.movie_outlined,
key: Key('workspace-cut-destination'),
),
label: Text(context.l10n.workspaceCut),
),
],
),
),
),
),
),
const VerticalDivider(width: 1),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) =>
mode == WorkspaceMode.agent &&
WorkspaceLayoutPolicy.showAgentBesideEditor(
constraints.maxWidth,
)
? Row(
children: [
SizedBox(width: constraints.maxWidth * .38, child: agent),
const VerticalDivider(width: 1),
Expanded(child: editor),
],
)
: mode == WorkspaceMode.agent
? agent
: editor,
),
),
],
),
);
}
+70
View File
@@ -0,0 +1,70 @@
import 'package:flutter/material.dart';
import '../../integrations/platform/editor_window_chrome.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../../l10n/l10n.dart';
/// Navigation and mode controls for bounded workspaces. Drawer visibility is
/// local presentation state and never overwrites the desktop sidebar preference.
class WorkspaceFrame extends StatelessWidget {
const WorkspaceFrame({
super.key,
required this.navigation,
required this.headerActions,
required this.title,
required this.integratedTitlebar,
required this.child,
this.bottomNavigationBar,
});
final Widget navigation;
final Widget headerActions;
final String title;
final bool integratedTitlebar;
final Widget child;
final Widget? bottomNavigationBar;
@override
Widget build(BuildContext context) => Scaffold(
drawer: Drawer(width: 320, child: SafeArea(child: navigation)),
body: Column(
children: [
SizedBox(
key: const Key('workspace-window-header'),
height: 48,
child: WindowHeaderPadding(
child: Row(
children: [
if (integratedTitlebar)
SizedBox(width: EditorWindowChrome.leadingWidth),
HeaderControlRegion(
child: Builder(
builder: (context) => IconButton(
key: const Key('workspace-navigation-button'),
tooltip: context.l10n.expandSidebar,
onPressed: () => Scaffold.of(context).openDrawer(),
icon: const Icon(Icons.menu),
),
),
),
Expanded(
child: Text(
title,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
headerActions,
],
),
),
),
const Divider(height: 1),
Expanded(child: child),
],
),
bottomNavigationBar: bottomNavigationBar,
);
}
@@ -0,0 +1,139 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:flutter/scheduler.dart';
import 'package:uuid/uuid.dart';
import 'package:path/path.dart' as p;
import 'request_report.dart';
import 'app_diagnostics.dart';
import 'diagnostic_redactor.dart';
/// Per-send measurements; never retains prompts, results, or credentials.
class AgentRequestDiagnostics {
AgentRequestDiagnostics({String? requestId})
: requestId = requestId ?? const Uuid().v4() {
SchedulerBinding.instance.addTimingsCallback(_frames);
_timer = Timer.periodic(const Duration(milliseconds: 200), (_) {
final now = _clock.elapsedMicroseconds;
maxTimerDelayUs = max(maxTimerDelayUs, now - _lastTickUs - 200000);
_lastTickUs = now;
});
}
final _clock = Stopwatch()..start();
final String requestId;
late final Timer _timer;
int _lastTickUs = 0;
int frameCount = 0;
int slowFrames = 0;
int maxBuildUs = 0;
int maxRasterUs = 0;
int maxTimerDelayUs = 0;
int? preparationUs;
String outcome = 'error';
final List<Map<String, Object?>> runs = [];
void prepared() => preparationUs = _clock.elapsedMicroseconds;
void _frames(List<FrameTiming> frames) {
for (final frame in frames) {
frameCount++;
final build = frame.buildDuration.inMicroseconds;
final raster = frame.rasterDuration.inMicroseconds;
maxBuildUs = max(maxBuildUs, build);
maxRasterUs = max(maxRasterUs, raster);
if (build > 16667 || raster > 16667) slowFrames++;
}
}
RequestReport stop() {
maxTimerDelayUs = max(
maxTimerDelayUs,
_clock.elapsedMicroseconds - _lastTickUs - 200000,
);
_timer.cancel();
SchedulerBinding.instance.removeTimingsCallback(_frames);
_clock.stop();
return RequestReport(
requestId: requestId,
sessionId: AppDiagnostics.instance?.sessionId,
outcome: outcome,
elapsedUs: _clock.elapsedMicroseconds,
preparationUs: preparationUs,
frames: RequestFrameReport(
count: frameCount,
slowFrames: slowFrames,
maxBuildUs: maxBuildUs,
maxRasterUs: maxRasterUs,
maxTimerDelayUs: maxTimerDelayUs,
),
runs: List.of(runs),
);
}
/// Keeps the latest 20 reports, serializing publication and pruning.
/// Best effort: storage failures never prevent the next edit.
static Future<void> _writes = Future.value();
static Future<void> persist(Directory root, RequestReport report) {
final write = _writes.then((_) async {
try {
final directory = Directory(p.join(root.path, 'diagnostics'));
await directory.create(recursive: true);
final now = DateTime.now().toUtc();
final suppliedId = report.requestId;
final requestId =
suppliedId != null &&
RegExp(r'^[a-fA-F0-9-]{36}$').hasMatch(suppliedId)
? suppliedId
: const Uuid().v4();
final file = File(
p.join(
directory.path,
'request-${now.microsecondsSinceEpoch}-$requestId.json',
),
);
final temporary = File('${file.path}.tmp');
final encoded = jsonEncode(
DiagnosticRedactor().value(report.copyWith(at: now).toJson()),
);
if (utf8.encode(encoded).length > 256 * 1024) return;
await temporary.writeAsString(encoded, flush: true);
await temporary.rename(file.path);
final files = await directory
.list()
.where(
(e) =>
e is File &&
p.basename(e.path).startsWith('request-') &&
e.path.endsWith('.json'),
)
.cast<File>()
.toList();
final dated = <(File, DateTime)>[];
for (final file in files) {
dated.add((file, (await file.stat()).modified));
}
dated.sort((a, b) => a.$2.compareTo(b.$2));
if (dated.length > 20) {
for (final entry in dated.take(dated.length - 20)) {
await entry.$1.delete();
}
}
} catch (error, stack) {
AppDiagnostics.failure(
'agent',
'persistRequestReport',
error,
stack,
context: {'requestId': report.requestId},
);
// Disk and encoding failures must not affect the conversation.
}
});
_writes = write;
return write;
}
}
+215
View File
@@ -0,0 +1,215 @@
import 'dart:async';
import 'dart:io';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_native/cutdex_native.dart';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import 'package:path_provider/path_provider.dart';
import 'package:uuid/uuid.dart';
import 'diagnostic_store.dart';
import 'request_report.dart';
/// Application-owned storage and SDK adapter. Inactive unless explicitly installed.
final class AppDiagnostics {
AppDiagnostics(
this.store, {
String? sessionId,
Map<String, Object?> metadata = const {},
}) : sessionId = sessionId ?? const Uuid().v4(),
metadata = Map.of(metadata);
static AppDiagnostics? instance;
final DiagnosticStore store;
final String sessionId;
final Map<String, Object?> metadata;
static Future<AppDiagnostics> initialize() async {
Directory directory;
Object? initializationFailure;
StackTrace? initializationStack;
try {
directory = Directory(
p.join(
(await getApplicationSupportDirectory()).path,
'Cutdex',
'Diagnostics',
),
);
} catch (error, stack) {
initializationFailure = error;
initializationStack = stack;
// Use temporary storage when support-directory discovery is unavailable.
directory = Directory(
p.join(Directory.systemTemp.path, 'Cutdex', 'Diagnostics'),
);
}
final diagnostics = AppDiagnostics(
DiagnosticStore(directory),
metadata: {
'platform': Platform.operatingSystem,
'osVersion': Platform.operatingSystemVersion,
'dartVersion': Platform.version,
'buildMode': kReleaseMode
? 'release'
: kProfileMode
? 'profile'
: 'debug',
'appVersion': const String.fromEnvironment(
'CUTDEX_APP_VERSION',
defaultValue: 'unknown',
),
'appBuild': const String.fromEnvironment(
'CUTDEX_APP_BUILD',
defaultValue: 'unknown',
),
},
);
instance = diagnostics;
diagnostics.event(
const DiagnosticEvent(
component: 'app',
operation: 'start',
level: DiagnosticSeverity.info,
),
);
if (initializationFailure != null) {
diagnostics.event(
DiagnosticEvent(
component: 'diagnostics',
operation: 'initialize',
error: initializationFailure,
stackTrace: initializationStack,
),
);
}
return diagnostics;
}
static void report(DiagnosticEvent event) => instance?.event(event);
static void failure(
String component,
String operation,
Object error,
StackTrace stack, {
Map<String, Object?> context = const {},
}) => reportDiagnostic(
report,
DiagnosticEvent(
component: component,
operation: operation,
error: error,
stackTrace: stack,
context: context,
),
);
void event(DiagnosticEvent event, {bool immediate = false}) {
try {
final error = event.error;
store.record({
'version': 1,
'at': DateTime.now().toUtc().toIso8601String(),
'sessionId': sessionId,
'environment': metadata,
'level': event.level.name,
'component': event.component,
'operation': event.operation,
if (error != null)
'error': {
'type': error.runtimeType.toString(),
'message': switch (error) {
FormatException() => 'FormatException: ${error.message}',
ArgumentError() =>
'ArgumentError(${error.name}): ${error.message}',
ProcessException() =>
'ProcessException: ${error.message} (${error.errorCode})',
_ => error.toString(),
},
if (error is RuntimeException) ...{
'code': error.code,
'domain': error.domain,
'retryable': error.retryable,
'nativeDetails': error.details,
},
if (error is ProcessingException) ...{
'code': error.code,
'backend': error.backend,
},
},
if (event.stackTrace != null) 'stackTrace': event.stackTrace.toString(),
'context': event.context,
}, immediate: immediate);
} catch (_) {
// Diagnostics cannot change the application failure path.
}
}
Future<void> request(RequestReport report, String requestId) =>
store.saveRequest({
...report.copyWith(at: report.at ?? DateTime.now().toUtc()).toJson(),
'requestId': requestId,
'sessionId': sessionId,
}, requestId);
Future<File> export(Directory destination) =>
store.export(destination, {...metadata, 'sessionId': sessionId});
Future<void> readApplicationInfo() async {
try {
metadata.addAll(
await NativeDeviceInfo.readApplicationInfo().timeout(
const Duration(seconds: 2),
),
);
event(
const DiagnosticEvent(
component: 'app',
operation: 'applicationInfo',
level: DiagnosticSeverity.info,
),
);
} catch (error, stack) {
event(
DiagnosticEvent(
component: 'diagnostics',
operation: 'applicationInfo',
error: error,
stackTrace: stack,
level: DiagnosticSeverity.warning,
),
);
}
}
/// Preserves framework/engine behavior while observing both error routes.
void installErrorHandlers() {
final previousFlutter = FlutterError.onError;
FlutterError.onError = (details) {
event(
DiagnosticEvent(
component: 'flutter',
operation: 'frameworkError',
error: details.exception,
stackTrace: details.stack,
context: {'library': details.library},
),
);
if (previousFlutter != null) previousFlutter(details);
};
final previousPlatform = PlatformDispatcher.instance.onError;
PlatformDispatcher.instance.onError = (error, stack) {
event(
DiagnosticEvent(
component: 'dart',
operation: 'uncaughtAsyncError',
error: error,
stackTrace: stack,
),
immediate: true,
);
return previousPlatform?.call(error, stack) ?? false;
};
}
}
+76
View File
@@ -0,0 +1,76 @@
/// Sanitizes diagnostic values before they reach memory, disk or an export.
final class DiagnosticRedactor {
static final _privateKey = RegExp(
r'^(authorization|cookies?|password|secret|(?:access|refresh|auth)?[_-]?token|credential(?:Id)?|api.?key|prompt|messages|responseBody|requestBody)$',
caseSensitive: false,
);
static final _bearer = RegExp(
r'\bBearer\s+[^\s,;"\x27]+',
caseSensitive: false,
);
static final _apiKey = RegExp(r'\bsk-[a-zA-Z0-9_-]+');
static final _assignment = RegExp(
r'\b(api[_-]?key|access[_-]?token|password|secret|authorization)\s*[:=]\s*[^\r\n,;]+',
caseSensitive: false,
);
static final _url = RegExp(r'https?://[^\s<>"\x27]+');
static final _path = RegExp(
r'(?:file://)?/(?:Users|home|private|tmp|var|Volumes|storage|data|mnt|media|sdcard|Documents)/[^\r\n"\x27,;]*|[A-Za-z]:[\\/][^\r\n"\x27,;]*|\\\\[^\r\n"\x27,;]+',
);
static final _email = RegExp(r'\b[^\s@]+@[^\s@]+\.[a-zA-Z]{2,}\b');
String text(String value, {int limit = 8192}) {
var result = value;
// Most metadata consists of identifiers. Avoid expensive pattern scans when
// their required marker is absent; matching and redaction stay unchanged.
if (result.toLowerCase().contains('bearer')) {
result = result.replaceAll(_bearer, 'Bearer [redacted]');
}
if (result.contains('sk-')) {
result = result.replaceAll(_apiKey, '[redacted]');
}
if (result.contains(':') || result.contains('=')) {
result = result.replaceAllMapped(
_assignment,
(m) => '${m[1]}=[redacted]',
);
}
if (result.contains('http://') || result.contains('https://')) {
result = result.replaceAllMapped(_url, (m) {
final uri = Uri.tryParse(m[0]!);
return uri == null ? '[url]' : '${uri.scheme}://${uri.host}/[redacted]';
});
}
if (result.contains('/') || result.contains(r'\')) {
result = result.replaceAll(_path, '[local-path]');
}
if (result.contains('@')) {
result = result.replaceAll(_email, '[email]');
}
if (result.length > limit) {
result = '${result.substring(0, limit)}…[truncated]';
}
return result;
}
Object? value(Object? input, {int depth = 0}) {
if (depth > 8) return '[truncated]';
if (input == null || input is bool || input is num) return input;
if (input is String) return text(input);
if (input is Map) {
return <String, Object?>{
for (final entry in input.entries.take(64))
text(
entry.key.toString(),
limit: 128,
): _privateKey.hasMatch(entry.key.toString())
? '[redacted]'
: value(entry.value, depth: depth + 1),
};
}
if (input is Iterable) {
return input.take(2048).map((v) => value(v, depth: depth + 1)).toList();
}
return text(input.toString());
}
}
+353
View File
@@ -0,0 +1,353 @@
import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:path/path.dart' as p;
import 'diagnostic_redactor.dart';
/// Serializes bounded log writes, rotation and exports; failures remain observable
/// in memory without interrupting editing or recursively logging themselves.
final class DiagnosticStore {
DiagnosticStore(
this.directory, {
this.maxFileBytes = 512 * 1024,
this.fileCount = 5,
this.maxPending = 256,
this.flushInterval = const Duration(milliseconds: 250),
this.batchSize = 32,
this.maxBatchBytes = 64 * 1024,
this.maxPendingBytes = 1024 * 1024,
int? errorReserveRecords,
int? errorReserveBytes,
}) : errorReserveRecords = errorReserveRecords ?? maxPending ~/ 8,
errorReserveBytes = errorReserveBytes ?? maxPendingBytes ~/ 4,
assert(
errorReserveRecords == null ||
(errorReserveRecords >= 0 && errorReserveRecords < maxPending),
),
assert(
errorReserveBytes == null ||
(errorReserveBytes >= 0 && errorReserveBytes < maxPendingBytes),
),
assert(maxFileBytes >= 1024),
assert(fileCount > 0),
assert(maxPending > 0),
assert(flushInterval > Duration.zero),
assert(batchSize > 0),
assert(maxBatchBytes > 0),
assert(maxPendingBytes > 0);
final Directory directory;
final int maxFileBytes, fileCount, maxPending;
final Duration flushInterval;
final int batchSize, maxBatchBytes, maxPendingBytes;
final int errorReserveRecords, errorReserveBytes;
final _buffer = Queue<_DiagnosticRecord>();
Timer? _timer;
int _bufferBytes = 0;
int _pendingBytes = 0;
int eventWriteBatches = 0;
int eventFlushes = 0;
int eventBytesWritten = 0;
int get pendingRecords => _pending;
int get pendingEventBytes => _pendingBytes;
final _redactor = DiagnosticRedactor();
Future<void> _tail = Future.value();
int _pending = 0;
int dropped = 0;
int droppedErrors = 0;
int writeFailures = 0;
String? lastWriteFailure;
final List<Map<String, Object?>> _fallback = [];
File _log(int index) => File(p.join(directory.path, 'events-$index.jsonl'));
void record(Map<String, Object?> record, {bool immediate = false}) {
final isError = record['level'] == 'error';
final recordLimit = isError ? maxPending : maxPending - errorReserveRecords;
final byteLimit = isError
? maxPendingBytes
: maxPendingBytes - errorReserveBytes;
// Non-error events and reports cannot consume reserved error capacity.
// Saturated queues skip formatting; fatal errors bypass both limits.
if (!immediate && (_pending >= recordLimit || _pendingBytes >= byteLimit)) {
_drop(isError);
return;
}
try {
final safe = (_redactor.value(record)! as Map).cast<String, Object?>();
final encoded = utf8.encode('${jsonEncode(safe)}\n');
if (encoded.length > maxFileBytes) {
_drop(isError);
return;
}
if (immediate) {
try {
directory.createSync(recursive: true);
final fatal = File(p.join(directory.path, 'fatal.jsonl'));
if (fatal.existsSync() &&
fatal.lengthSync() + encoded.length > maxFileBytes) {
fatal.deleteSync();
}
fatal.writeAsBytesSync(encoded, mode: FileMode.append, flush: true);
} catch (error) {
_failed([_DiagnosticRecord(safe, encoded)], error);
}
return;
}
if (_pendingBytes + encoded.length > byteLimit) {
_drop(isError);
return;
}
_pending++;
_pendingBytes += encoded.length;
_bufferBytes += encoded.length;
_buffer.add(_DiagnosticRecord(safe, encoded));
if (_buffer.length >= batchSize || _bufferBytes >= maxBatchBytes) {
_enqueueBuffered();
} else {
_timer ??= Timer(flushInterval, _enqueueBuffered);
}
} catch (_) {
_drop(isError);
}
}
void _drop(bool isError) {
dropped++;
if (isError) droppedErrors++;
}
void _enqueueBuffered() {
_timer?.cancel();
_timer = null;
if (_buffer.isEmpty) return;
final records = _buffer.toList(growable: false);
_buffer.clear();
_bufferBytes = 0;
_tail = _tail.then((_) => _writeBatch(records));
}
Future<void> _writeBatch(List<_DiagnosticRecord> records) async {
eventWriteBatches++;
var written = 0;
try {
await directory.create(recursive: true);
while (written < records.length) {
final current = _log(0);
var length = 0;
var interrupted = false;
if (await current.exists()) {
final reader = await current.open();
try {
length = await reader.length();
if (length > 0) {
await reader.setPosition(length - 1);
interrupted = await reader.readByte() != 10;
}
} finally {
await reader.close();
}
}
if (length + (interrupted ? 1 : 0) + records[written].encoded.length >
maxFileBytes) {
await _rotate();
length = 0;
interrupted = false;
}
final bytes = BytesBuilder(copy: false);
// Isolate an interrupted append from the next complete JSONL record.
if (interrupted) bytes.addByte(10);
var end = written;
while (end < records.length) {
final encoded = records[end].encoded;
if (length + bytes.length + encoded.length > maxFileBytes ||
(end > written &&
bytes.length + encoded.length > maxBatchBytes)) {
break;
}
bytes.add(encoded);
end++;
}
final chunk = bytes.takeBytes();
await current.writeAsBytes(chunk, mode: FileMode.append, flush: true);
eventFlushes++;
eventBytesWritten += chunk.length;
written = end;
}
} catch (error) {
// A failed batch retains every unconfirmed record, with bounded fallback.
_failed(records.skip(written), error);
} finally {
_pending -= records.length;
_pendingBytes -= records.fold(
0,
(size, record) => size + record.encoded.length,
);
}
}
Future<void> _rotate() async {
final oldest = _log(fileCount - 1);
if (await oldest.exists()) await oldest.delete();
for (var i = fileCount - 2; i >= 0; i--) {
final file = _log(i);
if (await file.exists()) await file.rename(_log(i + 1).path);
}
}
void _failed(Iterable<_DiagnosticRecord> records, Object error) {
lastWriteFailure = _redactor.text(error.toString());
for (final record in records) {
writeFailures++;
_fallback.add(record.safe);
if (_fallback.length > 100) _fallback.removeAt(0);
}
}
/// Drains buffered records and waits for writes already accepted by the store.
Future<void> flush() {
_enqueueBuffered();
return _tail;
}
Future<void> saveRequest(Map<String, Object?> report, String requestId) {
// UUID-only names prevent user text or paths from choosing a destination.
if (!RegExp(r'^[a-fA-F0-9-]{36}$').hasMatch(requestId)) {
return Future.value();
}
if (_pending >= maxPending - errorReserveRecords) {
dropped++;
return Future.value();
}
_enqueueBuffered();
_pending++;
final operation = _tail.then((_) async {
final requests = Directory(p.join(directory.path, 'requests'));
try {
await requests.create(recursive: true);
final safe = _redactor.value(report);
final encoded = jsonEncode(safe);
if (utf8.encode(encoded).length > 256 * 1024) {
dropped++;
return;
}
final file = File(
p.join(
requests.path,
'${DateTime.now().toUtc().microsecondsSinceEpoch}-$requestId.json',
),
);
final temporary = File('${file.path}.tmp');
await temporary.writeAsString(encoded, flush: true);
await temporary.rename(file.path);
final files = await requests
.list()
.where((e) => e is File && e.path.endsWith('.json'))
.cast<File>()
.toList();
files.sort((a, b) => a.path.compareTo(b.path));
if (files.length > 20) {
for (final old in files.take(files.length - 20)) {
await old.delete();
}
}
} catch (error) {
writeFailures++;
lastWriteFailure = _redactor.text(error.toString());
} finally {
_pending--;
}
});
_tail = operation;
return operation;
}
/// Exports only managed diagnostics, never project files or conversations.
Future<File> export(Directory destination, Map<String, Object?> metadata) {
_enqueueBuffered();
final completion = Completer<File>();
_tail = _tail.then((_) async {
try {
final records = <Object?>[];
final logs = [
for (var i = fileCount - 1; i >= 0; i--) _log(i),
File(p.join(directory.path, 'fatal.jsonl')),
];
for (final file in logs) {
if (!await file.exists() || await file.length() > maxFileBytes) {
continue;
}
for (final line in await file.readAsLines()) {
try {
records.add(_redactor.value(jsonDecode(line)));
} catch (_) {
// An interrupted append must not prevent exporting other records.
}
}
}
final reports = <Object?>[];
final requests = Directory(p.join(directory.path, 'requests'));
if (await requests.exists()) {
final files = await requests
.list()
.where((e) => e is File && e.path.endsWith('.json'))
.cast<File>()
.toList();
files.sort((a, b) => b.path.compareTo(a.path));
for (final file in files.take(20)) {
if (await file.length() > 256 * 1024) continue;
try {
reports.add(
_redactor.value(jsonDecode(await file.readAsString())),
);
} catch (_) {}
}
}
await destination.create(recursive: true);
final file = File(
p.join(
destination.path,
'cutdex-diagnostics-${DateTime.now().toUtc().microsecondsSinceEpoch}.json',
),
);
final temporary = File('${file.path}.tmp');
await temporary.writeAsString(
jsonEncode({
'version': 1,
'exportedAt': DateTime.now().toUtc().toIso8601String(),
'metadata': _redactor.value(metadata),
'storage': {
'dropped': dropped,
'droppedErrors': droppedErrors,
'errorReserveRecords': errorReserveRecords,
'errorReserveBytes': errorReserveBytes,
'writeFailures': writeFailures,
'eventWriteBatches': eventWriteBatches,
'eventFlushes': eventFlushes,
'eventBytesWritten': eventBytesWritten,
'lastWriteFailure': lastWriteFailure,
},
'events': records,
'requests': reports,
'fallbackEvents': _fallback,
}),
flush: true,
);
await temporary.rename(file.path);
completion.complete(file);
} catch (error, stack) {
completion.completeError(error, stack);
}
});
return completion.future;
}
}
final class _DiagnosticRecord {
const _DiagnosticRecord(this.safe, this.encoded);
final Map<String, Object?> safe;
final List<int> encoded;
}
+53
View File
@@ -0,0 +1,53 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:ui';
import 'package:flutter/scheduler.dart';
/// Opt-in real-engine timings. No callbacks or I/O in ordinary app launches.
/// Set CUTDEX_FRAME_TIMINGS to a JSONL output path before launching the app.
void recordFrameTimingsFromEnvironment() {
final path = Platform.environment['CUTDEX_FRAME_TIMINGS'];
if (path == null || path.isEmpty) return;
final pending = <List<int>>[];
var writing = false;
var dropped = 0;
SchedulerBinding.instance.addTimingsCallback((frames) {
for (final frame in frames) {
if (pending.length >= 2048) {
dropped++;
continue;
}
pending.add([
frame.timestampInMicroseconds(FramePhase.vsyncStart),
frame.buildDuration.inMicroseconds,
frame.rasterDuration.inMicroseconds,
frame.totalSpan.inMicroseconds,
]);
}
});
Timer.periodic(const Duration(seconds: 2), (_) async {
if (writing || pending.isEmpty) return;
writing = true;
final batch = List<List<int>>.of(pending);
pending.clear();
final lost = dropped;
dropped = 0;
try {
await File(path).writeAsString(
'${jsonEncode({
'at': DateTime.now().toUtc().toIso8601String(),
'columns': ['vsyncUs', 'buildUs', 'rasterUs', 'totalUs'],
'dropped': lost,
'frames': batch,
})}\n',
mode: FileMode.append,
);
} on FileSystemException {
// Diagnostics must never interrupt editing (e.g. an unavailable drive).
} finally {
writing = false;
}
});
}
+34
View File
@@ -0,0 +1,34 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'request_report.freezed.dart';
part 'request_report.g.dart';
@freezed
abstract class RequestFrameReport with _$RequestFrameReport {
const factory RequestFrameReport({
required int count,
@JsonKey(name: 'over16ms') required int slowFrames,
required int maxBuildUs,
required int maxRasterUs,
required int maxTimerDelayUs,
}) = _RequestFrameReport;
factory RequestFrameReport.fromJson(Map<String, Object?> json) =>
_$RequestFrameReportFromJson(json);
}
@freezed
abstract class RequestReport with _$RequestReport {
const factory RequestReport({
@Default(1) int version,
required String outcome,
required int elapsedUs,
int? preparationUs,
required RequestFrameReport frames,
required List<Map<String, Object?>> runs,
@JsonKey(includeIfNull: false) DateTime? at,
@JsonKey(includeIfNull: false) String? requestId,
@JsonKey(includeIfNull: false) String? sessionId,
}) = _RequestReport;
factory RequestReport.fromJson(Map<String, Object?> json) =>
_$RequestReportFromJson(json);
}
File diff suppressed because it is too large. Load diff
+55
View File
@@ -0,0 +1,55 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'request_report.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
_RequestFrameReport _$RequestFrameReportFromJson(Map<String, dynamic> json) =>
_RequestFrameReport(
count: (json['count'] as num).toInt(),
slowFrames: (json['over16ms'] as num).toInt(),
maxBuildUs: (json['maxBuildUs'] as num).toInt(),
maxRasterUs: (json['maxRasterUs'] as num).toInt(),
maxTimerDelayUs: (json['maxTimerDelayUs'] as num).toInt(),
);
Map<String, dynamic> _$RequestFrameReportToJson(_RequestFrameReport instance) =>
<String, dynamic>{
'count': instance.count,
'over16ms': instance.slowFrames,
'maxBuildUs': instance.maxBuildUs,
'maxRasterUs': instance.maxRasterUs,
'maxTimerDelayUs': instance.maxTimerDelayUs,
};
_RequestReport _$RequestReportFromJson(Map<String, dynamic> json) =>
_RequestReport(
version: (json['version'] as num?)?.toInt() ?? 1,
outcome: json['outcome'] as String,
elapsedUs: (json['elapsedUs'] as num).toInt(),
preparationUs: (json['preparationUs'] as num?)?.toInt(),
frames: RequestFrameReport.fromJson(
json['frames'] as Map<String, dynamic>,
),
runs: (json['runs'] as List<dynamic>)
.map((e) => e as Map<String, dynamic>)
.toList(),
at: json['at'] == null ? null : DateTime.parse(json['at'] as String),
requestId: json['requestId'] as String?,
sessionId: json['sessionId'] as String?,
);
Map<String, dynamic> _$RequestReportToJson(_RequestReport instance) =>
<String, dynamic>{
'version': instance.version,
'outcome': instance.outcome,
'elapsedUs': instance.elapsedUs,
'preparationUs': instance.preparationUs,
'frames': instance.frames.toJson(),
'runs': instance.runs,
'at': ?instance.at?.toIso8601String(),
'requestId': ?instance.requestId,
'sessionId': ?instance.sessionId,
};
+103
View File
@@ -0,0 +1,103 @@
/// Stable application error identities; independent of interface language.
enum AppErrorCode {
operationFailed,
agentRestartHint,
loadRecentProjectsFailed,
loadProjectsFailed,
projectAccessFailed,
projectLocationNotWritable,
projectLocationUnavailable,
projectLocationCreateFailed,
projectMissingDirectory,
recentProjectSaveFailed,
lastProjectSaveFailed,
enterProjectName,
projectSwitched,
notLocalMedia,
revealMediaFailed,
openMatchingProject,
openTimelineFailed,
projectMismatch,
openProjectFirst,
localFilesOnly,
foldersUnsupported,
mediaImportCancelled,
fileAccessFailed,
registerMediaFailed,
mediaNoLongerExists,
mediaNoTracks,
invalidMediaDuration,
mediaInfoUnsupported,
mediaInfoFailed,
saveTimelineFailed,
projectNameInvalid,
projectLocationDefaultUnavailable,
chooseProjectLocation,
timelineMissing,
timelineInUse,
timelineHasBackgroundTasks,
timelineRequired,
projectSessionClosed,
timelineSessionClosed,
mediaReadFailed,
mediaImportFailed,
unsupportedMediaType,
mediaNoVideoTracks,
mediaDurationOutOfRange,
resourceChecksumFailed,
enterName,
agentLocationUnavailable,
agentLocationBusy,
startBackgroundRemovalFailed,
subtitleEngineUnavailable,
timelineChanged,
resourceDownloadHttpFailed,
diagnostic,
}
/// An error remains structured until the presentation layer chooses its wording.
final class AppFailure {
const AppFailure(this.code, {this.diagnostic, this.httpStatusCode});
final AppErrorCode code;
final String? diagnostic;
final int? httpStatusCode;
bool get requiresProjectLocation => switch (code) {
AppErrorCode.projectLocationNotWritable ||
AppErrorCode.projectLocationUnavailable ||
AppErrorCode.projectLocationCreateFailed ||
AppErrorCode.projectLocationDefaultUnavailable ||
AppErrorCode.chooseProjectLocation => true,
_ => false,
};
@override
bool operator ==(Object other) =>
other is AppFailure &&
code == other.code &&
diagnostic == other.diagnostic &&
httpStatusCode == other.httpStatusCode;
@override
int get hashCode => Object.hash(code, diagnostic, httpStatusCode);
@override
String toString() => diagnostic ?? code.name;
}
/// Keeps existing StateError catch boundaries while carrying a stable identity.
final class AppException extends StateError {
AppException(AppErrorCode code, {String? diagnostic, int? httpStatusCode})
: this.fromFailure(
AppFailure(
code,
diagnostic: diagnostic,
httpStatusCode: httpStatusCode,
),
);
AppException.fromFailure(this.failure) : super(failure.toString());
final AppFailure failure;
}
@@ -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,
],
),
),
),
);
}
}
+253
View File
@@ -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,
),
);
}
}
+46
View File
@@ -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),
);
}
}
+359
View File
@@ -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),
),
),
),
),
),
],
);
},
);
}
+134
View File
@@ -0,0 +1,134 @@
import 'dart:math' as math;
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/theme.dart';
class AudioAssetTile extends StatelessWidget {
const AudioAssetTile({
super.key,
required this.asset,
this.showName = true,
this.aspectRatio = 16 / 9,
});
final AssetDocument asset;
final bool showName;
final double aspectRatio;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AspectRatio(
key: ValueKey('audio-cover-${asset.id}'),
aspectRatio: aspectRatio,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: _AudioWaveformCover(asset),
),
),
if (showName) ...[
const SizedBox(height: AppSpacing.small),
Tooltip(
message: asset.name,
child: Text(
asset.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: theme.textTheme.bodySmall,
),
),
],
],
);
}
}
class _AudioWaveformCover extends ConsumerWidget {
const _AudioWaveformCover(this.asset);
final AssetDocument asset;
@override
Widget build(BuildContext context, WidgetRef ref) {
final waveform = ref.watch(mediaWaveformProvider(asset)).value;
final theme = Theme.of(context);
if (waveform == null) {
return Center(
child: Icon(
Icons.audio_file_outlined,
size: AppIconSize.emptyState,
color: theme.colorScheme.onSurfaceVariant,
),
);
}
return CustomPaint(
key: ValueKey('audio-waveform-${asset.id}'),
painter: _AudioCoverPainter(
waveform,
theme.extension<TimelineThemeData>()?.audioAccentColor ??
theme.colorScheme.primary,
MediaQuery.devicePixelRatioOf(context),
),
);
}
}
class _AudioCoverPainter extends CustomPainter {
const _AudioCoverPainter(this.waveform, this.color, this.devicePixelRatio);
final TimelineWaveform waveform;
final Color color;
final double devicePixelRatio;
@override
void paint(Canvas canvas, Size size) {
if (size.isEmpty) return;
final columns = math.max(1, (size.width / 2).floor());
final start = waveform.sourceStartSeconds * TimelineClock.ticksPerSecond;
final duration =
waveform.frameCount /
waveform.sampleRate *
TimelineClock.ticksPerSecond;
final paint = Paint()
..color = color
..style = PaintingStyle.fill
..isAntiAlias = false;
final strokePixels = math.max(1, devicePixelRatio.round());
final bottomPixels = math.max(1, (size.height * devicePixelRatio).floor());
for (var column = 0; column < columns; column++) {
final envelope = waveform.envelope(
(start + duration * column / columns).round(),
(start + duration * (column + 1) / columns).round(),
);
final peak = math.max(envelope.minimum.abs(), envelope.maximum.abs());
final height = math.min(size.height, math.max(1.0, peak * size.height));
final x = (column + 0.5) * size.width / columns;
final leftPixels = (x * devicePixelRatio - strokePixels / 2).round();
final topPixels = ((size.height - height) * devicePixelRatio)
.round()
.clamp(0, bottomPixels - 1);
canvas.drawRect(
Rect.fromLTWH(
leftPixels / devicePixelRatio,
topPixels / devicePixelRatio,
strokePixels / devicePixelRatio,
(bottomPixels - topPixels) / devicePixelRatio,
),
paint,
);
}
}
@override
bool shouldRepaint(_AudioCoverPainter oldDelegate) =>
oldDelegate.waveform != waveform ||
oldDelegate.color != color ||
oldDelegate.devicePixelRatio != devicePixelRatio;
}
@@ -0,0 +1,130 @@
import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
part 'background_removal_controller.g.dart';
part 'background_removal_controller.freezed.dart';
enum BackgroundRemovalFailure { download, start, rejected }
@freezed
sealed class BackgroundRemovalState with _$BackgroundRemovalState {
const factory BackgroundRemovalState.idle() = RemovalIdle;
const factory BackgroundRemovalState.downloading() = RemovalDownloading;
const factory BackgroundRemovalState.starting() = RemovalStarting;
const factory BackgroundRemovalState.started() = RemovalStarted;
const factory BackgroundRemovalState.cancelled() = RemovalCancelled;
const factory BackgroundRemovalState.failed(
BackgroundRemovalFailure failure, {
String? message,
}) = RemovalFailed;
}
@riverpod
class BackgroundRemovalController extends _$BackgroundRemovalController {
bool _cancelled = false;
ProcessingResourceRepository? _repository;
@override
BackgroundRemovalState build(
EditorTimelineSession session,
BackgroundRemovalClipTarget target,
) {
ref.onDispose(() {
_cancelled = true;
});
return const BackgroundRemovalState.idle();
}
Future<void> start(
ProcessingResourceRepository repository, {
bool download = false,
}) async {
if (state is RemovalDownloading || state is RemovalStarting) return;
final lease = ref.keepAlive();
final release = session.retainViews();
_repository = repository;
_cancelled = false;
var installed = !download;
state = download
? const BackgroundRemovalState.downloading()
: const BackgroundRemovalState.starting();
try {
if (download) {
await repository.ensureAvailable(
ProcessingCapability.backgroundRemoval,
);
installed = true;
}
if (_cancelled || !ref.mounted || !session.acceptsEdits) return;
state = const BackgroundRemovalState.starting();
final processing = ProcessingConfiguration.configured(
diagnostics: AppDiagnostics.report,
resourcesRoot: repository.root.parent.path,
);
final model = processing?.backgroundRemovalModel;
if (processing == null || model == null) {
throw AppException(AppErrorCode.startBackgroundRemovalFailed);
}
session.backgroundRemovals.configure(
backend: processing.backend.execute,
model: model,
);
await session.backgroundRemovals.start(
sequence: target.sequence,
clipId: target.clipId,
mediaId: target.mediaId,
name: target.name,
backend: processing.backend.execute,
model: model,
);
if (ref.mounted) state = const BackgroundRemovalState.started();
} on ProcessingResourceCancelledException {
if (ref.mounted) state = const BackgroundRemovalState.cancelled();
} on CommandRejected catch (error) {
if (ref.mounted) {
state = BackgroundRemovalState.failed(
BackgroundRemovalFailure.rejected,
message: error.message,
);
}
} catch (_) {
if (ref.mounted) {
state = BackgroundRemovalState.failed(
installed
? BackgroundRemovalFailure.start
: BackgroundRemovalFailure.download,
);
}
} finally {
if (ref.mounted &&
(state is RemovalDownloading || state is RemovalStarting)) {
state = const BackgroundRemovalState.cancelled();
}
_repository = null;
release();
lease.close();
}
}
void cancel(ProcessingResourceRepository repository) {
_cancelled = true;
(_repository ?? repository).cancel(ProcessingCapability.backgroundRemoval);
}
void togglePause(ProcessingResourceRepository repository) {
if (repository.downloadPausedFor(ProcessingCapability.backgroundRemoval)) {
repository.resumeDownload(ProcessingCapability.backgroundRemoval);
} else {
repository.pauseDownload(ProcessingCapability.backgroundRemoval);
}
}
}
@@ -0,0 +1,456 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'background_removal_controller.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$BackgroundRemovalState {
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is BackgroundRemovalState);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState()';
}
}
/// @nodoc
class $BackgroundRemovalStateCopyWith<$Res> {
$BackgroundRemovalStateCopyWith(
BackgroundRemovalState _,
$Res Function(BackgroundRemovalState) __,
);
}
/// Adds pattern-matching-related methods to [BackgroundRemovalState].
extension BackgroundRemovalStatePatterns on BackgroundRemovalState {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>({
TResult Function(RemovalIdle value)? idle,
TResult Function(RemovalDownloading value)? downloading,
TResult Function(RemovalStarting value)? starting,
TResult Function(RemovalStarted value)? started,
TResult Function(RemovalCancelled value)? cancelled,
TResult Function(RemovalFailed value)? failed,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle(_that);
case RemovalDownloading() when downloading != null:
return downloading(_that);
case RemovalStarting() when starting != null:
return starting(_that);
case RemovalStarted() when started != null:
return started(_that);
case RemovalCancelled() when cancelled != null:
return cancelled(_that);
case RemovalFailed() when failed != null:
return failed(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>({
required TResult Function(RemovalIdle value) idle,
required TResult Function(RemovalDownloading value) downloading,
required TResult Function(RemovalStarting value) starting,
required TResult Function(RemovalStarted value) started,
required TResult Function(RemovalCancelled value) cancelled,
required TResult Function(RemovalFailed value) failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle():
return idle(_that);
case RemovalDownloading():
return downloading(_that);
case RemovalStarting():
return starting(_that);
case RemovalStarted():
return started(_that);
case RemovalCancelled():
return cancelled(_that);
case RemovalFailed():
return failed(_that);
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>({
TResult? Function(RemovalIdle value)? idle,
TResult? Function(RemovalDownloading value)? downloading,
TResult? Function(RemovalStarting value)? starting,
TResult? Function(RemovalStarted value)? started,
TResult? Function(RemovalCancelled value)? cancelled,
TResult? Function(RemovalFailed value)? failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle(_that);
case RemovalDownloading() when downloading != null:
return downloading(_that);
case RemovalStarting() when starting != null:
return starting(_that);
case RemovalStarted() when started != null:
return started(_that);
case RemovalCancelled() when cancelled != null:
return cancelled(_that);
case RemovalFailed() when failed != null:
return failed(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>({
TResult Function()? idle,
TResult Function()? downloading,
TResult Function()? starting,
TResult Function()? started,
TResult Function()? cancelled,
TResult Function(BackgroundRemovalFailure failure, String? message)? failed,
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle();
case RemovalDownloading() when downloading != null:
return downloading();
case RemovalStarting() when starting != null:
return starting();
case RemovalStarted() when started != null:
return started();
case RemovalCancelled() when cancelled != null:
return cancelled();
case RemovalFailed() when failed != null:
return failed(_that.failure, _that.message);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>({
required TResult Function() idle,
required TResult Function() downloading,
required TResult Function() starting,
required TResult Function() started,
required TResult Function() cancelled,
required TResult Function(BackgroundRemovalFailure failure, String? message)
failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle():
return idle();
case RemovalDownloading():
return downloading();
case RemovalStarting():
return starting();
case RemovalStarted():
return started();
case RemovalCancelled():
return cancelled();
case RemovalFailed():
return failed(_that.failure, _that.message);
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>({
TResult? Function()? idle,
TResult? Function()? downloading,
TResult? Function()? starting,
TResult? Function()? started,
TResult? Function()? cancelled,
TResult? Function(BackgroundRemovalFailure failure, String? message)?
failed,
}) {
final _that = this;
switch (_that) {
case RemovalIdle() when idle != null:
return idle();
case RemovalDownloading() when downloading != null:
return downloading();
case RemovalStarting() when starting != null:
return starting();
case RemovalStarted() when started != null:
return started();
case RemovalCancelled() when cancelled != null:
return cancelled();
case RemovalFailed() when failed != null:
return failed(_that.failure, _that.message);
case _:
return null;
}
}
}
/// @nodoc
class RemovalIdle implements BackgroundRemovalState {
const RemovalIdle();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalIdle);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.idle()';
}
}
/// @nodoc
class RemovalDownloading implements BackgroundRemovalState {
const RemovalDownloading();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalDownloading);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.downloading()';
}
}
/// @nodoc
class RemovalStarting implements BackgroundRemovalState {
const RemovalStarting();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalStarting);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.starting()';
}
}
/// @nodoc
class RemovalStarted implements BackgroundRemovalState {
const RemovalStarted();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalStarted);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.started()';
}
}
/// @nodoc
class RemovalCancelled implements BackgroundRemovalState {
const RemovalCancelled();
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType && other is RemovalCancelled);
}
@override
int get hashCode => runtimeType.hashCode;
@override
String toString() {
return 'BackgroundRemovalState.cancelled()';
}
}
/// @nodoc
class RemovalFailed implements BackgroundRemovalState {
const RemovalFailed(this.failure, {this.message});
final BackgroundRemovalFailure failure;
final String? message;
/// Create a copy of BackgroundRemovalState
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$RemovalFailedCopyWith<RemovalFailed> get copyWith =>
_$RemovalFailedCopyWithImpl<RemovalFailed>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is RemovalFailed &&
(identical(other.failure, failure) || other.failure == failure) &&
(identical(other.message, message) || other.message == message));
}
@override
int get hashCode {
return Object.hash(runtimeType, failure, message);
}
@override
String toString() {
return 'BackgroundRemovalState.failed(failure: $failure, message: $message)';
}
}
/// @nodoc
abstract mixin class $RemovalFailedCopyWith<$Res>
implements $BackgroundRemovalStateCopyWith<$Res> {
factory $RemovalFailedCopyWith(
RemovalFailed value,
$Res Function(RemovalFailed) _then,
) = _$RemovalFailedCopyWithImpl;
@useResult
$Res call({BackgroundRemovalFailure failure, String? message});
}
/// @nodoc
class _$RemovalFailedCopyWithImpl<$Res>
implements $RemovalFailedCopyWith<$Res> {
_$RemovalFailedCopyWithImpl(this._self, this._then);
final RemovalFailed _self;
final $Res Function(RemovalFailed) _then;
/// Create a copy of BackgroundRemovalState
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
$Res call({Object? failure = null, Object? message = freezed}) {
return _then(
RemovalFailed(
null == failure
? _self.failure
: failure // ignore: cast_nullable_to_non_nullable
as BackgroundRemovalFailure,
message: freezed == message
? _self.message
: message // ignore: cast_nullable_to_non_nullable
as String?,
),
);
}
}
@@ -0,0 +1,124 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'background_removal_controller.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(BackgroundRemovalController)
final backgroundRemovalControllerProvider =
BackgroundRemovalControllerFamily._();
final class BackgroundRemovalControllerProvider
extends
$NotifierProvider<BackgroundRemovalController, BackgroundRemovalState> {
BackgroundRemovalControllerProvider._({
required BackgroundRemovalControllerFamily super.from,
required (EditorTimelineSession, BackgroundRemovalClipTarget)
super.argument,
}) : super(
retry: null,
name: r'backgroundRemovalControllerProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$backgroundRemovalControllerHash();
@override
String toString() {
return r'backgroundRemovalControllerProvider'
''
'$argument';
}
@$internal
@override
BackgroundRemovalController create() => BackgroundRemovalController();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(BackgroundRemovalState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<BackgroundRemovalState>(value),
);
}
@override
bool operator ==(Object other) {
return other is BackgroundRemovalControllerProvider &&
other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$backgroundRemovalControllerHash() =>
r'429add9c699b92fdba9c553810f17f4a6859f4e6';
final class BackgroundRemovalControllerFamily extends $Family
with
$ClassFamilyOverride<
BackgroundRemovalController,
BackgroundRemovalState,
BackgroundRemovalState,
BackgroundRemovalState,
(EditorTimelineSession, BackgroundRemovalClipTarget)
> {
BackgroundRemovalControllerFamily._()
: super(
retry: null,
name: r'backgroundRemovalControllerProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
BackgroundRemovalControllerProvider call(
EditorTimelineSession session,
BackgroundRemovalClipTarget target,
) => BackgroundRemovalControllerProvider._(
argument: (session, target),
from: this,
);
@override
String toString() => r'backgroundRemovalControllerProvider';
}
abstract class _$BackgroundRemovalController
extends $Notifier<BackgroundRemovalState> {
late final _$args =
ref.$arg as (EditorTimelineSession, BackgroundRemovalClipTarget);
EditorTimelineSession get session => _$args.$1;
BackgroundRemovalClipTarget get target => _$args.$2;
BackgroundRemovalState build(
EditorTimelineSession session,
BackgroundRemovalClipTarget target,
);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref as $Ref<BackgroundRemovalState, BackgroundRemovalState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<BackgroundRemovalState, BackgroundRemovalState>,
BackgroundRemovalState,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
}
}
@@ -0,0 +1,202 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../integrations/runtime/processing_resource_state.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
import 'background_removal_controller.dart';
export 'processing_targets.dart';
class BackgroundRemovalDialog extends ConsumerStatefulWidget {
const BackgroundRemovalDialog({
super.key,
required this.session,
required this.target,
});
final EditorTimelineSession session;
final BackgroundRemovalClipTarget target;
@override
ConsumerState<BackgroundRemovalDialog> createState() =>
_BackgroundRemovalDialogState();
}
class _BackgroundRemovalDialogState
extends ConsumerState<BackgroundRemovalDialog> {
late final VoidCallback _release;
bool _closing = false;
BackgroundRemovalControllerProvider get _provider =>
backgroundRemovalControllerProvider(widget.session, widget.target);
BackgroundRemovalState get _state => ref.read(_provider);
bool get _installing => _state is RemovalDownloading;
bool get _starting => _state is RemovalStarting;
String? get _error => switch (_state) {
RemovalFailed(:final failure, :final message) => switch (failure) {
BackgroundRemovalFailure.download =>
context.l10n.processingResourceDownloadFailed,
BackgroundRemovalFailure.start =>
context.l10n.startBackgroundRemovalFailed,
BackgroundRemovalFailure.rejected => message,
},
_ => null,
};
@override
void initState() {
super.initState();
_release = widget.session.retainViews();
}
@override
void dispose() {
_release();
super.dispose();
}
Future<void> _start(ProcessingResourceRepository repository) =>
ref.read(_provider.notifier).start(repository);
Future<void> _downloadAndStart(ProcessingResourceRepository repository) =>
ref.read(_provider.notifier).start(repository, download: true);
@override
Widget build(BuildContext context) {
ref.watch(_provider);
ref.listen(_provider, (previous, next) {
if (next is! RemovalStarted || _closing) return;
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final message = context.l10n.backgroundRemovalTaskStarted;
Navigator.of(context).pop();
messenger?.showSnackBar(SnackBar(content: Text(message)));
});
});
return ref
.watch(processingResourceRepositoryProvider)
.when(
loading: () => const DelayedLoadingIndicator(
child: AppDialog(
title: '',
width: 520,
child: Center(child: CircularProgressIndicator()),
),
),
error: (_, _) => AppDialog(
title: context.l10n.removeBackground,
width: 520,
child: Text(context.l10n.loadResourceLocationFailed),
),
data: (repository) => Consumer(
builder: (context, ref, _) {
final resources = ref.watch(
processingResourcesProvider(repository),
);
final install =
resources.installs
.where(
(item) =>
item.package.capability ==
ProcessingCapability.backgroundRemoval,
)
.firstOrNull ??
repository.installFor(ProcessingCapability.backgroundRemoval);
final installed =
install.state == ProcessingResourceState.installed ||
ProcessingConfiguration.configured(
resourcesRoot: repository.root.parent.path,
)?.backgroundRemovalModel !=
null;
final downloading =
install.state == ProcessingResourceState.downloading;
if (!installed) {
return ProcessingResourceDownloadDialog(
title: context.l10n.backgroundRemovalDownloadTask,
description: context.l10n.backgroundRemovalResourceRequired,
resourceName: context.l10n.backgroundRemovalResourceName,
downloadSize: context.l10n.subtitleResourcesDownloadSize(
formatResourceBytes(install.package.bytes),
),
downloading: downloading,
paused: resources.paused.contains(
ProcessingCapability.backgroundRemoval,
),
downloadedBytes: install.downloadedBytes,
totalBytes: install.package.bytes,
bytesPerSecond:
resources.rates[ProcessingCapability.backgroundRemoval] ??
0,
error: _error,
downloadButtonKey: const Key(
'download-background-removal-resource',
),
pauseButtonKey: const Key(
'pause-background-removal-resource',
),
backgroundButtonKey: const Key(
'background-background-removal-resource',
),
onCancel: () async {
if (downloading &&
!await confirmResourceDownloadCancellation(context)) {
return;
}
if (!mounted || !context.mounted) return;
if (downloading) {
ref.read(_provider.notifier).cancel(repository);
}
Navigator.of(context).pop();
},
onDownload: () {
if (!_installing && !downloading) {
_downloadAndStart(repository);
}
},
onTogglePause: () =>
ref.read(_provider.notifier).togglePause(repository),
onBackground: () => Navigator.of(context).pop(),
);
}
return AppDialog(
title: context.l10n.removeBackground,
width: 520,
description: context.l10n.backgroundRemovalDestructiveHint,
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(context.l10n.close),
),
FilledButton(
onPressed:
_installing || _starting || !widget.session.acceptsEdits
? null
: () => _start(repository),
child: Text(context.l10n.startBackgroundRemoval),
),
],
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
if (_error case final error?) ...[
const SizedBox(height: AppSpacing.compact),
Text(error),
],
],
),
);
},
),
);
}
}
@@ -0,0 +1,862 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'subtitle_download.dart';
import 'subtitle_task_actions.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:flutter/material.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../workspace/background_task_registry.dart';
import '../../workspace/background_task_state.dart';
import '../../integrations/runtime/processing_resource_state.dart';
import '../../workspace/timeline_session.dart';
import 'transcription_dialog.dart';
class BackgroundTasksDialog extends StatelessWidget {
const BackgroundTasksDialog({super.key, required this.session});
final EditorTimelineSession session;
@override
Widget build(BuildContext context) => AppDialog(
title: context.l10n.backgroundTasks,
width: 560,
height: 520,
child: BackgroundTasksContent(session: session),
);
}
class BackgroundTasksContent extends ConsumerWidget {
const BackgroundTasksContent({
super.key,
this.session,
this.registry,
this.repository,
}) : assert(session != null || registry != null);
final EditorTimelineSession? session;
final BackgroundTaskRegistry? registry;
final ProcessingResourceRepository? repository;
@override
Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch(
backgroundTasksProvider(registry: registry, session: session),
);
final resources = repository == null
? null
: ref.watch(processingResourcesProvider(repository!));
final subtitleEntries = snapshot.subtitles;
final removalEntries = snapshot.removals;
final subtitleDownloading = resources?.subtitleDownloading == true;
final resourceDownloads =
resources?.installs
.where(
(install) =>
(install.state == ProcessingResourceState.downloading &&
!(subtitleDownloading &&
ProcessingResourceRepository.subtitleCapabilities
.contains(install.package.capability))) ||
install.state == ProcessingResourceState.failed,
)
.toList() ??
<ProcessingResourceInstall>[];
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (subtitleEntries.isEmpty &&
!subtitleDownloading &&
resourceDownloads.isEmpty &&
removalEntries.isEmpty)
SizedBox(
key: const Key('background-tasks-empty-state'),
height: AppMenuMetrics.rowHeight,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppMenuMetrics.iconGap,
),
child: Align(
alignment: AlignmentDirectional.centerStart,
child: Text(
context.l10n.noBackgroundTasks,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
fontSize: AppMenuMetrics.fontSize,
height: AppMenuMetrics.lineHeight / AppMenuMetrics.fontSize,
),
),
),
),
)
else
Flexible(
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
if (subtitleDownloading)
_ResourceDownloadCard(
repository: repository!,
subtitleBundle: true,
),
for (final (index, install) in resourceDownloads.indexed) ...[
if (index > 0 || subtitleDownloading)
const SizedBox(height: 2),
_ResourceDownloadCard(
repository: repository!,
install: install,
),
],
for (final (index, entry) in removalEntries.indexed) ...[
if (index > 0 ||
resourceDownloads.isNotEmpty ||
subtitleDownloading)
const SizedBox(height: 2),
_BackgroundRemovalTaskCard(
key: ValueKey(entry.task.id),
entry: entry,
),
],
for (final (index, entry)
in subtitleEntries.reversed.indexed) ...[
if (index > 0 ||
resourceDownloads.isNotEmpty ||
removalEntries.isNotEmpty ||
subtitleDownloading)
const SizedBox(height: 2),
_SubtitleTaskCard(
key: ValueKey(entry.job.recognition.id),
entry: entry,
),
],
],
),
),
),
],
);
}
}
String _ownerName(BackgroundTaskSession owner) => owner.projectName.isEmpty
? owner.timelineName
: '${owner.projectName} · ${owner.timelineName}';
Future<void> _showTaskDetails(
BuildContext context, {
required WidgetBuilder builder,
EditorTimelineSession? session,
}) async {
final release = session?.retainViews();
try {
await showAppDialog<void>(
context: context,
builder: (context) => AppDialog(
title: context.l10n.backgroundTaskDetails,
width: 560,
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(context.l10n.close),
),
],
child: builder(context),
),
);
} finally {
release?.call();
}
}
class _SubtitleTaskDetails extends ConsumerWidget {
const _SubtitleTaskDetails(this.initial);
final SubtitleTaskEntry initial;
@override
Widget build(BuildContext context, WidgetRef ref) {
final latest = ref.watch(
backgroundTasksProvider(session: initial.owner.session).select(
(snapshot) => snapshot.subtitles
.where((entry) => entry.job.id == initial.job.id)
.firstOrNull,
),
);
if (latest == null) return Text(context.l10n.noBackgroundTasks);
return _SubtitleTaskCard(
entry: latest.copyWith(owner: initial.owner),
details: true,
);
}
}
class _RemovalTaskDetails extends ConsumerWidget {
const _RemovalTaskDetails(this.initial);
final RemovalTaskEntry initial;
@override
Widget build(BuildContext context, WidgetRef ref) {
final latest = ref.watch(
backgroundTasksProvider(session: initial.owner.session).select(
(snapshot) => snapshot.removals
.where((entry) => entry.task.id == initial.task.id)
.firstOrNull,
),
);
if (latest == null) return Text(context.l10n.noBackgroundTasks);
return _BackgroundRemovalTaskCard(
entry: latest.copyWith(owner: initial.owner),
details: true,
);
}
}
class _TaskSummary extends StatelessWidget {
const _TaskSummary({
required this.name,
required this.status,
required this.onTap,
this.active = false,
this.progress,
this.progressDetails,
this.action,
});
final String name, status;
final VoidCallback onTap;
final bool active;
final double? progress;
final Widget? progressDetails;
final Widget? action;
@override
Widget build(BuildContext context) => Material(
type: MaterialType.transparency,
borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius),
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(AppMenuMetrics.itemRadius),
hoverColor: AppSidebarColors.of(context).hover,
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 8),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: [
Text(name, maxLines: 1, overflow: TextOverflow.ellipsis),
const SizedBox(height: 4),
if (progressDetails case final details?)
details
else ...[
Text(
'$status${active && progress != null ? " · ${(progress! * 100).floor()}%" : ""}',
style: Theme.of(context).textTheme.bodySmall,
),
if (active) ...[
const SizedBox(height: 6),
LinearProgressIndicator(value: progress),
],
],
],
),
),
?action,
],
),
),
),
);
}
class _BackgroundRemovalTaskCard extends StatelessWidget {
const _BackgroundRemovalTaskCard({
super.key,
required this.entry,
this.details = false,
});
final RemovalTaskEntry entry;
final bool details;
@override
Widget build(BuildContext context) {
final total = entry.total;
final completed = entry.completed;
final progressValue = total == null || total <= 0 || completed == null
? null
: completed / total;
final active = !entry.terminal;
final status = switch (entry.status) {
BackgroundRemovalStatus.queued => context.l10n.preparingMedia,
BackgroundRemovalStatus.running => context.l10n.removeBackground,
BackgroundRemovalStatus.applying =>
context.l10n.backgroundRemovalApplying,
BackgroundRemovalStatus.succeeded =>
context.l10n.backgroundRemovalComplete,
BackgroundRemovalStatus.failed => context.l10n.backgroundRemovalFailed,
BackgroundRemovalStatus.cancelling => context.l10n.cancelling,
BackgroundRemovalStatus.cancelled => context.l10n.cancelled,
BackgroundRemovalStatus.interrupted => context.l10n.interruptedTask,
};
if (!details) {
return _TaskSummary(
name: entry.name,
status: status,
active: active,
progress: progressValue,
action: active
? TextButton(
onPressed: entry.status == BackgroundRemovalStatus.cancelling
? null
: () => entry.owner.session.backgroundRemovals.cancel(
entry.task.id,
),
child: Text(context.l10n.cancel),
)
: null,
onTap: () => _showTaskDetails(
context,
session: entry.owner.session,
builder: (_) => _RemovalTaskDetails(entry),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(entry.name, style: Theme.of(context).textTheme.titleSmall),
Text(
_ownerName(entry.owner),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: AppSpacing.small),
Text(status),
if (entry.error case final error?)
Text(
context.l10n.errorMessage(error),
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
if (active) ...[
const SizedBox(height: AppSpacing.small),
LinearProgressIndicator(value: progressValue),
if (progressValue != null)
Align(
alignment: Alignment.centerRight,
child: Text('${(progressValue * 100).floor()}%'),
),
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: entry.status == BackgroundRemovalStatus.cancelling
? null
: () => entry.owner.session.backgroundRemovals.cancel(
entry.task.id,
),
child: Text(context.l10n.cancel),
),
),
],
],
);
}
}
class _ResourceDownloadCard extends ConsumerWidget {
const _ResourceDownloadCard({
required this.repository,
this.install,
this.subtitleBundle = false,
this.details = false,
}) : assert(subtitleBundle || install != null);
final ProcessingResourceRepository repository;
final ProcessingResourceInstall? install;
final bool subtitleBundle;
final bool details;
@override
Widget build(BuildContext context, WidgetRef ref) {
final snapshot = ref.watch(processingResourcesProvider(repository));
final install = this.install == null
? null
: snapshot.installs
.where((item) => item.package.id == this.install!.package.id)
.firstOrNull ??
this.install;
final downloading = subtitleBundle
? snapshot.subtitleDownloading
: install!.state == ProcessingResourceState.downloading;
final paused =
downloading &&
(subtitleBundle
? snapshot.subtitlePaused
: snapshot.paused.contains(install!.package.capability));
final label = paused
? context.l10n.downloadPaused
: subtitleBundle
? downloading
? context.l10n.downloadingResource
: context.l10n.backgroundTaskCompleted
: switch (install!.state) {
ProcessingResourceState.downloading =>
context.l10n.downloadingResource,
ProcessingResourceState.installed =>
context.l10n.backgroundTaskCompleted,
ProcessingResourceState.notInstalled => context.l10n.cancelled,
ProcessingResourceState.failed => context.l10n.backgroundTaskFailed,
};
final name = subtitleBundle
? context.l10n.subtitleResourceDownloadTask
: install!.package.capability == ProcessingCapability.backgroundRemoval
? context.l10n.backgroundRemovalDownloadTask
: install.package.name;
final downloadedBytes = subtitleBundle
? snapshot.subtitleDownloadedBytes
: install!.downloadedBytes;
final totalBytes = subtitleBundle
? snapshot.subtitleTotalBytes
: install!.package.bytes;
Future<void> cancel() async {
if (!await confirmResourceDownloadCancellation(context)) return;
if (subtitleBundle) {
if (repository.subtitleDownloading) {
repository.cancelSubtitleResources();
}
} else if (repository.installFor(install!.package.capability).state ==
ProcessingResourceState.downloading) {
repository.cancel(install.package.capability);
}
}
Future<void> retry() async {
try {
await repository.ensureAvailable(install!.package.capability);
} catch (_) {
// Repository publishes the error in task details.
}
}
void togglePause() {
if (subtitleBundle) {
if (paused) {
repository.resumeSubtitleResources();
} else {
repository.pauseSubtitleResources();
}
} else if (paused) {
repository.resumeDownload(install!.package.capability);
} else {
repository.pauseDownload(install!.package.capability);
}
}
if (!details) {
return _TaskSummary(
name: name,
status: label,
active: downloading,
progressDetails: downloading
? ResourceDownloadProgress(
downloadedBytes: downloadedBytes,
totalBytes: totalBytes,
bytesPerSecond: subtitleBundle
? snapshot.subtitleBytesPerSecond
: snapshot.rates[install!.package.capability] ?? 0,
status: paused ? label : '',
paused: paused,
)
: null,
action: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (downloading)
TextButton(
key: const Key('background-download-pause-button'),
onPressed: togglePause,
child: Text(
paused
? context.l10n.resumeDownload
: context.l10n.pauseDownload,
),
),
TextButton(
onPressed: downloading ? cancel : retry,
child: Text(
downloading ? context.l10n.cancel : context.l10n.retryTask,
),
),
],
),
onTap: () {
final download = ref.read(subtitleDownloadProvider);
final activeDownload =
subtitleBundle &&
download.running &&
download.request?.session.acceptsEdits == true
? download.request
: null;
if (activeDownload != null) {
showAppDialog<void>(
context: context,
builder: (_) => TranscriptionDialog.forCurrentTask(
session: activeDownload.session,
),
);
return;
}
_showTaskDetails(
context,
builder: (_) => _ResourceDownloadCard(
repository: repository,
install: subtitleBundle
? null
: repository.installFor(install!.package.capability),
subtitleBundle: subtitleBundle,
details: true,
),
);
},
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(name, style: Theme.of(context).textTheme.titleSmall),
const SizedBox(height: AppSpacing.small),
if (!downloading) Text(label),
if (install?.error != null)
Text(context.l10n.failureMessage(install!.error!)),
if (downloading) ...[
ResourceDownloadProgress(
downloadedBytes: downloadedBytes,
totalBytes: totalBytes,
bytesPerSecond: subtitleBundle
? snapshot.subtitleBytesPerSecond
: snapshot.rates[install!.package.capability] ?? 0,
status: paused ? label : '',
paused: paused,
),
],
if (downloading || install?.state == ProcessingResourceState.failed)
Align(
alignment: Alignment.centerRight,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (downloading)
TextButton(
onPressed: togglePause,
child: Text(
paused
? context.l10n.resumeDownload
: context.l10n.pauseDownload,
),
),
TextButton(
onPressed: downloading ? cancel : retry,
child: Text(
downloading ? context.l10n.cancel : context.l10n.retryTask,
),
),
],
),
),
],
);
}
}
class _SubtitleTaskCard extends ConsumerStatefulWidget {
const _SubtitleTaskCard({
super.key,
required this.entry,
this.details = false,
});
final SubtitleTaskEntry entry;
EditorTimelineSession get session => entry.owner.session;
SubtitleBackgroundTask get job => entry.job;
final bool details;
TranscriptionClipTarget? get target => job.recognition.command.clipId == null
? null
: TranscriptionClipTarget(
sequence: job.sequence,
clipId: job.recognition.command.clipId!,
mediaId: job.recognition.command.mediaId,
name: entry.name,
audioStream: job.recognition.command.audioStream,
);
@override
ConsumerState<_SubtitleTaskCard> createState() => _SubtitleTaskCardState();
}
class _SubtitleTaskCardState extends ConsumerState<_SubtitleTaskCard> {
SubtitleTaskActionsProvider get _provider =>
subtitleTaskActionsProvider(widget.session, widget.job.id);
SubtitleTaskActions get _actions => ref.read(_provider.notifier);
bool get _picking => ref.read(_provider).isLoading;
String? _validationError;
String? get _error {
final value = ref.read(_provider);
if (_validationError != null) return _validationError;
if (value.error case SubtitleActionException(:final kind, :final cause)) {
if (cause is CommandRejected && cause.code == 'staleVersion') {
return context.l10n.timelineChanged;
}
final message = context.l10n.errorMessage(cause);
return switch (kind) {
SubtitleActionKind.original => context.l10n.applyCaptionsError(message),
SubtitleActionKind.translation =>
context.l10n.applyTranslatedCaptionsError(message),
_ => message,
};
}
final result = value.value;
return switch (result?.kind) {
SubtitleActionKind.original => context.l10n.captionsAdded(
result!.cueCount.toString(),
),
SubtitleActionKind.translation => context.l10n.translatedCaptionsAdded(
result!.cueCount.toString(),
),
_ => null,
};
}
Future<void> _applyResult({bool translated = false}) async {
if (_picking) return;
final job = widget.job;
final version = widget.session.version;
String? clip = widget.target?.clipId;
if (clip == null) {
final candidates = await _actions.candidates(job, translated: translated);
if (!mounted) return;
if (candidates.isEmpty) {
setState(
() => _validationError = translated
? context.l10n.placeTranslationMediaFirst
: context.l10n.placeMediaFirst,
);
return;
}
clip = await showAppDialog<String>(
context: context,
builder: (context) => AppDialog(
title: context.l10n.selectTargetClip,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final candidate in candidates)
AppDialogOption(
label:
'${candidate.name ?? context.l10n.clip} · ${candidate.id.value}',
onPressed: () => Navigator.pop(context, candidate.id.value),
),
],
),
),
);
}
if (clip == null || !mounted) return;
setState(() => _validationError = null);
await _actions.apply(
job,
clip,
expectedVersion: version,
translated: translated,
);
}
String _failureMessage(String? code) => switch (code) {
'notConfigured' => context.l10n.transcriptionAccessFailed,
'noAudio' => context.l10n.transcriptionNoAudio,
'invalidResult' => context.l10n.transcriptionInvalidResult,
'workerExited' => context.l10n.transcriptionWorkerExited,
'processingFailed' => context.l10n.transcriptionProcessingFailed,
final value? => context.l10n.transcriptionError(value),
null => context.l10n.transcriptionFailed,
};
Future<void> _action(Future<void> Function() action) async {
setState(() => _validationError = null);
await action();
if (mounted && !widget.details && _error != null) {
ScaffoldMessenger.maybeOf(context)
?.showSnackBar(SnackBar(content: Text(_error!)));
}
}
@override
Widget build(BuildContext context) {
ref.watch(_provider);
final job = widget.job;
final taskSession = widget.session;
final entry = widget.entry;
final total = entry.total;
final completed = entry.completed;
final value = total == null || total <= 0 || completed == null
? null
: (completed / total).clamp(0.0, 1.0);
final status = entry.status;
final failure = entry.error;
final label = switch (status) {
TranscriptionStatus.queued =>
!entry.hasTranslation
? context.l10n.preparingMedia
: context.l10n.preparingTranslation,
TranscriptionStatus.running =>
!entry.hasTranslation
? context.l10n.transcribing
: context.l10n.translatingCaptions,
TranscriptionStatus.cancelling => context.l10n.cancelling,
TranscriptionStatus.succeeded =>
entry.followingUp
? context.l10n.preparingTranslation
: context.l10n.captionsGenerated,
TranscriptionStatus.failed =>
failure == 'sourceLanguageUnknown'
? context.l10n.sourceLanguageUnknown
: _failureMessage(failure),
TranscriptionStatus.cancelled => context.l10n.cancelled,
TranscriptionStatus.interrupted => context.l10n.interruptedTask,
};
if (!widget.details) {
return _TaskSummary(
name: entry.name,
status: status == TranscriptionStatus.failed
? context.l10n.backgroundTaskFailed
: entry.recognitionAvailable &&
entry.terminal &&
status == TranscriptionStatus.succeeded
? '$label · ${context.l10n.captionCount(entry.resultCues.length)}'
: label,
active: !entry.terminal,
progress: entry.followingUp && entry.recognitionTerminal ? null : value,
action: !entry.terminal
? TextButton(
onPressed: _picking
? null
: () => _action(() => _actions.cancel(job)),
child: Text(context.l10n.cancel),
)
: status == TranscriptionStatus.failed ||
status == TranscriptionStatus.interrupted ||
status == TranscriptionStatus.cancelled
? TextButton(
onPressed: _picking || !taskSession.acceptsEdits
? null
: () => _action(() => _actions.retry(job)),
child: Text(context.l10n.retryTask),
)
: null,
onTap: () => _showTaskDetails(
context,
session: taskSession,
builder: (_) => _SubtitleTaskDetails(entry),
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
Text(entry.name, style: Theme.of(context).textTheme.titleSmall),
Text(
_ownerName(entry.owner),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: AppSpacing.small),
Text(label),
if (!entry.terminal) ...[
const SizedBox(height: AppSpacing.small),
LinearProgressIndicator(
value: entry.followingUp && entry.recognitionTerminal
? null
: value,
),
const SizedBox(height: AppSpacing.small),
if (!entry.hasTranslation)
Text(context.l10n.recognizedCaptions(entry.recognizedCues)),
if (value != null &&
!(entry.followingUp && entry.recognitionTerminal))
Text('${(value * 100).floor()}%'),
if (!entry.hasTranslation && entry.recentCues.isNotEmpty)
Text(entry.recentCues.join('\n')),
],
Text(
'${context.l10n.sourceLanguage}: ${context.l10n.subtitleLanguageName(entry.sourceLanguage)}',
),
if (entry.targetLanguage != 'none')
Text(
'${context.l10n.translationLanguage}: ${context.l10n.subtitleLanguageName(entry.targetLanguage)}',
),
if (entry.recognitionAvailable) ...[
Text(context.l10n.captionCount(entry.recognizedCues)),
const SizedBox(height: AppSpacing.small),
SizedBox(
height: 160,
child: ListView.builder(
primary: false,
itemCount: entry.resultCues.length,
itemBuilder: (context, index) => Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: SelectableText(entry.resultCues[index]),
),
),
),
],
if (_error != null) ...[
const SizedBox(height: AppSpacing.small),
Text(_error!),
],
Wrap(
alignment: WrapAlignment.end,
spacing: 8,
children: [
if (!entry.terminal)
TextButton(
onPressed: _picking
? null
: () => _action(() => _actions.cancel(job)),
child: Text(context.l10n.cancel),
),
if (entry.terminal &&
(status == TranscriptionStatus.failed ||
status == TranscriptionStatus.interrupted ||
status == TranscriptionStatus.cancelled))
TextButton(
onPressed: _picking || !widget.session.acceptsEdits
? null
: () => _action(() => _actions.retry(job)),
child: Text(context.l10n.retryTask),
),
if (entry.recognitionAvailable)
TextButton(
onPressed: _picking || !widget.session.acceptsEdits
? null
: _applyResult,
child: Text(context.l10n.applyOriginalCaptions),
),
if (entry.translationAvailable)
TextButton(
onPressed: _picking || !widget.session.acceptsEdits
? null
: () => _applyResult(translated: true),
child: Text(context.l10n.applyTranslatedCaptions),
),
],
),
],
);
}
}
+38
View File
@@ -0,0 +1,38 @@
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
/// Subscribes to one cover frame so loading it only rebuilds its image.
class MediaAssetCover extends ConsumerWidget {
const MediaAssetCover({
super.key,
required this.asset,
required this.fallback,
this.errorFallback,
this.fit = BoxFit.contain,
this.timeMilliseconds = 0,
});
final AssetDocument asset;
final Widget fallback;
final Widget? errorFallback;
final BoxFit fit;
final int timeMilliseconds;
@override
Widget build(BuildContext context, WidgetRef ref) {
final bytes = ref
.watch(mediaCoverProvider(asset, timeMilliseconds: timeMilliseconds))
.value;
return bytes == null
? fallback
: Image.memory(
bytes,
fit: fit,
excludeFromSemantics: true,
errorBuilder: (_, _, _) => errorFallback ?? fallback,
);
}
}
+9
View File
@@ -0,0 +1,9 @@
import 'package:flutter/foundation.dart';
/// Drag data carries identities; feedback switches off inside the timeline.
class MediaAssetDrag {
MediaAssetDrag({required this.projectId, required this.assetId});
final String projectId;
final String assetId;
final feedbackVisible = ValueNotifier<bool>(true);
}
+115
View File
@@ -0,0 +1,115 @@
import 'dart:math' as math;
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/media_presentations.dart';
import 'package:cutdex_ui/theme.dart';
import 'audio_asset_tile.dart';
import 'media_asset_cover.dart';
/// Compact full-width preview used by the media library's list layout.
class MediaAssetStrip extends StatelessWidget {
const MediaAssetStrip({super.key, required this.asset});
static const height = 46.0;
final AssetDocument asset;
@override
Widget build(BuildContext context) => SizedBox(
height: height,
child: LayoutBuilder(
builder: (context, constraints) {
if (asset.metadata['kind'] == 'audio') {
return AudioAssetTile(
asset: asset,
showName: false,
aspectRatio: constraints.maxWidth / height,
);
}
return _VisualAssetStrip(asset: asset, width: constraints.maxWidth);
},
),
);
}
class _VisualAssetStrip extends ConsumerWidget {
const _VisualAssetStrip({required this.asset, required this.width});
final AssetDocument asset;
final double width;
@override
Widget build(BuildContext context, WidgetRef ref) {
final video = asset.metadata['kind'] == 'video';
final duration = video
? ref.watch(mediaDurationProvider(asset)).value
: null;
final count = (width / (MediaAssetStrip.height * 16 / 9)).ceil().clamp(
1,
16,
);
return ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var index = 0; index < count; index++)
Expanded(
child: MediaAssetCover(
asset: asset,
fit: BoxFit.cover,
timeMilliseconds: video && duration != null
? (duration * 1000 * index / count).floor()
: 0,
fallback: const Center(child: Icon(Icons.movie_outlined)),
errorFallback: const Center(
child: Icon(Icons.broken_image_outlined),
),
),
),
],
),
);
}
}
class MediaAssetDuration extends ConsumerWidget {
const MediaAssetDuration({super.key, required this.asset});
final AssetDocument asset;
@override
Widget build(BuildContext context, WidgetRef ref) {
if (!const {'audio', 'video'}.contains(asset.metadata['kind'])) {
return const SizedBox.shrink();
}
final duration = ref.watch(mediaDurationProvider(asset)).value;
if (duration == null) return const SizedBox.shrink();
final seconds = math.max(0, duration.floor());
final hours = seconds ~/ 3600;
final minutes = hours > 0 ? (seconds ~/ 60) % 60 : seconds ~/ 60;
final text =
'${hours > 0 ? '$hours:' : ''}'
'${minutes.toString().padLeft(2, '0')}:'
'${(seconds % 60).toString().padLeft(2, '0')}';
return DecoratedBox(
decoration: BoxDecoration(
color: Colors.black.withValues(alpha: .55),
borderRadius: BorderRadius.circular(4),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 4, vertical: 1),
child: Text(
text,
key: ValueKey('media-duration-${asset.id}'),
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Colors.white,
fontFeatures: const [FontFeature.tabularFigures()],
),
),
),
);
}
}
+505
View File
@@ -0,0 +1,505 @@
import 'package:cutdex/errors/app_failure.dart';
import 'dart:math' as math;
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import 'audio_asset_tile.dart';
import 'media_asset_drag.dart';
import 'media_asset_strip.dart';
import 'media_browser_controller.dart';
import 'unavailable_media_placeholder.dart';
import 'visual_asset_tile.dart';
extension MediaFilterLabel on MediaFilter {
String label(BuildContext context) => switch (this) {
MediaFilter.all => context.l10n.all,
MediaFilter.image => context.l10n.picture,
MediaFilter.video => context.l10n.video,
MediaFilter.audio => context.l10n.audio,
};
}
const maximumMediaGridTileWidth = 160.0;
class MediaBrowserBody extends ConsumerStatefulWidget {
const MediaBrowserBody({
super.key,
required this.projectId,
required this.grid,
this.draggable = false,
});
final String projectId;
final bool grid;
final bool draggable;
@override
ConsumerState<MediaBrowserBody> createState() => _MediaBrowserBodyState();
}
class _MediaBrowserBodyState extends ConsumerState<MediaBrowserBody>
with WidgetsBindingObserver {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
ref.invalidate(mediaAvailabilityProvider);
}
}
MediaBrowserController get _browser =>
ref.read(mediaBrowserProvider(widget.projectId));
bool get _checkingDrop => _browser.busy;
String? get _selectedAssetId => _browser.selectedAssetId;
set _selectedAssetId(String? value) => _browser.selectedAssetId = value;
MediaFilter get _filter => _browser.filter;
bool get _isGrid => widget.grid;
bool get _desktop => ref.read(platformCapabilitiesProvider).nativeFileDrop;
Future<void> _action(Future<bool> Function() action) async {
final ok = await action();
if (!mounted || ok) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
context.l10n.failureMessage(
ref.read(projectsProvider).asData?.value.error ??
const AppFailure(AppErrorCode.operationFailed),
),
),
),
);
}
Future<void> _rename(AssetDocument asset) async {
final controller = TextEditingController(text: asset.name);
final name = await showAppDialog<String>(
context: context,
builder: (context) => AppDialog(
title: context.l10n.renameMedia,
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: Text(context.l10n.cancel),
),
ListenableBuilder(
listenable: controller,
builder: (context, _) => FilledButton(
onPressed: controller.text.trim().isEmpty
? null
: () => Navigator.pop(context, controller.text.trim()),
child: Text(context.l10n.save),
),
),
],
child: AppField(
label: context.l10n.name,
child: TextField(
controller: controller,
autofocus: true,
onSubmitted: (value) {
if (value.trim().isNotEmpty) Navigator.pop(context, value.trim());
},
),
),
),
);
// The route's closing animation can still read its text controller.
await Future<void>.delayed(const Duration(milliseconds: 200));
controller.dispose();
if (!mounted || name == null) return;
await _action(() => _browser.rename(asset, name));
}
Future<void> _remove(AssetDocument asset) async {
final confirmed = await showAppDialog<bool>(
context: context,
builder: (context) => AppDialog(
title: context.l10n.removeMedia,
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: Text(context.l10n.cancel),
),
TextButton(
onPressed: () => Navigator.pop(context, true),
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
child: Text(context.l10n.remove),
),
],
child: Text(context.l10n.removeMediaConfirmation(asset.name)),
),
);
if (!mounted || confirmed != true) return;
await _action(() => _browser.remove(asset));
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: ref.watch(mediaBrowserProvider(widget.projectId)),
builder: (context, _) => _buildBrowser(context),
);
Widget _buildBrowser(BuildContext context) {
ref.watch(externalMediaImportProvider(widget.projectId));
final workspace = ref.watch(projectsProvider).asData?.value;
final active = workspace?.activeProject?.id == widget.projectId;
final allAssets = active ? workspace!.assets : <AssetDocument>[];
final assets = _filter == MediaFilter.all
? allAssets
: allAssets
.where((asset) => asset.metadata['kind'] == _filter.kind)
.toList();
final timelineId = active ? workspace?.timeline?.id : null;
final timeline = timelineId == null
? null
: ref
.watch(editorTimelineProvider(widget.projectId, timelineId))
.asData
?.value;
return assets.isEmpty
? Center(
child: Padding(
padding: const EdgeInsets.all(AppSpacing.medium),
child: Text(
_filter != MediaFilter.all
? context.l10n.noMediaOfType(_filter.label(context))
: _desktop
? context.l10n.dragMediaHint
: context.l10n.noMedia,
textAlign: TextAlign.center,
),
),
)
: LayoutBuilder(
builder: (context, constraints) {
const spacing = AppSpacing.small;
final width = math.max(
1.0,
constraints.maxWidth - AppSpacing.compact * 2,
);
final columns = math.max(
1,
((width + spacing) / (maximumMediaGridTileWidth + spacing))
.ceil(),
);
final tileWidth = (width - spacing * (columns - 1)) / columns;
final textStyle = Theme.of(context).textTheme.bodySmall!;
final labelHeight =
MediaQuery.textScalerOf(context).scale(textStyle.fontSize!) *
(textStyle.height ?? 1.2);
Widget item(BuildContext context, int index) {
final asset = assets[index];
return Consumer(
builder: (context, ref, _) {
final availability = ref
.watch(
mediaAvailabilityProvider(widget.projectId, asset),
)
.asData
?.value;
final unavailable =
availability != null &&
availability != MediaAvailability.available;
return AppContextMenu(
key: ValueKey(('media-menu', asset.id)),
itemsBuilder: (_) {
final available = ref
.read(projectsProvider)
.asData
?.value;
final canEdit =
available?.activeProject?.id == widget.projectId &&
available?.projectBusy == false &&
!_checkingDrop;
final sequence = timeline?.activeSequenceId;
return [
AppMenuItem(
label: context.l10n.addToTimeline,
icon: Icons.add,
onPressed:
canEdit &&
!unavailable &&
sequence != null &&
available?.timeline?.id == timelineId
? () =>
_action(() => _browser.insertAsset(asset))
: null,
),
AppMenuItem(
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
onPressed: canEdit ? () => _rename(asset) : null,
),
AppMenuItem(
label: defaultTargetPlatform == TargetPlatform.macOS
? context.l10n.revealFinder
: context.l10n.revealFileManager,
icon: Icons.folder_open,
onPressed: canEdit && _desktop
? () => _action(() => _browser.reveal(asset))
: null,
),
const AppMenuSeparator(),
AppMenuItem(
label: context.l10n.removeMedia,
icon: Icons.delete_outline,
destructive: true,
onPressed: canEdit ? () => _remove(asset) : null,
),
];
},
child: Listener(
onPointerDown: (event) {
if (event.buttons == 2) {
setState(() => _selectedAssetId = asset.id);
}
},
child: _SelectableAsset(
key: ValueKey(asset.id),
grid: _isGrid,
drag: MediaAssetDrag(
projectId: widget.projectId,
assetId: asset.id,
),
name: asset.name,
draggable:
widget.draggable &&
!workspace!.projectBusy &&
!_checkingDrop &&
!unavailable,
selected: _selectedAssetId == asset.id,
onTap: () => _browser.selectAsset(asset),
child: _assetTile(asset, availability),
),
),
);
},
);
}
return ScrollEdgeFadeBuilder(
key: ValueKey(('media-scroll-fade', widget.projectId, _isGrid)),
builder: (controller) => !_isGrid
? ListView.separated(
key: PageStorageKey(('media-list', widget.projectId)),
controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact),
itemCount: assets.length,
itemBuilder: item,
separatorBuilder: (_, _) =>
const SizedBox(height: AppSpacing.small),
)
: GridView.builder(
key: PageStorageKey(('media-grid', widget.projectId)),
controller: controller,
padding: const EdgeInsets.all(AppSpacing.compact),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: columns,
crossAxisSpacing: spacing,
mainAxisSpacing: AppSpacing.compact,
mainAxisExtent:
tileWidth * 9 / 16 +
AppSpacing.small +
labelHeight +
2,
),
itemCount: assets.length,
itemBuilder: item,
),
);
},
);
}
Widget _assetTile(AssetDocument asset, MediaAvailability? availability) {
final unavailable =
availability != null && availability != MediaAvailability.available;
final cover = unavailable
? AspectRatio(
aspectRatio: 16 / 9,
child: _isGrid
? UnavailableMediaPlaceholder(availability: availability)
: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: Center(
child: Text(
availability == MediaAvailability.missing
? context.l10n.mediaMissing
: context.l10n.mediaUnavailable,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.error,
),
),
),
),
)
: !_isGrid &&
const {'audio', 'video', 'image'}.contains(asset.metadata['kind'])
? MediaAssetStrip(asset: asset)
: switch (asset.metadata['kind']) {
'video' ||
'image' => VisualAssetTile(asset: asset, showName: false),
'audio' => AudioAssetTile(asset: asset, showName: false),
_ => AspectRatio(
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: const Icon(Icons.insert_drive_file_outlined),
),
),
};
final name = Tooltip(
// Hover still shows the full name; touch long press belongs to actions.
triggerMode: TooltipTriggerMode.manual,
message: asset.name,
child: Text(
asset.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ClipRRect(
borderRadius: BorderRadius.circular(6),
child: Stack(
children: [
if (!_isGrid)
SizedBox(height: MediaAssetStrip.height, child: cover)
else
cover,
Positioned(
top: 4,
right: 4,
child: MediaAssetDuration(asset: asset),
),
],
),
),
const SizedBox(height: AppSpacing.small),
name,
],
);
}
}
class _SelectableAsset extends StatelessWidget {
const _SelectableAsset({
super.key,
required this.grid,
required this.selected,
required this.drag,
required this.name,
required this.draggable,
required this.onTap,
required this.child,
});
final bool selected;
final bool grid;
final MediaAssetDrag drag;
final String name;
final bool draggable;
final VoidCallback onTap;
final Widget child;
@override
Widget build(BuildContext context) {
final selectionDecoration = BoxDecoration(
borderRadius: BorderRadius.circular(6),
border: Border.all(color: Theme.of(context).colorScheme.primary),
);
final tile = Semantics(
selected: selected,
child: InkWell(
onTap: onTap,
hoverColor: Colors.transparent,
highlightColor: Colors.transparent,
splashFactory: NoSplash.splashFactory,
child: Stack(
children: [
child,
if (selected && !grid)
Positioned(
top: 0,
left: 0,
right: 0,
height: MediaAssetStrip.height,
child: IgnorePointer(
child: DecoratedBox(decoration: selectionDecoration),
),
),
if (selected && grid)
Positioned(
top: 0,
left: 0,
right: 0,
child: IgnorePointer(
child: AspectRatio(
aspectRatio: 16 / 9,
child: DecoratedBox(decoration: selectionDecoration),
),
),
),
],
),
),
);
return Draggable<MediaAssetDrag>(
data: drag,
maxSimultaneousDrags: draggable ? 1 : 0,
dragAnchorStrategy: pointerDragAnchorStrategy,
onDragStarted: onTap,
onDragEnd: (_) => drag.feedbackVisible.value = true,
feedback: ValueListenableBuilder<bool>(
valueListenable: drag.feedbackVisible,
builder: (context, visible, child) =>
visible ? child! : const SizedBox.shrink(),
child: Material(
elevation: 4,
color: Theme.of(context).colorScheme.surfaceContainerHigh,
child: SizedBox(
width: 144,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.small),
child: Text(
name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
),
),
),
child: tile,
);
}
}
@@ -0,0 +1,194 @@
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/foundation.dart';
import '../../integrations/platform/file_picker.dart';
import '../../integrations/platform/platform_capabilities.dart';
import '../../workspace/media_file_extensions.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/media_import.dart';
import '../../workspace/media_import_feedback.dart';
import '../../workspace/preview_target.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
enum MediaFilter {
all(null),
image('image'),
video('video'),
audio('audio');
const MediaFilter(this.kind);
final String? kind;
}
final mediaBrowserProvider = Provider.family<MediaBrowserController, String>((
ref,
projectId,
) {
final controller = MediaBrowserController(ref, projectId);
ref.onDispose(controller.dispose);
return controller;
});
/// Project-specific browsing choices are shared by every media presentation.
class MediaBrowserController extends ChangeNotifier {
MediaBrowserController(this._ref, this.projectId);
final Ref _ref;
final String projectId;
final feedback = MediaImportFeedbackController();
bool _working = false;
bool _disposed = false;
bool get busy =>
_working || _ref.read(externalMediaImportProvider(projectId)).isLoading;
bool get active =>
!_disposed &&
_ref.mounted &&
_ref.read(projectsProvider).value?.activeProject?.id == projectId;
bool get canEdit =>
active &&
_ref.read(projectsProvider).value?.projectBusy == false &&
!busy;
bool get canImport =>
canEdit && _ref.read(platformCapabilitiesProvider).localFileSelection;
Future<ExternalMediaSelection?> pickFiles() => _import(
() => _ref
.read(filePickerProvider)
.pickFiles(allowedExtensions: selectableMediaFileExtensions),
);
Future<ExternalMediaSelection?> importFiles(List<ExternalMediaFile> files) =>
_import(() async => files);
Future<ExternalMediaSelection?> _import(
Future<List<ExternalMediaFile>> Function() select,
) async {
if (!canImport) return null;
_working = true;
notifyListeners();
try {
final files = await select();
if (!active ||
files.isEmpty ||
_ref.read(projectsProvider).value?.projectBusy != false) {
return null;
}
final result = await _ref
.read(externalMediaImportProvider(projectId).notifier)
.importFiles(files);
final asset = result?.selected.firstOrNull;
if (!_disposed && asset != null) {
_selectedAssetId = asset.id;
if (_filter != MediaFilter.all &&
asset.metadata['kind'] != _filter.kind) {
_filter = MediaFilter.all;
}
}
if (!_disposed) feedback.recordResult(result);
return result;
} catch (_) {
if (!_disposed) feedback.recordFailure();
rethrow;
} finally {
_working = false;
if (!_disposed) notifyListeners();
}
}
void selectAsset(AssetDocument asset) {
selectedAssetId = asset.id;
_ref.invalidate(mediaAvailabilityProvider(projectId, asset));
final timeline = _ref.read(projectsProvider).value?.timeline;
if (timeline != null) {
_ref
.read(previewNavigationProvider(projectId, timeline.id).notifier)
.showAsset(asset);
}
}
Future<bool> rename(AssetDocument asset, String name) async =>
canEdit &&
await _ref
.read(projectsProvider.notifier)
.editMediaAsset(projectId, asset.id, name: name);
Future<bool> remove(AssetDocument asset) async {
if (!canEdit) return false;
final removed = await _ref
.read(projectsProvider.notifier)
.editMediaAsset(projectId, asset.id);
if (removed && !_disposed && _selectedAssetId == asset.id) {
selectedAssetId = null;
}
return removed;
}
Future<bool> reveal(AssetDocument asset) async =>
canEdit &&
await _ref
.read(projectsProvider.notifier)
.revealMediaAsset(projectId, asset);
Future<bool> insertAsset(AssetDocument asset) async {
if (!canEdit ||
_ref.read(mediaAvailabilityProvider(projectId, asset)).value !=
MediaAvailability.available) {
return false;
}
final timelineId = _ref.read(projectsProvider).value?.timeline?.id;
if (timelineId == null) return false;
final session = _ref
.read(editorTimelineProvider(projectId, timelineId))
.value;
final sequence = session?.activeSequenceId;
if (session == null || sequence == null) return false;
final inserted = await _ref
.read(projectsProvider.notifier)
.insertTimelineAsset(
projectId: projectId,
session: session,
sequenceId: sequence,
assetId: asset.id,
position: session.view(sequence).playheadTick,
);
if (inserted && active) {
_ref
.read(previewNavigationProvider(projectId, timelineId).notifier)
.showTimeline();
}
return inserted;
}
@override
void dispose() {
_disposed = true;
feedback.dispose();
super.dispose();
}
String? _selectedAssetId;
MediaFilter _filter = MediaFilter.all;
bool _grid = true;
String? get selectedAssetId => _selectedAssetId;
MediaFilter get filter => _filter;
bool get grid => _grid;
set selectedAssetId(String? value) {
_selectedAssetId = value;
notifyListeners();
}
set filter(MediaFilter value) {
_filter = value;
notifyListeners();
}
set grid(bool value) {
_grid = value;
notifyListeners();
}
}
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/media_import.dart';
import '../../workspace/media_import_feedback.dart';
import 'media_browser_controller.dart';
Future<void> pickMediaFiles(MediaBrowserController browser) async {
try {
await browser.pickFiles();
} catch (_) {
// The controller retains the failure for its next visible presentation.
}
}
Future<void> importMediaFiles(
MediaBrowserController browser,
List<ExternalMediaFile> files,
) async {
try {
await browser.importFiles(files);
} catch (_) {
// The controller retains the failure for its next visible presentation.
}
}
class MediaImportFeedbackListener extends StatefulWidget {
const MediaImportFeedbackListener({
super.key,
required this.feedback,
required this.child,
});
final MediaImportFeedbackController feedback;
final Widget child;
@override
State<MediaImportFeedbackListener> createState() =>
_MediaImportFeedbackListenerState();
}
class _MediaImportFeedbackListenerState
extends State<MediaImportFeedbackListener> {
bool _scheduled = false;
bool get _visible =>
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
@override
void initState() {
super.initState();
widget.feedback.addListener(_schedule);
}
@override
void didChangeDependencies() {
super.didChangeDependencies();
_schedule();
}
@override
void didUpdateWidget(covariant MediaImportFeedbackListener oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.feedback != widget.feedback) {
oldWidget.feedback.removeListener(_schedule);
widget.feedback.addListener(_schedule);
}
_schedule();
}
void _schedule() {
if (_scheduled || !widget.feedback.hasPending) return;
_scheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
_scheduled = false;
if (!mounted || !_visible || !widget.feedback.hasPending) return;
final messenger = ScaffoldMessenger.maybeOf(context);
if (messenger == null) return;
for (final result in widget.feedback.takePending()) {
final messages = [
if (result == null) context.l10n.operationFailed,
for (final failure
in result?.result?.failures ?? <MediaImportFailure>[])
'${failure.name}: ${context.l10n.failureMessage(failure.failure)}',
if (result?.failed == true) context.l10n.noImportableFiles,
];
messenger.showSnackBar(
SnackBar(
content: ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 180),
child: SingleChildScrollView(child: Text(messages.join('\n'))),
),
),
);
}
});
WidgetsBinding.instance.ensureVisualUpdate();
}
@override
void dispose() {
widget.feedback.removeListener(_schedule);
super.dispose();
}
@override
Widget build(BuildContext context) => widget.child;
}
+168
View File
@@ -0,0 +1,168 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_availability.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_provider.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
class MediaBrowserPage extends StatelessWidget {
const MediaBrowserPage({super.key, required this.projectId});
final String projectId;
@override
Widget build(BuildContext context) => TouchMediaBrowser(
key: const Key('media-browser-page'),
projectId: projectId,
);
}
class MediaBrowserDrawer extends StatelessWidget {
const MediaBrowserDrawer({super.key, required this.projectId});
final String projectId;
@override
Widget build(BuildContext context) => TouchMediaBrowser(
key: const Key('media-browser-drawer'),
projectId: projectId,
);
}
/// Touch controls share browser commands and item components with desktop.
class TouchMediaBrowser extends ConsumerWidget {
const TouchMediaBrowser({super.key, required this.projectId});
final String projectId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final browser = ref.watch(mediaBrowserProvider(projectId));
ref.watch(externalMediaImportProvider(projectId));
final workspace = ref.watch(projectsProvider).value;
final timelineId = workspace?.activeProject?.id == projectId
? workspace?.timeline?.id
: null;
final timeline = timelineId == null
? null
: ref.watch(editorTimelineProvider(projectId, timelineId)).value;
return ListenableBuilder(
listenable: browser,
builder: (context, _) {
final selected = workspace?.assets
.where((asset) => asset.id == browser.selectedAssetId)
.firstOrNull;
final availability = selected == null
? null
: ref.watch(mediaAvailabilityProvider(projectId, selected)).value;
final canInsert =
browser.canEdit &&
selected != null &&
timeline?.activeSequenceId != null &&
availability == MediaAvailability.available;
return MediaImportFeedbackListener(
feedback: browser.feedback,
child: Material(
key: const Key('media-panel-surface'),
child: Column(
children: [
SizedBox(
key: const Key('media-panel-header'),
height: 56,
child: Row(
children: [
SizedBox.square(
dimension: 48,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: browser.canImport
? () => pickMediaFiles(browser)
: null,
icon: const Icon(Icons.add),
),
),
Expanded(
child: DropdownButton<MediaFilter>(
key: const Key('media-category-picker'),
isExpanded: true,
underline: const SizedBox.shrink(),
value: browser.filter,
items: [
for (final filter in MediaFilter.values)
DropdownMenuItem(
value: filter,
child: Text(filter.label(context)),
),
],
onChanged: (filter) {
if (filter != null) browser.filter = filter;
},
),
),
SizedBox.square(
dimension: 48,
child: IconButton(
key: const Key('media-layout-toggle'),
tooltip: browser.grid
? context.l10n.listLayout
: context.l10n.gridLayout,
icon: Icon(
browser.grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
),
onPressed: () => browser.grid = !browser.grid,
),
),
],
),
),
if (browser.busy) const LinearProgressIndicator(),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
projectId: projectId,
grid: browser.grid,
),
),
Padding(
padding: const EdgeInsets.all(8),
child: SizedBox(
width: double.infinity,
child: FilledButton.icon(
key: const Key('media-add-selected'),
style: FilledButton.styleFrom(
minimumSize: const Size(0, 48),
),
onPressed: !canInsert
? null
: () async {
final inserted = await browser.insertAsset(
selected,
);
if (!inserted && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(context.l10n.operationFailed),
),
);
}
},
icon: const Icon(Icons.add),
label: Text(
context.l10n.addToTimeline,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
),
);
},
);
}
}
+213
View File
@@ -0,0 +1,213 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
import '../../integrations/platform/native_project_drop_region.dart';
import '../../integrations/platform/platform_capabilities.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/drop_to_add_overlay.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/projects.dart';
import 'media_browser_body.dart';
import 'media_browser_controller.dart';
import 'media_browser_feedback.dart';
/// Desktop presentation owns compact controls and native file dragging.
class MediaPanel extends ConsumerStatefulWidget {
const MediaPanel({
super.key,
required this.projectId,
this.backgroundColor,
this.grid,
this.onGridChanged,
}) : assert((grid == null) == (onGridChanged == null));
final String projectId;
final Color? backgroundColor;
final bool? grid;
final ValueChanged<bool>? onGridChanged;
@override
ConsumerState<MediaPanel> createState() => _MediaPanelState();
}
class _MediaPanelState extends ConsumerState<MediaPanel> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
ref.watch(projectsProvider);
final browser = ref.watch(mediaBrowserProvider(widget.projectId));
ref.watch(externalMediaImportProvider(widget.projectId));
final nativeDrop = ref.watch(platformCapabilitiesProvider).nativeFileDrop;
return ListenableBuilder(
listenable: browser,
builder: (context, _) {
final grid = widget.grid ?? browser.grid;
final visible =
TickerMode.valuesOf(context).enabled &&
(ModalRoute.of(context)?.isCurrent ?? true);
final enabled = browser.canImport && visible;
void toggleGrid() {
final next = !grid;
if (widget.onGridChanged case final onChanged?) {
onChanged(next);
} else {
browser.grid = next;
}
}
final content = MediaImportFeedbackListener(
feedback: browser.feedback,
child: Material(
key: const Key('media-panel-surface'),
color: widget.backgroundColor,
child: Stack(
fit: StackFit.expand,
children: [
Column(
children: [
SizedBox(
key: const Key('media-panel-header'),
height: AppControlSize.panelToolbar,
child: Padding(
padding: const EdgeInsets.all(AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) {
final compact = constraints.maxWidth < 180;
final controls = Row(
mainAxisSize: compact
? MainAxisSize.min
: MainAxisSize.max,
children: [
if (compact)
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-import-button'),
tooltip: context.l10n.importMedia,
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
),
)
else
SizedBox(
height: AppControlSize.headerButton,
child: TextButton.icon(
key: const Key('media-import-button'),
style: AppTheme.toolbarButtonStyle(
context,
),
onPressed: enabled
? () => pickMediaFiles(browser)
: null,
icon: const Icon(
Icons.add,
size: AppIconSize.header,
),
label: Text(context.l10n.importMedia),
),
),
if (compact)
const SizedBox(width: AppSpacing.tiny)
else
const Spacer(),
SizedBox(
width: 76,
child: AppSelect<MediaFilter>(
emptyLabel: context.l10n.noMatchingOptions,
label: context.l10n.mediaCategory,
outlined: false,
controlHeight: AppControlSize.headerButton,
textStyle: AppTheme.toolbarTextStyle(
context,
),
value: browser.filter,
onChanged: (value) =>
browser.filter = value,
options: [
for (final filter in MediaFilter.values)
AppSelectOption(
filter,
filter.label(context),
),
],
),
),
const SizedBox(width: AppSpacing.tiny),
SizedBox.square(
dimension: AppControlSize.headerButton,
child: IconButton(
key: const Key('media-layout-toggle'),
onPressed: toggleGrid,
icon: Icon(
grid
? Icons.view_list_outlined
: Icons.grid_view_outlined,
size: AppIconSize.header,
),
tooltip: grid
? context.l10n.listLayout
: context.l10n.gridLayout,
),
),
],
);
return compact
? SingleChildScrollView(
key: const Key('media-header-scroll'),
scrollDirection: Axis.horizontal,
child: controls,
)
: controls;
},
),
),
),
Expanded(
key: const Key('media-panel-body'),
child: MediaBrowserBody(
projectId: widget.projectId,
grid: grid,
draggable: true,
),
),
],
),
if (browser.busy)
const DelayedLoadingIndicator(
child: Align(
alignment: Alignment.topCenter,
child: LinearProgressIndicator(),
),
),
if (_hovering && enabled)
const DropToAddOverlay(key: Key('media-drop-highlight')),
],
),
),
);
if (!nativeDrop) return content;
return NativeProjectDropRegion(
enabled: visible && browser.active && (enabled || browser.busy),
onEnter: (_) {
if (enabled) setState(() => _hovering = true);
},
onExit: () {
if (mounted && _hovering) setState(() => _hovering = false);
},
onDrop: (files) async {
setState(() => _hovering = false);
await importMediaFiles(browser, files);
},
child: content,
);
},
);
}
}
@@ -0,0 +1,26 @@
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'processing_targets.freezed.dart';
/// A fixed timeline target, retained even if selection or active sequence changes.
@freezed
abstract class TranscriptionClipTarget with _$TranscriptionClipTarget {
const factory TranscriptionClipTarget({
required SequenceId sequence,
required String clipId,
required String mediaId,
required String name,
required int audioStream,
}) = _TranscriptionClipTarget;
}
@freezed
abstract class BackgroundRemovalClipTarget with _$BackgroundRemovalClipTarget {
const factory BackgroundRemovalClipTarget({
required SequenceId sequence,
required String clipId,
required String mediaId,
required String name,
}) = _BackgroundRemovalClipTarget;
}
@@ -0,0 +1,855 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'processing_targets.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$TranscriptionClipTarget {
SequenceId get sequence;
String get clipId;
String get mediaId;
String get name;
int get audioStream;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$TranscriptionClipTargetCopyWith<TranscriptionClipTarget> get copyWith =>
_$TranscriptionClipTargetCopyWithImpl<TranscriptionClipTarget>(
this as TranscriptionClipTarget,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as TranscriptionClipTarget;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is TranscriptionClipTarget &&
(identical(other.sequence, _this.sequence) ||
other.sequence == _this.sequence) &&
(identical(other.clipId, _this.clipId) ||
other.clipId == _this.clipId) &&
(identical(other.mediaId, _this.mediaId) ||
other.mediaId == _this.mediaId) &&
(identical(other.name, _this.name) || other.name == _this.name) &&
(identical(other.audioStream, _this.audioStream) ||
other.audioStream == _this.audioStream));
}
@override
int get hashCode {
final _this = this as TranscriptionClipTarget;
return Object.hash(
runtimeType,
_this.sequence,
_this.clipId,
_this.mediaId,
_this.name,
_this.audioStream,
);
}
@override
String toString() {
final _this = this as TranscriptionClipTarget;
return 'TranscriptionClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name}, audioStream: ${_this.audioStream})';
}
}
/// @nodoc
abstract mixin class $TranscriptionClipTargetCopyWith<$Res> {
factory $TranscriptionClipTargetCopyWith(
TranscriptionClipTarget value,
$Res Function(TranscriptionClipTarget) _then,
) = _$TranscriptionClipTargetCopyWithImpl;
@useResult
$Res call({
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
});
}
/// @nodoc
class _$TranscriptionClipTargetCopyWithImpl<$Res>
implements $TranscriptionClipTargetCopyWith<$Res> {
_$TranscriptionClipTargetCopyWithImpl(this._self, this._then);
final TranscriptionClipTarget _self;
final $Res Function(TranscriptionClipTarget) _then;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
Object? audioStream = null,
}) {
return _then(
TranscriptionClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
audioStream: null == audioStream
? _self.audioStream
: audioStream // ignore: cast_nullable_to_non_nullable
as int,
),
);
}
}
/// Adds pattern-matching-related methods to [TranscriptionClipTarget].
extension TranscriptionClipTargetPatterns on TranscriptionClipTarget {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_TranscriptionClipTarget value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_TranscriptionClipTarget value) $default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_TranscriptionClipTarget value)? $default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
_that.audioStream,
);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
)
$default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget():
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
_that.audioStream,
);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
)?
$default,
) {
final _that = this;
switch (_that) {
case _TranscriptionClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
_that.audioStream,
);
case _:
return null;
}
}
}
/// @nodoc
class _TranscriptionClipTarget implements TranscriptionClipTarget {
const _TranscriptionClipTarget({
required this.sequence,
required this.clipId,
required this.mediaId,
required this.name,
required this.audioStream,
});
@override
final SequenceId sequence;
@override
final String clipId;
@override
final String mediaId;
@override
final String name;
@override
final int audioStream;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$TranscriptionClipTargetCopyWith<_TranscriptionClipTarget> get copyWith =>
__$TranscriptionClipTargetCopyWithImpl<_TranscriptionClipTarget>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _TranscriptionClipTarget &&
(identical(other.sequence, sequence) ||
other.sequence == sequence) &&
(identical(other.clipId, clipId) || other.clipId == clipId) &&
(identical(other.mediaId, mediaId) || other.mediaId == mediaId) &&
(identical(other.name, name) || other.name == name) &&
(identical(other.audioStream, audioStream) ||
other.audioStream == audioStream));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
sequence,
clipId,
mediaId,
name,
audioStream,
);
}
@override
String toString() {
return 'TranscriptionClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name, audioStream: $audioStream)';
}
}
/// @nodoc
abstract mixin class _$TranscriptionClipTargetCopyWith<$Res>
implements $TranscriptionClipTargetCopyWith<$Res> {
factory _$TranscriptionClipTargetCopyWith(
_TranscriptionClipTarget value,
$Res Function(_TranscriptionClipTarget) _then,
) = __$TranscriptionClipTargetCopyWithImpl;
@override
@useResult
$Res call({
SequenceId sequence,
String clipId,
String mediaId,
String name,
int audioStream,
});
}
/// @nodoc
class __$TranscriptionClipTargetCopyWithImpl<$Res>
implements _$TranscriptionClipTargetCopyWith<$Res> {
__$TranscriptionClipTargetCopyWithImpl(this._self, this._then);
final _TranscriptionClipTarget _self;
final $Res Function(_TranscriptionClipTarget) _then;
/// Create a copy of TranscriptionClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
Object? audioStream = null,
}) {
return _then(
_TranscriptionClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
audioStream: null == audioStream
? _self.audioStream
: audioStream // ignore: cast_nullable_to_non_nullable
as int,
),
);
}
}
/// @nodoc
mixin _$BackgroundRemovalClipTarget {
SequenceId get sequence;
String get clipId;
String get mediaId;
String get name;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$BackgroundRemovalClipTargetCopyWith<BackgroundRemovalClipTarget>
get copyWith =>
_$BackgroundRemovalClipTargetCopyWithImpl<BackgroundRemovalClipTarget>(
this as BackgroundRemovalClipTarget,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as BackgroundRemovalClipTarget;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is BackgroundRemovalClipTarget &&
(identical(other.sequence, _this.sequence) ||
other.sequence == _this.sequence) &&
(identical(other.clipId, _this.clipId) ||
other.clipId == _this.clipId) &&
(identical(other.mediaId, _this.mediaId) ||
other.mediaId == _this.mediaId) &&
(identical(other.name, _this.name) || other.name == _this.name));
}
@override
int get hashCode {
final _this = this as BackgroundRemovalClipTarget;
return Object.hash(
runtimeType,
_this.sequence,
_this.clipId,
_this.mediaId,
_this.name,
);
}
@override
String toString() {
final _this = this as BackgroundRemovalClipTarget;
return 'BackgroundRemovalClipTarget(sequence: ${_this.sequence}, clipId: ${_this.clipId}, mediaId: ${_this.mediaId}, name: ${_this.name})';
}
}
/// @nodoc
abstract mixin class $BackgroundRemovalClipTargetCopyWith<$Res> {
factory $BackgroundRemovalClipTargetCopyWith(
BackgroundRemovalClipTarget value,
$Res Function(BackgroundRemovalClipTarget) _then,
) = _$BackgroundRemovalClipTargetCopyWithImpl;
@useResult
$Res call({SequenceId sequence, String clipId, String mediaId, String name});
}
/// @nodoc
class _$BackgroundRemovalClipTargetCopyWithImpl<$Res>
implements $BackgroundRemovalClipTargetCopyWith<$Res> {
_$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then);
final BackgroundRemovalClipTarget _self;
final $Res Function(BackgroundRemovalClipTarget) _then;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
}) {
return _then(
BackgroundRemovalClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
),
);
}
}
/// Adds pattern-matching-related methods to [BackgroundRemovalClipTarget].
extension BackgroundRemovalClipTargetPatterns on BackgroundRemovalClipTarget {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_BackgroundRemovalClipTarget value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_BackgroundRemovalClipTarget value) $default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_BackgroundRemovalClipTarget value)? $default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
)?
$default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
)
$default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget():
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(
SequenceId sequence,
String clipId,
String mediaId,
String name,
)?
$default,
) {
final _that = this;
switch (_that) {
case _BackgroundRemovalClipTarget() when $default != null:
return $default(
_that.sequence,
_that.clipId,
_that.mediaId,
_that.name,
);
case _:
return null;
}
}
}
/// @nodoc
class _BackgroundRemovalClipTarget implements BackgroundRemovalClipTarget {
const _BackgroundRemovalClipTarget({
required this.sequence,
required this.clipId,
required this.mediaId,
required this.name,
});
@override
final SequenceId sequence;
@override
final String clipId;
@override
final String mediaId;
@override
final String name;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$BackgroundRemovalClipTargetCopyWith<_BackgroundRemovalClipTarget>
get copyWith =>
__$BackgroundRemovalClipTargetCopyWithImpl<_BackgroundRemovalClipTarget>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _BackgroundRemovalClipTarget &&
(identical(other.sequence, sequence) ||
other.sequence == sequence) &&
(identical(other.clipId, clipId) || other.clipId == clipId) &&
(identical(other.mediaId, mediaId) || other.mediaId == mediaId) &&
(identical(other.name, name) || other.name == name));
}
@override
int get hashCode {
return Object.hash(runtimeType, sequence, clipId, mediaId, name);
}
@override
String toString() {
return 'BackgroundRemovalClipTarget(sequence: $sequence, clipId: $clipId, mediaId: $mediaId, name: $name)';
}
}
/// @nodoc
abstract mixin class _$BackgroundRemovalClipTargetCopyWith<$Res>
implements $BackgroundRemovalClipTargetCopyWith<$Res> {
factory _$BackgroundRemovalClipTargetCopyWith(
_BackgroundRemovalClipTarget value,
$Res Function(_BackgroundRemovalClipTarget) _then,
) = __$BackgroundRemovalClipTargetCopyWithImpl;
@override
@useResult
$Res call({SequenceId sequence, String clipId, String mediaId, String name});
}
/// @nodoc
class __$BackgroundRemovalClipTargetCopyWithImpl<$Res>
implements _$BackgroundRemovalClipTargetCopyWith<$Res> {
__$BackgroundRemovalClipTargetCopyWithImpl(this._self, this._then);
final _BackgroundRemovalClipTarget _self;
final $Res Function(_BackgroundRemovalClipTarget) _then;
/// Create a copy of BackgroundRemovalClipTarget
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({
Object? sequence = null,
Object? clipId = null,
Object? mediaId = null,
Object? name = null,
}) {
return _then(
_BackgroundRemovalClipTarget(
sequence: null == sequence
? _self.sequence
: sequence // ignore: cast_nullable_to_non_nullable
as SequenceId,
clipId: null == clipId
? _self.clipId
: clipId // ignore: cast_nullable_to_non_nullable
as String,
mediaId: null == mediaId
? _self.mediaId
: mediaId // ignore: cast_nullable_to_non_nullable
as String,
name: null == name
? _self.name
: name // ignore: cast_nullable_to_non_nullable
as String,
),
);
}
}
+267
View File
@@ -0,0 +1,267 @@
import 'package:cutdex/diagnostics/app_diagnostics.dart';
import 'package:cutdex/errors/app_failure.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../integrations/runtime/processing_configuration.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
part 'subtitle_download.g.dart';
part 'subtitle_download.freezed.dart';
enum SubtitleStartFailure { start, download, engine }
@freezed
abstract class SubtitleRequest with _$SubtitleRequest {
const factory SubtitleRequest({
required EditorTimelineSession session,
required SequenceId? sequence,
AssetDocument? asset,
TranscriptionClipTarget? target,
@Default('auto') String language,
@Default('none') String targetLanguage,
}) = _SubtitleRequest;
}
@freezed
sealed class SubtitleDownloadState with _$SubtitleDownloadState {
const SubtitleDownloadState._();
const factory SubtitleDownloadState.idle() = SubtitleIdle;
const factory SubtitleDownloadState.starting(SubtitleRequest request) =
SubtitleStarting;
const factory SubtitleDownloadState.downloading(
SubtitleRequest request, {
required ProcessingCapability stage,
ProcessingResourceRepository? repository,
@Default(0) double progress,
@Default(false) bool paused,
}) = SubtitleDownloading;
const factory SubtitleDownloadState.started(SubtitleRequest request) =
SubtitleStarted;
const factory SubtitleDownloadState.cancelled(SubtitleRequest request) =
SubtitleCancelled;
const factory SubtitleDownloadState.failed(
SubtitleRequest request,
SubtitleStartFailure failure,
) = SubtitleFailed;
SubtitleRequest? get request => switch (this) {
SubtitleIdle() => null,
SubtitleStarting(:final request) ||
SubtitleDownloading(:final request) ||
SubtitleStarted(:final request) ||
SubtitleCancelled(:final request) ||
SubtitleFailed(:final request) => request,
};
bool get running => this is SubtitleStarting || this is SubtitleDownloading;
}
/// Owns the download and task handoff even when its dialog is closed.
@Riverpod(keepAlive: true)
class SubtitleDownload extends _$SubtitleDownload {
ProcessingResourceRepository? _repository;
bool _cancelled = false;
@override
SubtitleDownloadState build() {
ref.onDispose(() {
_cancelled = true;
_repository?.cancelSubtitleResources();
});
return const SubtitleDownloadState.idle();
}
Future<void> start(SubtitleRequest request, {bool download = false}) async {
if (state.running) return;
_cancelled = false;
var resourceInstalled = false;
final session = request.session;
final release = session.retainViews();
state = download
? SubtitleDownloadState.downloading(
request,
stage: session.transcriptions?.recognitionAvailable == true
? ProcessingCapability.translation
: ProcessingCapability.transcription,
)
: SubtitleDownloadState.starting(request);
ProcessingResourceRepository? repository;
void changed() {
if (!ref.mounted || state is! SubtitleDownloading) return;
final current = state as SubtitleDownloading;
state = current.copyWith(
paused: repository?.subtitlePaused ?? current.paused,
);
}
try {
final service = session.transcriptions;
if (download) {
final loaded = await ref.read(
processingResourceRepositoryProvider.future,
);
repository = loaded;
if (_cancelled || !ref.mounted) {
return;
}
_repository = loaded;
final pausedBeforeLoad = (state as SubtitleDownloading).paused;
state = (state as SubtitleDownloading).copyWith(repository: loaded);
loaded.addListener(changed);
final install = loaded.ensureSubtitleResources(
available: {
if (service?.recognitionAvailable == true)
ProcessingCapability.transcription,
if (service?.translationAvailable == true)
ProcessingCapability.translation,
},
onProgress: (stage, progress) {
if (!ref.mounted) return;
if (state case SubtitleDownloading(:final paused)) {
state = SubtitleDownloadState.downloading(
request,
stage: stage,
repository: loaded,
progress: progress,
paused: paused,
);
}
},
);
if (pausedBeforeLoad) loaded.pauseSubtitleResources();
await install;
resourceInstalled = true;
if (_cancelled || !ref.mounted) {
return;
}
final processing = ProcessingConfiguration.configured(
diagnostics: AppDiagnostics.report,
resourcesRoot: loaded.root.parent.path,
);
final speechBackend = service?.backend ?? processing?.backend;
final speechModel =
service?.modelDirectory ?? processing?.transcriptionModel;
final translationBackend =
service?.translationBackend ?? processing?.backend;
final translationModel =
service?.translationModel ?? processing?.translationModel;
if (speechBackend == null ||
speechModel == null ||
translationBackend == null ||
translationModel == null) {
throw AppException(AppErrorCode.subtitleEngineUnavailable);
}
session.configureProcessing(
transcriptionBackend: speechBackend,
transcriptionModel: speechModel,
translationBackend: translationBackend,
translationModel: translationModel,
);
}
if (_cancelled || !ref.mounted) {
return;
}
await _startSubtitles(request);
if (ref.mounted) state = SubtitleDownloadState.started(request);
} on ProcessingResourceCancelledException {
if (ref.mounted) state = SubtitleDownloadState.cancelled(request);
} catch (_) {
if (ref.mounted) {
state = SubtitleDownloadState.failed(
request,
!download
? SubtitleStartFailure.start
: resourceInstalled
? SubtitleStartFailure.engine
: SubtitleStartFailure.download,
);
}
} finally {
repository?.removeListener(changed);
_repository = null;
if (ref.mounted && _cancelled && state.running) {
state = SubtitleDownloadState.cancelled(request);
}
release();
}
}
void togglePause() {
if (state case SubtitleDownloading(:final paused)) {
state = (state as SubtitleDownloading).copyWith(paused: !paused);
if (paused) {
_repository?.resumeSubtitleResources();
} else {
_repository?.pauseSubtitleResources();
}
}
}
void cancel() {
if (!state.running) return;
_cancelled = true;
_repository?.cancelSubtitleResources();
}
}
Future<void> _startSubtitles(SubtitleRequest request) async {
final mediaId = request.target?.mediaId ?? request.asset?.id;
final name = request.target?.name ?? request.asset?.name ?? mediaId;
final sequence = request.sequence;
if (sequence == null || mediaId == null || name == null) {
throw const CommandRejected(
'missingSequence',
'Sequence or media does not exist',
);
}
await request.session.subtitleWorkflows.start(
sequence: sequence,
command: StartTranscription(
mediaId: mediaId,
clipId: request.target?.clipId,
audioStream: request.target?.audioStream ?? 0,
language: request.language,
),
name: name,
targetLanguage: request.targetLanguage,
);
}
/// Configured sessions can start independently of another project's download.
@riverpod
class SubtitleStart extends _$SubtitleStart {
@override
SubtitleDownloadState build(EditorTimelineSession session) =>
const SubtitleDownloadState.idle();
void reset() {
if (!state.running) state = const SubtitleDownloadState.idle();
}
Future<void> start(SubtitleRequest request) async {
if (state.running) return;
final lease = ref.keepAlive();
final release = session.retainViews();
state = SubtitleDownloadState.starting(request);
try {
await _startSubtitles(request);
if (ref.mounted) state = SubtitleDownloadState.started(request);
} catch (_) {
if (ref.mounted) {
state = SubtitleDownloadState.failed(
request,
SubtitleStartFailure.start,
);
}
} finally {
release();
lease.close();
}
}
}
File diff suppressed because it is too large. Load diff
+174
View File
@@ -0,0 +1,174 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'subtitle_download.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Owns the download and task handoff even when its dialog is closed.
@ProviderFor(SubtitleDownload)
final subtitleDownloadProvider = SubtitleDownloadProvider._();
/// Owns the download and task handoff even when its dialog is closed.
final class SubtitleDownloadProvider
extends $NotifierProvider<SubtitleDownload, SubtitleDownloadState> {
/// Owns the download and task handoff even when its dialog is closed.
SubtitleDownloadProvider._()
: super(
from: null,
argument: null,
retry: null,
name: r'subtitleDownloadProvider',
isAutoDispose: false,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$subtitleDownloadHash();
@$internal
@override
SubtitleDownload create() => SubtitleDownload();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SubtitleDownloadState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SubtitleDownloadState>(value),
);
}
}
String _$subtitleDownloadHash() => r'2bf89e93b596e3b24f3880279477c91227b261b4';
/// Owns the download and task handoff even when its dialog is closed.
abstract class _$SubtitleDownload extends $Notifier<SubtitleDownloadState> {
SubtitleDownloadState build();
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<SubtitleDownloadState, SubtitleDownloadState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<SubtitleDownloadState, SubtitleDownloadState>,
SubtitleDownloadState,
Object?,
Object?
>;
return element.handleCreate(ref, build);
}
}
/// Configured sessions can start independently of another project's download.
@ProviderFor(SubtitleStart)
final subtitleStartProvider = SubtitleStartFamily._();
/// Configured sessions can start independently of another project's download.
final class SubtitleStartProvider
extends $NotifierProvider<SubtitleStart, SubtitleDownloadState> {
/// Configured sessions can start independently of another project's download.
SubtitleStartProvider._({
required SubtitleStartFamily super.from,
required EditorTimelineSession super.argument,
}) : super(
retry: null,
name: r'subtitleStartProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$subtitleStartHash();
@override
String toString() {
return r'subtitleStartProvider'
''
'($argument)';
}
@$internal
@override
SubtitleStart create() => SubtitleStart();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(SubtitleDownloadState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<SubtitleDownloadState>(value),
);
}
@override
bool operator ==(Object other) {
return other is SubtitleStartProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$subtitleStartHash() => r'3278b419fd819fa4dcc021815280cc1cce72dbb5';
/// Configured sessions can start independently of another project's download.
final class SubtitleStartFamily extends $Family
with
$ClassFamilyOverride<
SubtitleStart,
SubtitleDownloadState,
SubtitleDownloadState,
SubtitleDownloadState,
EditorTimelineSession
> {
SubtitleStartFamily._()
: super(
retry: null,
name: r'subtitleStartProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
/// Configured sessions can start independently of another project's download.
SubtitleStartProvider call(EditorTimelineSession session) =>
SubtitleStartProvider._(argument: session, from: this);
@override
String toString() => r'subtitleStartProvider';
}
/// Configured sessions can start independently of another project's download.
abstract class _$SubtitleStart extends $Notifier<SubtitleDownloadState> {
late final _$args = ref.$arg as EditorTimelineSession;
EditorTimelineSession get session => _$args;
SubtitleDownloadState build(EditorTimelineSession session);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<SubtitleDownloadState, SubtitleDownloadState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<SubtitleDownloadState, SubtitleDownloadState>,
SubtitleDownloadState,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args));
}
}
@@ -0,0 +1,136 @@
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../workspace/timeline_session.dart';
part 'subtitle_task_actions.g.dart';
part 'subtitle_task_actions.freezed.dart';
enum SubtitleActionKind { original, translation, cancel, retry }
@freezed
abstract class SubtitleActionFeedback with _$SubtitleActionFeedback {
const factory SubtitleActionFeedback({
required SubtitleActionKind kind,
int? cueCount,
}) = _SubtitleActionFeedback;
}
@freezed
abstract class SubtitleActionException
with _$SubtitleActionException
implements Exception {
const factory SubtitleActionException(SubtitleActionKind kind, Object cause) =
_SubtitleActionException;
}
/// One operation state is shared by the compact card and its details dialog.
@riverpod
class SubtitleTaskActions extends _$SubtitleTaskActions {
@override
AsyncValue<SubtitleActionFeedback?> build(
EditorTimelineSession session,
String jobId,
) => const AsyncData(null);
Future<List<ElementDto>> candidates(
SubtitleBackgroundTask job, {
bool translated = false,
}) async {
final recognition = job.recognition;
return session.persistence
.timeline(job.sequence)
.exportDto()
.elements
.where((element) {
final binding = element.payloadRef == null
? null
: session.mediaBinding(element.payloadRef!);
return (translated
? binding?.media.uri == recognition.source
: binding?.media.id == recognition.command.mediaId) &&
binding?.audioTrackIndex == recognition.command.audioStream;
})
.toList();
}
Future<void> apply(
SubtitleBackgroundTask job,
String clipId, {
required String expectedVersion,
bool translated = false,
}) => _run(
translated ? SubtitleActionKind.translation : SubtitleActionKind.original,
() async {
final recognition = job.recognition;
final outcome = translated
? await session.executeCommand(
job.sequence,
ApplySubtitleTranslation(
source: recognition.source!.toFilePath(),
audioStream: recognition.command.audioStream,
sourceStartMs: recognition.sourceStartMs,
taskId: job.translation!.id,
clipId: clipId,
expectedVersion: expectedVersion,
),
)
: await session.executeCommand(
job.sequence,
ApplyTranscription(
taskId: recognition.id,
clipId: clipId,
expectedVersion: expectedVersion,
),
);
final ids = (outcome.data['captionIds'] as List).cast<String>();
final view = session.view(job.sequence);
final handle = ids.isEmpty
? null
: view.version.kernelVersion.query().elementById(
ElementId(ids.first),
);
final component = handle == null
? null
: session.captionComponentFor(job.sequence, handle);
if (component != null) view.setSelection([component]);
return outcome.data['cueCount'] as int;
},
);
Future<void> cancel(SubtitleBackgroundTask job) =>
_run(SubtitleActionKind.cancel, () async {
await session.subtitleWorkflows.cancel(job);
return null;
});
Future<void> retry(SubtitleBackgroundTask job) =>
_run(SubtitleActionKind.retry, () async {
await session.subtitleWorkflows.retry(job);
return null;
});
Future<void> _run(
SubtitleActionKind kind,
Future<int?> Function() action,
) async {
if (state.isLoading) return;
final lease = ref.keepAlive();
final release = session.retainViews();
state = const AsyncLoading();
try {
final count = await action();
if (ref.mounted) {
state = AsyncData(SubtitleActionFeedback(kind: kind, cueCount: count));
}
} catch (error, stack) {
if (ref.mounted) {
state = AsyncError(SubtitleActionException(kind, error), stack);
}
} finally {
release();
lease.close();
}
}
}
@@ -0,0 +1,645 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'subtitle_task_actions.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$SubtitleActionFeedback {
SubtitleActionKind get kind;
int? get cueCount;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SubtitleActionFeedbackCopyWith<SubtitleActionFeedback> get copyWith =>
_$SubtitleActionFeedbackCopyWithImpl<SubtitleActionFeedback>(
this as SubtitleActionFeedback,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as SubtitleActionFeedback;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is SubtitleActionFeedback &&
(identical(other.kind, _this.kind) || other.kind == _this.kind) &&
(identical(other.cueCount, _this.cueCount) ||
other.cueCount == _this.cueCount));
}
@override
int get hashCode {
final _this = this as SubtitleActionFeedback;
return Object.hash(runtimeType, _this.kind, _this.cueCount);
}
@override
String toString() {
final _this = this as SubtitleActionFeedback;
return 'SubtitleActionFeedback(kind: ${_this.kind}, cueCount: ${_this.cueCount})';
}
}
/// @nodoc
abstract mixin class $SubtitleActionFeedbackCopyWith<$Res> {
factory $SubtitleActionFeedbackCopyWith(
SubtitleActionFeedback value,
$Res Function(SubtitleActionFeedback) _then,
) = _$SubtitleActionFeedbackCopyWithImpl;
@useResult
$Res call({SubtitleActionKind kind, int? cueCount});
}
/// @nodoc
class _$SubtitleActionFeedbackCopyWithImpl<$Res>
implements $SubtitleActionFeedbackCopyWith<$Res> {
_$SubtitleActionFeedbackCopyWithImpl(this._self, this._then);
final SubtitleActionFeedback _self;
final $Res Function(SubtitleActionFeedback) _then;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? kind = null, Object? cueCount = freezed}) {
return _then(
SubtitleActionFeedback(
kind: null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
cueCount: freezed == cueCount
? _self.cueCount
: cueCount // ignore: cast_nullable_to_non_nullable
as int?,
),
);
}
}
/// Adds pattern-matching-related methods to [SubtitleActionFeedback].
extension SubtitleActionFeedbackPatterns on SubtitleActionFeedback {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_SubtitleActionFeedback value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_SubtitleActionFeedback value) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_SubtitleActionFeedback value)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, int? cueCount)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that.kind, _that.cueCount);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, int? cueCount) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback():
return $default(_that.kind, _that.cueCount);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(SubtitleActionKind kind, int? cueCount)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionFeedback() when $default != null:
return $default(_that.kind, _that.cueCount);
case _:
return null;
}
}
}
/// @nodoc
class _SubtitleActionFeedback implements SubtitleActionFeedback {
const _SubtitleActionFeedback({required this.kind, this.cueCount});
@override
final SubtitleActionKind kind;
@override
final int? cueCount;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SubtitleActionFeedbackCopyWith<_SubtitleActionFeedback> get copyWith =>
__$SubtitleActionFeedbackCopyWithImpl<_SubtitleActionFeedback>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _SubtitleActionFeedback &&
(identical(other.kind, kind) || other.kind == kind) &&
(identical(other.cueCount, cueCount) ||
other.cueCount == cueCount));
}
@override
int get hashCode {
return Object.hash(runtimeType, kind, cueCount);
}
@override
String toString() {
return 'SubtitleActionFeedback(kind: $kind, cueCount: $cueCount)';
}
}
/// @nodoc
abstract mixin class _$SubtitleActionFeedbackCopyWith<$Res>
implements $SubtitleActionFeedbackCopyWith<$Res> {
factory _$SubtitleActionFeedbackCopyWith(
_SubtitleActionFeedback value,
$Res Function(_SubtitleActionFeedback) _then,
) = __$SubtitleActionFeedbackCopyWithImpl;
@override
@useResult
$Res call({SubtitleActionKind kind, int? cueCount});
}
/// @nodoc
class __$SubtitleActionFeedbackCopyWithImpl<$Res>
implements _$SubtitleActionFeedbackCopyWith<$Res> {
__$SubtitleActionFeedbackCopyWithImpl(this._self, this._then);
final _SubtitleActionFeedback _self;
final $Res Function(_SubtitleActionFeedback) _then;
/// Create a copy of SubtitleActionFeedback
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? kind = null, Object? cueCount = freezed}) {
return _then(
_SubtitleActionFeedback(
kind: null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
cueCount: freezed == cueCount
? _self.cueCount
: cueCount // ignore: cast_nullable_to_non_nullable
as int?,
),
);
}
}
/// @nodoc
mixin _$SubtitleActionException {
SubtitleActionKind get kind;
Object get cause;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$SubtitleActionExceptionCopyWith<SubtitleActionException> get copyWith =>
_$SubtitleActionExceptionCopyWithImpl<SubtitleActionException>(
this as SubtitleActionException,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as SubtitleActionException;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is SubtitleActionException &&
(identical(other.kind, _this.kind) || other.kind == _this.kind) &&
const DeepCollectionEquality().equals(other.cause, _this.cause));
}
@override
int get hashCode {
final _this = this as SubtitleActionException;
return Object.hash(
runtimeType,
_this.kind,
const DeepCollectionEquality().hash(_this.cause),
);
}
@override
String toString() {
final _this = this as SubtitleActionException;
return 'SubtitleActionException(kind: ${_this.kind}, cause: ${_this.cause})';
}
}
/// @nodoc
abstract mixin class $SubtitleActionExceptionCopyWith<$Res> {
factory $SubtitleActionExceptionCopyWith(
SubtitleActionException value,
$Res Function(SubtitleActionException) _then,
) = _$SubtitleActionExceptionCopyWithImpl;
@useResult
$Res call({SubtitleActionKind kind, Object cause});
}
/// @nodoc
class _$SubtitleActionExceptionCopyWithImpl<$Res>
implements $SubtitleActionExceptionCopyWith<$Res> {
_$SubtitleActionExceptionCopyWithImpl(this._self, this._then);
final SubtitleActionException _self;
final $Res Function(SubtitleActionException) _then;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? kind = null, Object? cause = null}) {
return _then(
SubtitleActionException(
null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
null == cause ? _self.cause : cause,
),
);
}
}
/// Adds pattern-matching-related methods to [SubtitleActionException].
extension SubtitleActionExceptionPatterns on SubtitleActionException {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_SubtitleActionException value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_SubtitleActionException value) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_SubtitleActionException value)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, Object cause)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that.kind, _that.cause);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(SubtitleActionKind kind, Object cause) $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException():
return $default(_that.kind, _that.cause);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(SubtitleActionKind kind, Object cause)? $default,
) {
final _that = this;
switch (_that) {
case _SubtitleActionException() when $default != null:
return $default(_that.kind, _that.cause);
case _:
return null;
}
}
}
/// @nodoc
class _SubtitleActionException implements SubtitleActionException {
const _SubtitleActionException(this.kind, this.cause);
@override
final SubtitleActionKind kind;
@override
final Object cause;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$SubtitleActionExceptionCopyWith<_SubtitleActionException> get copyWith =>
__$SubtitleActionExceptionCopyWithImpl<_SubtitleActionException>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _SubtitleActionException &&
(identical(other.kind, kind) || other.kind == kind) &&
const DeepCollectionEquality().equals(other.cause, cause));
}
@override
int get hashCode {
return Object.hash(
runtimeType,
kind,
const DeepCollectionEquality().hash(cause),
);
}
@override
String toString() {
return 'SubtitleActionException(kind: $kind, cause: $cause)';
}
}
/// @nodoc
abstract mixin class _$SubtitleActionExceptionCopyWith<$Res>
implements $SubtitleActionExceptionCopyWith<$Res> {
factory _$SubtitleActionExceptionCopyWith(
_SubtitleActionException value,
$Res Function(_SubtitleActionException) _then,
) = __$SubtitleActionExceptionCopyWithImpl;
@override
@useResult
$Res call({SubtitleActionKind kind, Object cause});
}
/// @nodoc
class __$SubtitleActionExceptionCopyWithImpl<$Res>
implements _$SubtitleActionExceptionCopyWith<$Res> {
__$SubtitleActionExceptionCopyWithImpl(this._self, this._then);
final _SubtitleActionException _self;
final $Res Function(_SubtitleActionException) _then;
/// Create a copy of SubtitleActionException
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? kind = null, Object? cause = null}) {
return _then(
_SubtitleActionException(
null == kind
? _self.kind
: kind // ignore: cast_nullable_to_non_nullable
as SubtitleActionKind,
null == cause ? _self.cause : cause,
),
);
}
}
@@ -0,0 +1,138 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'subtitle_task_actions.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// One operation state is shared by the compact card and its details dialog.
@ProviderFor(SubtitleTaskActions)
final subtitleTaskActionsProvider = SubtitleTaskActionsFamily._();
/// One operation state is shared by the compact card and its details dialog.
final class SubtitleTaskActionsProvider
extends
$NotifierProvider<
SubtitleTaskActions,
AsyncValue<SubtitleActionFeedback?>
> {
/// One operation state is shared by the compact card and its details dialog.
SubtitleTaskActionsProvider._({
required SubtitleTaskActionsFamily super.from,
required (EditorTimelineSession, String) super.argument,
}) : super(
retry: null,
name: r'subtitleTaskActionsProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$subtitleTaskActionsHash();
@override
String toString() {
return r'subtitleTaskActionsProvider'
''
'$argument';
}
@$internal
@override
SubtitleTaskActions create() => SubtitleTaskActions();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<SubtitleActionFeedback?> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<SubtitleActionFeedback?>>(
value,
),
);
}
@override
bool operator ==(Object other) {
return other is SubtitleTaskActionsProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$subtitleTaskActionsHash() =>
r'6308d7270d9a363b70bb03ae8dbbbbc83d2a71b7';
/// One operation state is shared by the compact card and its details dialog.
final class SubtitleTaskActionsFamily extends $Family
with
$ClassFamilyOverride<
SubtitleTaskActions,
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>,
(EditorTimelineSession, String)
> {
SubtitleTaskActionsFamily._()
: super(
retry: null,
name: r'subtitleTaskActionsProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
/// One operation state is shared by the compact card and its details dialog.
SubtitleTaskActionsProvider call(
EditorTimelineSession session,
String jobId,
) => SubtitleTaskActionsProvider._(argument: (session, jobId), from: this);
@override
String toString() => r'subtitleTaskActionsProvider';
}
/// One operation state is shared by the compact card and its details dialog.
abstract class _$SubtitleTaskActions
extends $Notifier<AsyncValue<SubtitleActionFeedback?>> {
late final _$args = ref.$arg as (EditorTimelineSession, String);
EditorTimelineSession get session => _$args.$1;
String get jobId => _$args.$2;
AsyncValue<SubtitleActionFeedback?> build(
EditorTimelineSession session,
String jobId,
);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref =
this.ref
as $Ref<
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>
>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<
AsyncValue<SubtitleActionFeedback?>,
AsyncValue<SubtitleActionFeedback?>
>,
AsyncValue<SubtitleActionFeedback?>,
Object?,
Object?
>;
return element.handleCreate(ref, () => build(_$args.$1, _$args.$2));
}
}
@@ -0,0 +1,353 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/runtime/processing_contracts.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../integrations/runtime/processing_resource_repository.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/confirm_resource_download_cancel.dart';
import '../../shared/widgets/processing_resource_download_dialog.dart';
import '../../workspace/timeline_session.dart';
import 'processing_targets.dart';
import 'subtitle_download.dart';
export 'processing_targets.dart';
class TranscriptionDialog extends ConsumerStatefulWidget {
const TranscriptionDialog({
super.key,
required this.session,
this.asset,
this.target,
}) : assert(asset == null || target == null);
const TranscriptionDialog.forCurrentTask({
super.key,
required this.session,
this.asset,
this.target,
}) : assert(asset == null || target == null);
final EditorTimelineSession session;
final AssetDocument? asset;
final TranscriptionClipTarget? target;
@override
ConsumerState<TranscriptionDialog> createState() =>
_TranscriptionDialogState();
}
class _TranscriptionDialogState extends ConsumerState<TranscriptionDialog> {
String _translationSource = 'auto';
String _translationTarget = 'none';
bool _closing = false;
late final VoidCallback _release;
SubtitleStartProvider get _startProvider =>
subtitleStartProvider(widget.session);
SubtitleDownloadState get _download {
final global = ref.read(subtitleDownloadProvider);
final local = ref.read(_startProvider);
if (identical(global.request?.session, widget.session) && global.running) {
return global;
}
return local is SubtitleIdle ? global : local;
}
bool get _ownsDownload =>
identical(_download.request?.session, widget.session);
bool get _installingResource =>
_ownsDownload && _download is SubtitleDownloading;
bool get _picking => _ownsDownload && _download is SubtitleStarting;
bool get _resourcePaused => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final paused) => paused,
_ => false,
}
: false;
double? get _resourceProgress => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final progress) => progress,
_ => null,
}
: null;
ProcessingCapability get _resourceStage => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final stage) => stage,
_ => ProcessingCapability.transcription,
}
: ProcessingCapability.transcription;
ProcessingResourceRepository? get _resourceRepository => _ownsDownload
? switch (_download) {
SubtitleDownloading(:final repository) => repository,
_ => null,
}
: null;
TranscriptionClipTarget? get _target =>
_installingResource ? _download.request?.target : widget.target;
AssetDocument? get _asset =>
_installingResource ? _download.request?.asset : widget.asset;
String? get _mediaId => _target?.mediaId ?? _asset?.id;
String? get _error => !_ownsDownload
? null
: switch (_download) {
SubtitleFailed(:final failure) => switch (failure) {
SubtitleStartFailure.start => context.l10n.startTranscriptionFailed,
SubtitleStartFailure.download =>
context.l10n.processingResourceDownloadFailed,
SubtitleStartFailure.engine =>
context.l10n.subtitleEngineUnavailable,
},
_ => null,
};
@override
void initState() {
super.initState();
_release = widget.session.retainViews();
if (_ownsDownload && _download.running) {
_translationSource = _download.request!.language;
_translationTarget = _download.request!.targetLanguage;
}
}
@override
void dispose() {
_release();
super.dispose();
}
void _dismissDialog() {
if (!mounted) return;
final route = ModalRoute.of(context);
if (route == null) return;
final navigator = Navigator.of(context);
if (route.isCurrent) {
navigator.pop();
} else {
navigator.removeRoute(route);
}
}
SubtitleRequest _request() => SubtitleRequest(
session: widget.session,
sequence: _target?.sequence ?? widget.session.activeSequenceId,
target: _target,
asset: _asset,
language: _translationSource,
targetLanguage: _translationTarget,
);
Future<void> _start() => ref.read(_startProvider.notifier).start(_request());
Future<void> _downloadResourceAndStart() {
ref.read(_startProvider.notifier).reset();
return ref
.read(subtitleDownloadProvider.notifier)
.start(_request(), download: true);
}
void _toggleResourceDownload() =>
ref.read(subtitleDownloadProvider.notifier).togglePause();
void _cancelResourceDownload() =>
ref.read(subtitleDownloadProvider.notifier).cancel();
String _translationLanguageLabel(String code) =>
context.l10n.subtitleLanguageName(code);
Widget _translationLanguageMenu({
required String label,
required String value,
required String other,
required ValueChanged<String> onChanged,
bool source = false,
bool enabled = true,
}) => AppField(
label: label,
child: AppSelect<String>(
emptyLabel: context.l10n.noMatchingOptions,
label: label,
value: value,
searchable: true,
searchHint: context.l10n.searchOptions(label),
onChanged: enabled ? onChanged : null,
options: [
if (source) ...[
AppSelectOption('auto', context.l10n.autoDetect),
] else
AppSelectOption('none', context.l10n.noTranslation),
for (final code in [
'zh',
'en',
'ja',
'ko',
if (source) 'yue',
...m2m100LanguageNames.keys.where(
(code) => !const {'zh', 'en', 'ja', 'ko'}.contains(code),
),
])
AppSelectOption(
code,
_translationLanguageLabel(code),
enabled: code != other,
searchTerms: [
code,
?subtitleNativeLanguageNames[code],
?m2m100LanguageNames[code],
],
),
],
),
);
Widget _buildModelDownloadDialog() {
final packages =
_resourceRepository?.catalog ?? defaultProcessingResourceCatalog;
final service = widget.session.transcriptions;
final downloadBytes = packages
.where(
(package) =>
ProcessingResourceRepository.subtitleCapabilities.contains(
package.capability,
) &&
!(package.capability == ProcessingCapability.transcription &&
service?.recognitionAvailable == true) &&
!(package.capability == ProcessingCapability.translation &&
service?.translationAvailable == true),
)
.fold<int>(0, (total, package) => total + package.bytes);
final totalBytes = packages
.where(
(package) => ProcessingResourceRepository.subtitleCapabilities
.contains(package.capability),
)
.fold<int>(0, (total, package) => total + package.bytes);
final progressTotal = _resourceRepository?.subtitleTotalBytes ?? totalBytes;
final downloadedBytes =
_resourceRepository?.subtitleDownloadedBytes ??
((_resourceProgress ?? 0) * progressTotal).round();
return ProcessingResourceDownloadDialog(
title: context.l10n.subtitleResourceDownloadTask,
description: context.l10n.subtitleResourcesRequired,
resourceName: _resourceStage == ProcessingCapability.transcription
? context.l10n.speechResourceStage
: context.l10n.translationResourceStage,
downloadSize: context.l10n.subtitleResourcesDownloadSize(
formatResourceBytes(downloadBytes),
),
downloading: _installingResource,
paused: _resourcePaused,
downloadedBytes: downloadedBytes,
totalBytes: progressTotal,
bytesPerSecond: _resourceRepository?.subtitleDownloadBytesPerSecond ?? 0,
error: _error,
downloadButtonKey: const Key('download-transcription-resource'),
pauseButtonKey: const Key('download-transcription-resource'),
backgroundButtonKey: const Key('background-transcription-resource'),
onCancel: () async {
if (_installingResource &&
!await confirmResourceDownloadCancellation(context)) {
return;
}
if (!mounted) return;
_cancelResourceDownload();
_dismissDialog();
},
onDownload: _downloadResourceAndStart,
onTogglePause: _toggleResourceDownload,
onBackground: _dismissDialog,
);
}
@override
Widget build(BuildContext context) {
ref.watch(subtitleDownloadProvider);
ref.watch(_startProvider);
void handleResult(SubtitleDownloadState next) {
if (_closing || !identical(next.request?.session, widget.session)) return;
if (next is SubtitleStarted || next is SubtitleCancelled) {
_closing = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
final messenger = ScaffoldMessenger.maybeOf(context);
final message = context.l10n.subtitleTaskStarted;
_dismissDialog();
if (next is SubtitleStarted) {
messenger?.showSnackBar(SnackBar(content: Text(message)));
}
});
}
}
ref.listen(subtitleDownloadProvider, (_, next) => handleResult(next));
ref.listen(_startProvider, (_, next) => handleResult(next));
return ListenableBuilder(
listenable: widget.session,
builder: (context, _) {
final service = widget.session.transcriptions;
if (service?.recognitionAvailable != true ||
service?.translationAvailable != true ||
_installingResource) {
return _buildModelDownloadDialog();
}
final busy =
(service?.tasks.any((task) => !task.terminal) ?? false) ||
(service?.translationTasks.any((task) => !task.terminal) ?? false);
return AppDialog(
title: _target == null
? context.l10n.transcribe
: context.l10n.generateCaptions,
withShadow: true,
width: 560,
actions: [
if (_mediaId != null && service != null)
FilledButton(
onPressed: busy || _picking || !widget.session.acceptsEdits
? null
: _start,
child: Text(context.l10n.generateCaptions),
),
],
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
_translationLanguageMenu(
label: context.l10n.sourceLanguage,
value: _translationSource,
other: _translationTarget,
source: true,
enabled: !busy && !_picking,
onChanged: (value) =>
setState(() => _translationSource = value),
),
const SizedBox(height: AppSpacing.compact),
_translationLanguageMenu(
label: context.l10n.translationLanguage,
value: _translationTarget,
other: _translationSource,
enabled:
service?.translationAvailable == true &&
!busy &&
!_picking,
onChanged: (value) =>
setState(() => _translationTarget = value),
),
if (service?.translationAvailable != true)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.small),
child: Text(context.l10n.translationNotConfigured),
),
if (_error != null)
Padding(
padding: const EdgeInsets.only(top: AppSpacing.compact),
child: Text(_error!),
),
],
),
),
);
},
);
}
}
@@ -0,0 +1,58 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/media_availability.dart';
class UnavailableMediaPlaceholder extends StatelessWidget {
const UnavailableMediaPlaceholder({
super.key,
required this.availability,
this.showLabel = true,
this.isPreview = false,
});
final MediaAvailability availability;
final bool showLabel;
final bool isPreview;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final label = availability == MediaAvailability.missing
? context.l10n.mediaMissing
: context.l10n.mediaUnavailable;
// Project covers share the canvas background, including missing media.
return ColoredBox(
color: isPreview
? Colors.transparent
: AppSurfaces.of(context).previewBackground,
child: Center(
child: FittedBox(
fit: BoxFit.scaleDown,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.broken_image_outlined,
size: isPreview ? 32 : 24,
color: theme.colorScheme.error,
),
if (showLabel) ...[
const SizedBox(height: AppSpacing.gap),
Text(
label,
style:
(isPreview
? theme.textTheme.bodyMedium
: theme.textTheme.bodySmall)
?.copyWith(color: theme.colorScheme.error),
),
],
],
),
),
),
);
}
}
+53
View File
@@ -0,0 +1,53 @@
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/material.dart';
import 'media_asset_cover.dart';
import 'package:cutdex_ui/theme.dart';
class VisualAssetTile extends StatelessWidget {
const VisualAssetTile({super.key, required this.asset, this.showName = true});
final AssetDocument asset;
final bool showName;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AspectRatio(
key: ValueKey('visual-cover-${asset.id}'),
aspectRatio: 16 / 9,
child: ColoredBox(
color: AppSurfaces.of(context).previewBackground,
child: MediaAssetCover(
asset: asset,
fallback: Center(
child: Icon(
asset.metadata['kind'] == 'image'
? Icons.image_outlined
: Icons.movie_outlined,
size: AppIconSize.emptyState,
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
),
),
if (showName) ...[
const SizedBox(height: AppSpacing.small),
Tooltip(
message: asset.name,
child: Text(
asset.name,
key: ValueKey('visual-name-${asset.id}'),
maxLines: 1,
overflow: TextOverflow.ellipsis,
style: Theme.of(context).textTheme.bodySmall,
),
),
],
],
);
}
}
@@ -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,
};
+732
View File
@@ -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(':');
}
}
+91
View File
@@ -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
+664
View File
@@ -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),
),
]),
],
);
},
);
}
}
+215
View File
@@ -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),
);
}
}
Loaded 100 of 718 files, more files were not shown because too many files have changed in this diff. Show more