Files
cutdex/lib/features/preview/preview_panel.dart
T
lingjhf 2e0033ce2d
Gitea CI / Build Android APK (pull_request) Canceled after 0s
Gitea CI / Build Windows x64 app (pull_request) Canceled after 0s
Gitea CI / Audit and package Windows x64 (pull_request) Canceled after 0s
Gitea CI / Assemble and validate CI artifacts (pull_request) Canceled after 0s
Gitea CI / Gitea CI passed (pull_request) Canceled after 0s
Gitea CI / Check code and tests (pull_request) Canceled after 6m29s
feat(workspace): refresh desktop editing experience and prepare 0.1.2
2026-10-09 01:56:01 +08:00

931 lines
38 KiB
Dart

import 'package:cutdex/shared/widgets/error_notification_host.dart';
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/icons.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../shared/widgets/listenable_selector.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 registry = ref.read(previewControllerRegistryProvider);
final release = registry.retain(ids);
ref.onDispose(release);
final result = registry.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,
this.pending = false,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context) => PreviewFullscreenHost(
child: _EditorPreviewContent(
projectId: projectId,
timelineId: timelineId,
pending: pending,
),
);
}
class _EditorPreviewContent extends ConsumerWidget {
const _EditorPreviewContent({
required this.projectId,
required this.timelineId,
this.pending = false,
});
final String projectId;
final String timelineId;
final bool pending;
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorPreviewProvider(projectId, timelineId);
final watched = pending
? const AsyncData<PreviewController?>(null)
: ref.watch(provider);
final prepared = ref.watch(
previewControllerRegistryProvider.select(
(registry) => registry.cached((projectId, timelineId)),
),
);
final cached = watched.isLoading && !watched.hasError ? prepared : null;
final state = cached == null
? watched
: AsyncData<PreviewController?>(cached);
final controller = state.asData?.value;
Widget panel() => WorkspacePanel(
headerHeight: 0,
showHeaderDivider: false,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: controller,
select: () => (
controller?.canvas,
controller?.session,
controller?.error,
(controller?.durationTick ?? 0) > 0,
),
builder: (context, _) {
final activeController = controller;
final defaultCanvas =
pending ||
(state.isLoading && !state.hasError && controller == null);
final showCanvas =
defaultCanvas ||
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) => ListenableSelector<Object>(
listenable: activeController.positionChanges,
select: () => (
activeController.positionTick,
activeController.selectedVisualIds.isNotEmpty,
activeController.maskEditingElement,
activeController.obscureEditingElement,
),
builder: (context, _) => Theme(
data: AppTheme.previewCanvasTheme,
child: NativePreviewOverlay(
session: activeController.session!,
enabled:
activeController.selectedVisualIds.isNotEmpty ||
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null,
child:
activeController.maskEditingElement != null ||
activeController.obscureEditingElement != null
? MaskInteractionOverlay(
controller: activeController,
canvasRect: rect,
obscure:
activeController.obscureEditingElement !=
null,
)
: PreviewInteractionOverlay(
onError: (error) =>
ErrorNotificationHost.maybeOf(
context,
)?.show(
ErrorNotification(
content: Text(
context.l10n.canvasTransformFailed,
),
details: error.toString(),
),
),
controller: activeController,
canvasRect: rect,
),
),
),
)
: null;
return showCanvas
? Padding(
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: 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) => defaultCanvas
? const ColoredBox(
key: Key('preview-default-frame'),
color: Colors.black,
)
: state.when(
skipLoadingOnReload: true,
loading: () => const ColoredBox(
key: Key('preview-default-frame'),
color: Colors.black,
),
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?
when preview.error == null &&
preview.durationTick > 0)
RuntimePreview(session: session),
ListenableSelector(
listenable: Listenable.merge([
preview,
preview.positionChanges,
]),
select: () => (
preview.error,
preview.unavailableAtPlayhead.join(
', ',
),
),
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: NativePreviewOcclusion(
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),
),
);
if (pending) return panel();
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 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 CallbackShortcuts(
bindings: {
const SingleActivator(LogicalKeyboardKey.space): source.togglePlayback,
},
child: Focus(
autofocus: true,
child: WorkspacePanel(
title: AppTheme.isDesktop(context) ? null : asset.name,
showHeaderDivider: false,
headerHeight:
AppTheme.isDesktop(context) ||
PreviewFullscreenScope.of(context)?.fullscreen == true
? 0
: AppControlSize.panelHeader,
child: PreviewFullscreenLayout(
canvas: ListenableSelector(
listenable: source,
select: () => (
source.session,
source.image,
source.error,
source.busy,
source.aspectRatio,
source.audioOnly,
),
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 Padding(
padding:
PreviewFullscreenScope.of(context)?.fullscreen == true
? EdgeInsets.zero
: AppTheme.isDesktop(context)
? const EdgeInsets.all(AppDesktopMetrics.panelPadding)
: 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: [
if (!source.audioOnly)
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) {
if (PreviewFullscreenScope.of(context)?.fullscreen == true) {
return ListenableSelector(
listenable: _clock,
select: () => (
source?.positionTick ?? controller?.positionTick ?? 0,
source?.durationTick ?? controller?.durationTick ?? 0,
source?.frameDuration ?? controller?.frameDuration,
source?.playing ?? controller?.playing ?? false,
source?.canPlay ?? controller?.canPlay ?? false,
),
builder: (context, _) => _build(context),
);
}
return _build(context);
}
Listenable? get _clock =>
source ??
(controller == null
? null
: Listenable.merge([controller!, controller!.positionChanges]));
RationalTime get _frameDuration =>
source?.frameDuration ??
controller?.frameDuration ??
TimelineFormat.fps30.frameDuration;
Future<void> _seek(BuildContext context, int requested) async {
final preview = controller;
final duration = source?.durationTick ?? preview?.durationTick ?? 0;
final frameTick = TimelineClock.standard.toTicks(_frameDuration);
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) {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
content: Text(previewErrorMessage(error, context.l10n)),
),
);
}
}
}
Widget _frameButton(
BuildContext context,
int direction,
) => ListenableSelector(
listenable: _clock,
select: () => (
source?.canPlay ?? controller?.canPlay ?? false,
source?.durationTick ?? controller?.durationTick ?? 0,
),
builder: (context, state) => IconButton(
key: Key(direction < 0 ? 'preview-previous-frame' : 'preview-next-frame'),
tooltip: direction < 0
? context.l10n.previewPreviousFrame
: context.l10n.previewNextFrame,
onPressed: !state.$1 || state.$2 <= 0
? null
: () {
final position =
source?.positionTick ?? controller?.positionTick ?? 0;
unawaited(
_seek(
context,
position +
direction *
TimelineClock.standard.toTicks(_frameDuration),
),
);
},
icon: Icon(direction < 0 ? AppIcons.previousFrame : AppIcons.nextFrame),
),
);
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) => _seek(context, requested);
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: AppTheme.isDesktop(context)
? AppDesktopMetrics.playbackBar
: AppControlSize.panelHeader,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.compact),
child: LayoutBuilder(
builder: (context, constraints) {
final controls = Row(
children: [
Expanded(
child: ListenableSelector(
key: const Key('preview-time'),
listenable: _clock,
select: () => (
source?.positionTick ?? preview?.positionTick ?? 0,
source?.durationTick ?? preview?.durationTick ?? 0,
_frameDuration,
),
builder: (context, _) => 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()],
),
),
),
),
if (AppTheme.isDesktop(context)) _frameButton(context, -1),
ListenableSelector(
listenable: source ?? preview,
select: () => (
source?.playing ?? preview?.playing ?? false,
source?.canPlay ?? preview?.canPlay ?? false,
),
builder: (context, value) {
final playing = value.$1;
return 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 ? AppIcons.pause : AppIcons.play),
);
},
),
if (AppTheme.isDesktop(context)) _frameButton(context, 1),
Expanded(
child: ListenableSelector(
listenable: source ?? preview,
select: () => (
preview?.canvas,
preview?.error,
preview?.hasUnavailableMedia,
preview?.busy,
preview?.session,
source?.session,
source?.image,
),
builder: (context, _) => 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(AppIcons.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
? AppIcons.exitFullscreen
: AppIcons.fullscreen,
),
),
],
),
),
),
),
],
);
if (AppTheme.isDesktop(context) && constraints.maxWidth < 240) {
return SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: SizedBox(width: 240, child: controls),
);
}
return controls;
},
),
),
);
}
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(':');
}
}