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,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';
}