Files
cutdex/lib/features/timeline/timeline_panel.dart
T
lingjhf 27e77fff39 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.
2026-10-05 23:36:23 +08:00

1073 lines
37 KiB
Dart

import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/projects.dart';
import '../../integrations/runtime/timeline_thumbnails.dart';
import '../../integrations/runtime/timeline_waveforms.dart';
import 'package:flutter/material.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../media/transcription_dialog.dart';
import '../media/background_removal_dialog.dart';
import '../projects/widgets/name_dialog.dart';
import '../../workspace/timeline_session.dart';
import '../../workspace/preview_target.dart';
import 'timeline_asset_drop_target.dart';
import 'timeline_speed_editor.dart';
class EditorTimelinePanel extends ConsumerWidget {
const EditorTimelinePanel({
super.key,
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context, WidgetRef ref) {
final provider = editorTimelineProvider(projectId, timelineId);
final timeline = ref.watch(provider);
final projectState = ref.watch(projectsProvider).asData?.value;
final timelines = projectState?.activeProject?.id == projectId
? projectState!.timelines
: const <TimelineSummary>[];
return Theme(
data: AppTheme.timelinePanelTheme(Theme.of(context)),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_TimelineTabsBar(
projectId: projectId,
timelineId: timelineId,
timelines: timelines,
creating: projectState?.creatingTimeline ?? false,
openingTimelineId: projectState?.openingTimelineId,
),
const Divider(height: 1),
Expanded(
child: timeline.when(
loading: () => const WorkspacePanel(
key: Key('timeline-pending'),
child: SizedBox.expand(),
),
error: (_, _) => WorkspacePanel(
child: Center(
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
context.l10n.openTimelineFailed,
textAlign: TextAlign.center,
),
TextButton(
onPressed: () => ref.invalidate(provider),
child: Text(context.l10n.retry),
),
],
),
),
),
),
data: (session) => Listener(
behavior: HitTestBehavior.translucent,
onPointerDown: (_) {
if (const bool.fromEnvironment('CUTDEX_PREVIEW_TRACE')) {
debugPrint(
'CUTDEX_PREVIEW '
'${DateTime.now().millisecondsSinceEpoch} '
'dart pointer-down',
);
}
ref
.read(
previewNavigationProvider(
projectId,
timelineId,
).notifier,
)
.showTimeline();
},
child: _TimelineEditor(session: session, projectId: projectId),
),
),
),
],
),
);
}
}
class _TimelineTabsBar extends ConsumerStatefulWidget {
const _TimelineTabsBar({
required this.projectId,
required this.timelineId,
required this.timelines,
required this.creating,
required this.openingTimelineId,
});
final String projectId;
final String timelineId;
final List<TimelineSummary> timelines;
final bool creating;
final String? openingTimelineId;
@override
ConsumerState<_TimelineTabsBar> createState() => _TimelineTabsBarState();
}
class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> {
static const _barHeight = 26.0;
static const _menuWidth = 220.0;
final _scrollController = ScrollController();
final _selectedMenuItemKey = GlobalKey();
final _selectedTabKey = GlobalKey();
bool get _operationsBusy =>
widget.creating ||
widget.openingTimelineId != null ||
(ref.read(projectsProvider).value?.projectBusy ?? false);
Future<void> _openTimeline(TimelineSummary timeline) async {
if (_operationsBusy || timeline.id == widget.timelineId) return;
await ref
.read(projectsProvider.notifier)
.openTimeline(widget.projectId, timeline.id);
}
Future<void> _setTimelinePinned(TimelineSummary timeline) async {
if (_operationsBusy) return;
await ref
.read(projectsProvider.notifier)
.setTimelinePinned(timeline.id, !timeline.pinned);
}
@override
void initState() {
super.initState();
_showSelectedTab();
}
@override
void didUpdateWidget(covariant _TimelineTabsBar oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.timelineId != widget.timelineId) {
_showSelectedTab();
}
}
void _showSelectedTab() {
WidgetsBinding.instance.addPostFrameCallback((_) {
final selected = _selectedTabKey.currentContext;
if (selected != null) {
Scrollable.ensureVisible(
selected,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtEnd,
);
Scrollable.ensureVisible(
selected,
alignmentPolicy: ScrollPositionAlignmentPolicy.keepVisibleAtStart,
);
}
});
}
void _showSelectedMenuItem() {
WidgetsBinding.instance.addPostFrameCallback((_) {
final selected = _selectedMenuItemKey.currentContext;
if (selected != null) {
Scrollable.ensureVisible(selected, alignment: 0.5);
}
});
}
Future<void> _renameTimeline(TimelineSummary timeline) async {
if (_operationsBusy) return;
final project = ref.read(projectsProvider).value?.activeProject;
if (project?.id != widget.projectId) return;
final name = await askName(
context,
title: context.l10n.rename,
label: context.l10n.name,
initialValue: timeline.name,
submitLabel: context.l10n.rename,
);
if (name == null || !mounted || name == timeline.name) return;
await ref
.read(projectsProvider.notifier)
.renameTimeline(project!, timeline.id, name);
}
Future<void> _deleteTimeline(TimelineSummary timeline) async {
if (_operationsBusy || widget.timelines.length <= 1) return;
final confirmed = await showAppDialog<bool>(
context: context,
builder: (dialogContext) => AppDialog(
title: context.l10n.delete,
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogContext, false),
child: Text(context.l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.pop(dialogContext, true),
child: Text(context.l10n.delete),
),
],
child: Text(context.l10n.deleteTimelineConfirmation(timeline.name)),
),
);
if (confirmed == true && mounted) {
await ref.read(projectsProvider.notifier).deleteTimeline(timeline.id);
}
}
Future<void> _createTimeline() async {
if (_operationsBusy) return;
if (widget.timelines.length >= Projects.maxTimelineCount) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(
content: Text(
context.l10n.timelineLimitReached(Projects.maxTimelineCount),
),
),
);
return;
}
await ref
.read(projectsProvider.notifier)
.createTimeline(name: _nextName(context));
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
String _nextName(BuildContext context) {
final names = widget.timelines.map((timeline) => timeline.name).toSet();
for (var index = 1; ; index++) {
final candidate = context.l10n.defaultTimelineName(index);
if (!names.contains(candidate)) return candidate;
}
}
@override
Widget build(BuildContext context) {
return ColoredBox(
color: Theme.of(context).colorScheme.surface,
child: SizedBox(
key: const Key('timeline-tabs-bar'),
height: _barHeight,
child: Row(
children: [
SizedBox.square(
dimension: _barHeight,
child: IconButton(
key: const Key('timeline-add-button'),
tooltip: context.l10n.createTimelineHint,
onPressed: _createTimeline,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _barHeight,
height: _barHeight,
),
icon: const Icon(Icons.add, size: AppIconSize.small),
),
),
Expanded(
child: ScrollEdgeFade(
controller: _scrollController,
axis: Axis.horizontal,
child: Listener(
onPointerSignal: (event) {
if (event is! PointerScrollEvent ||
!_scrollController.hasClients) {
return;
}
final delta = event.scrollDelta.dy != 0
? event.scrollDelta.dy
: event.scrollDelta.dx;
if (delta == 0) return;
final position = _scrollController.position;
_scrollController.jumpTo(
(position.pixels + delta).clamp(
position.minScrollExtent,
position.maxScrollExtent,
),
);
},
child: SingleChildScrollView(
key: const Key('timeline-tabs-list'),
controller: _scrollController,
scrollDirection: Axis.horizontal,
child: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.tiny,
),
child: Row(
children: [
for (
var index = 0;
index < widget.timelines.length;
index++
) ...[
if (index > 0)
const SizedBox(width: AppSpacing.hairline),
_buildTab(context, widget.timelines[index]),
],
],
),
),
),
),
),
),
SizedBox.square(
dimension: _barHeight,
child: AppPopover(
width: _menuWidth,
maxHeight: 320,
alignment: AlignmentDirectional.bottomEnd,
child: SingleChildScrollView(
primary: false,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
for (final timeline in widget.timelines)
KeyedSubtree(
key: timeline.id == widget.timelineId
? _selectedMenuItemKey
: null,
child: AppMenuItem(
key: ValueKey('timeline-menu-${timeline.id}'),
label: timeline.name,
selected: timeline.id == widget.timelineId,
selectOption: true,
onPressed: () => _openTimeline(timeline),
),
),
],
),
),
builder: (context, toggle) => IconButton(
key: const Key('timeline-list-button'),
tooltip: context.l10n.timelines,
onPressed: () {
toggle();
_showSelectedMenuItem();
},
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: _barHeight,
height: _barHeight,
),
icon: const Icon(Icons.more_horiz, size: AppIconSize.small),
),
),
),
],
),
),
);
}
Widget _buildTab(BuildContext context, TimelineSummary timeline) {
final selected = timeline.id == widget.timelineId;
return KeyedSubtree(
key: selected ? _selectedTabKey : null,
child: AppContextMenu(
itemsBuilder: (context) => [
AppMenuItem(
key: ValueKey('timeline-pin-${timeline.id}'),
label: timeline.pinned
? context.l10n.unpinTimeline
: context.l10n.pinTimeline,
icon: Icons.push_pin_outlined,
onPressed: () => _setTimelinePinned(timeline),
),
AppMenuItem(
key: ValueKey('timeline-rename-${timeline.id}'),
label: context.l10n.rename,
icon: Icons.drive_file_rename_outline,
onPressed: () => _renameTimeline(timeline),
),
AppMenuItem(
key: ValueKey('timeline-delete-${timeline.id}'),
label: context.l10n.delete,
icon: Icons.delete_outline,
destructive: true,
onPressed: widget.timelines.length <= 1
? null
: () => _deleteTimeline(timeline),
),
],
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 3),
child: TextButton(
key: ValueKey('timeline-tab-${timeline.id}'),
onPressed: () => _openTimeline(timeline),
style: ButtonStyle(
minimumSize: const WidgetStatePropertyAll(Size(0, 20)),
maximumSize: const WidgetStatePropertyAll(
Size(double.infinity, 20),
),
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
textStyle: WidgetStatePropertyAll(
Theme.of(context).textTheme.labelLarge?.copyWith(
fontSize: 12,
height: 1.3,
fontWeight: FontWeight.w400,
),
),
padding: const WidgetStatePropertyAll(
EdgeInsets.symmetric(horizontal: AppSpacing.small),
),
foregroundColor: WidgetStatePropertyAll(
selected
? Theme.of(context).colorScheme.onSurface
: Theme.of(context).colorScheme.onSurfaceVariant,
),
backgroundColor: WidgetStatePropertyAll(
selected
? Theme.of(context).colorScheme.onSurface
.withValues(alpha: .05)
: Colors.transparent,
),
overlayColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.hovered) ||
states.contains(WidgetState.focused) ||
states.contains(WidgetState.pressed)) {
return Theme.of(context).colorScheme.onSurface
.withValues(alpha: .078);
}
return Colors.transparent;
}),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (timeline.pinned) ...[
const Icon(Icons.push_pin, size: 10),
const SizedBox(width: AppSpacing.tiny),
],
Text(
timeline.name,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
),
),
),
);
}
}
class _TimelineEditor extends StatefulWidget {
const _TimelineEditor({required this.session, required this.projectId});
final String projectId;
final EditorTimelineSession session;
@override
State<_TimelineEditor> createState() => _TimelineEditorState();
}
class _TimelineEditorState extends State<_TimelineEditor> {
EditorTimelineSession get session => widget.session;
String get projectId => widget.projectId;
late RuntimeTimelineThumbnails _thumbnails;
late RuntimeTimelineWaveforms _waveforms;
@override
void initState() {
super.initState();
_createMediaCaches();
}
@override
void didUpdateWidget(covariant _TimelineEditor oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.session, widget.session)) {
_thumbnails.dispose();
_waveforms.dispose();
_createMediaCaches();
}
}
void _createMediaCaches() {
_thumbnails = RuntimeTimelineThumbnails(
resolveTrackSelection: (ref) => session.mediaBinding(ref)?.videoSelection,
resolveMedia: (ref) {
final binding = session.mediaBinding(ref);
if (session.unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.videoTrackIndex == null ? null : binding!.media;
},
);
_waveforms = RuntimeTimelineWaveforms(
resolveTrackSelection: (ref) => session.mediaBinding(ref)?.audioSelection,
resolveGain: session.waveformGain,
gainChanges: session.audioGainPreview,
resolveMedia: (ref) {
final binding = session.mediaBinding(ref);
if (session.unavailableAssets.containsKey(binding?.media.id)) {
return null;
}
return binding?.audioTrackIndex == null ? null : binding!.media;
},
);
}
@override
void dispose() {
_thumbnails.dispose();
_waveforms.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: session,
builder: (context, _) => _build(context),
);
TranscriptionClipTarget? _captionTarget(
TimelineViewController controller,
SequenceId sequence,
) {
if (!session.acceptsEdits ||
controller.isDragging ||
controller.selectedIdentities.length != 1) {
return null;
}
final handle = switch (controller.selectedIdentities.single) {
ElementHandle value => value,
LayoutBodyId value => controller.elementForIdentity(value),
_ => null,
};
final query = controller.version.kernelVersion.query();
if (handle == null || query.ownerOf(handle) == null) return null;
final clip = query.element(handle);
final binding = clip.payloadRef == null
? null
: session.mediaBinding(clip.payloadRef!);
if (binding == null ||
binding.audioTrackIndex == null ||
session.unavailableAssets.containsKey(binding.media.id)) {
return null;
}
return TranscriptionClipTarget(
sequence: sequence,
clipId: clip.id.value,
mediaId: binding.media.id,
name: clip.name ?? context.l10n.clip,
audioStream: binding.audioTrackIndex!,
);
}
BackgroundRemovalClipTarget? _backgroundRemovalTarget(
TimelineViewController controller,
SequenceId sequence,
) {
if (!session.acceptsEdits ||
controller.isDragging ||
controller.selectedIdentities.length != 1) {
return null;
}
final handle = controller.elementForIdentity(
controller.selectedIdentities.single,
);
final query = controller.version.kernelVersion.query();
if (handle == null || query.ownerOf(handle) == null) return null;
final clip = query.element(handle);
final binding = clip.payloadRef == null
? null
: session.mediaBinding(clip.payloadRef!);
if (binding?.videoTrackIndex == null ||
session.unavailableAssets.containsKey(binding!.media.id)) {
return null;
}
return BackgroundRemovalClipTarget(
sequence: sequence,
clipId: clip.id.value,
mediaId: binding.media.id,
name: clip.name ?? context.l10n.clip,
);
}
List<ElementHandle> _selectedCaptionCues(TimelineViewController controller) {
final query = controller.version.kernelVersion.query();
final result = <ElementHandle>[];
for (final identity in controller.selectedIdentities) {
final handle = controller.elementForIdentity(identity);
if (handle == null || query.ownerOf(handle) == null) return [];
final ref = query.element(handle).payloadRef;
if (ref == null || session.payloadFor(ref)?.type != 'caption') {
return [];
}
result.add(handle);
}
return result;
}
bool _canSplitCaption(
TimelineViewController controller,
List<ElementHandle> cues,
) {
if (cues.length != 1 || controller.isDragging) return false;
final query = controller.version.kernelVersion.query();
final start = query.absoluteStart(cues.single);
return controller.playheadTick > start &&
controller.playheadTick < start + query.element(cues.single).duration;
}
void _splitCaption(
SequenceId sequence,
TimelineViewController controller,
ElementHandle cue,
) {
final query = controller.version.kernelVersion.query();
final offset = controller.playheadTick - query.absoluteStart(cue);
session.splitCaption(
sequence,
SplitCaption(
captionId: query.element(cue).id.value,
offset: CommandTime(offset, TimelineClock.ticksPerSecond),
expectedVersion: session.version,
),
);
}
void _runCaptionEdit(BuildContext context, void Function() edit) {
try {
edit();
} on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(
content: Text(
error.code == 'staleVersion'
? context.l10n.captionChanged
: context.l10n.editCaptionError(
context.l10n.errorMessage(error),
),
),
),
);
}
}
Widget _toolbarButton({
Key? key,
required String tooltip,
required VoidCallback? onPressed,
required IconData icon,
String? semanticLabel,
}) => IconButton(
key: key,
tooltip: tooltip,
onPressed: onPressed,
iconSize: AppIconSize.header,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(
width: AppControlSize.headerButton,
height: AppControlSize.headerButton,
),
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
icon: Icon(icon, semanticLabel: semanticLabel),
);
Widget _build(BuildContext context) {
final sequenceId = session.activeSequenceId;
if (sequenceId == null) {
return WorkspacePanel(
child: Center(child: Text(context.l10n.noTimelineSequence)),
);
}
final controller = session.view(sequenceId);
final captionCues = _selectedCaptionCues(controller);
final canSplitCaption = _canSplitCaption(controller, captionCues);
return WorkspacePanel(
headerHeight: 32,
headerPadding: EdgeInsets.zero,
controls: ListenableBuilder(
listenable: Listenable.merge([
controller.contentChanges,
controller.playheadChanges,
session,
]),
builder: (context, _) => SizedBox(
key: const Key('timeline-toolbar'),
height: 32,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: AppSpacing.gap),
child: LayoutBuilder(
builder: (context, constraints) => SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: IntrinsicWidth(
child: Row(
children: [
Row(
mainAxisSize: MainAxisSize.min,
spacing: AppSpacing.tiny,
children: [
_toolbarButton(
tooltip: context.l10n.undo,
onPressed: controller.canUndo
? controller.undo
: null,
icon: Icons.undo,
),
_toolbarButton(
tooltip: context.l10n.redo,
onPressed: controller.canRedo
? controller.redo
: null,
icon: Icons.redo,
),
_toolbarButton(
tooltip: context.l10n.splitAtPlayhead,
onPressed: canSplitCaption
? () => _runCaptionEdit(
context,
() => _splitCaption(
sequenceId,
controller,
captionCues.single,
),
)
: controller.canCutSelection
? controller.cutSelectionAtPlayhead
: null,
icon: Icons.content_cut,
),
_toolbarButton(
key: const ValueKey('timeline-trim-left'),
tooltip: context.l10n.trimLeftTooltip,
onPressed: controller.canCutSelection
? controller.trimLeftAtPlayhead
: null,
icon: Icons.align_horizontal_left,
semanticLabel: context.l10n.trimLeft,
),
_toolbarButton(
key: const ValueKey('timeline-trim-right'),
tooltip: context.l10n.trimRightTooltip,
onPressed: controller.canCutSelection
? controller.trimRightAtPlayhead
: null,
icon: Icons.align_horizontal_right,
semanticLabel: context.l10n.trimRight,
),
_toolbarButton(
key: const ValueKey('timeline-delete-selection'),
tooltip: context.l10n.deleteSelectedClips,
onPressed: () {
if (!controller.canDeleteSelection) return;
controller.deleteSelection();
},
icon: Icons.delete_outline,
),
],
),
const Spacer(),
if (controller.commandRejection != null)
Tooltip(
message: controller.commandRejection!,
child: const Icon(Icons.info_outline),
),
],
),
),
),
),
),
),
),
),
child: ListenableBuilder(
listenable: controller.contentChanges,
builder: (context, child) => AppContextMenu(
itemsBuilder: (_) {
final target = _captionTarget(controller, sequenceId);
final backgroundRemovalTarget = _backgroundRemovalTarget(
controller,
sequenceId,
);
final query = controller.version.kernelVersion.query();
final handle =
!controller.isDragging &&
controller.selectedIdentities.length == 1
? controller.elementForIdentity(
controller.selectedIdentities.single,
)
: null;
final clip = handle == null || query.ownerOf(handle) == null
? null
: query.element(handle);
final detachTarget = clip?.id;
final restoreAudio =
clip != null &&
clip.payloadRef != null &&
session.payloadFor(clip.payloadRef!)?.type == 'video' &&
(ClipAudioGain.isDetached(clip) ||
ClipAudioGain.fromRecord(clip).muted);
return [
AppMenuItem(
label: restoreAudio
? context.l10n.restoreAudio
: context.l10n.detachAudio,
icon: restoreAudio
? Icons.volume_up_outlined
: Icons.audio_file_outlined,
onPressed:
session.acceptsEdits &&
detachTarget != null &&
(restoreAudio ||
session.canDetachAudio(sequenceId, detachTarget))
? () {
try {
if (restoreAudio) {
session.commands.setAudio(
sequence: sequenceId,
clip: detachTarget,
muted: false,
);
} else {
session.detachAudio(sequenceId, detachTarget);
}
} catch (error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(context.l10n.errorMessage(error)),
),
);
}
}
: null,
),
AppMenuItem(
label: context.l10n.separateVocals,
icon: Icons.graphic_eq,
onPressed: null,
),
AppMenuItem(
label: context.l10n.removeBackground,
icon: Icons.person_remove_outlined,
onPressed: backgroundRemovalTarget == null
? null
: () => showAppDialog<void>(
context: context,
builder: (_) => BackgroundRemovalDialog(
session: session,
target: backgroundRemovalTarget,
),
),
),
AppMenuItem(
label: context.l10n.generateCaptions,
icon: Icons.subtitles_outlined,
onPressed: target == null
? null
: () => showAppDialog<void>(
context: context,
builder: (_) => TranscriptionDialog.forCurrentTask(
session: session,
target: target,
),
),
),
AppMenuItem(
label: context.l10n.deleteSelectedClips,
icon: Icons.delete_outline,
destructive: true,
onPressed: controller.canDeleteSelection
? controller.deleteSelection
: null,
),
];
},
child: child!,
),
child: Column(
children: [
Expanded(
child: Directionality(
textDirection: TextDirection.ltr,
child: TimelineViewport(
leadingPadding: AppSpacing.medium,
controller: controller,
child: TimelineAssetDropTarget(
projectId: projectId,
session: session,
sequenceId: sequenceId,
child: TimelineInteractionRegion(
controller: controller,
keyframes: true,
child: Stack(
fit: StackFit.expand,
children: [
TimelineView(
key: const Key('editor-timeline-surface'),
controller: controller,
classifyContent: session.classify,
contentStatus: session.mediaStatus,
contentTitle: session.contentTitle,
contentStatusChanges: session,
thumbnails: _thumbnails,
waveforms: _waveforms,
showKeyframes: true,
paintClipHeader: TimelineSpeedEditor.headerPainter(
context,
session: session,
sequence: sequenceId,
),
overlay: TimelineSpeedEditor(
session: session,
sequence: sequenceId,
controller: controller,
),
),
ListenableBuilder(
listenable: controller.contentChanges,
builder: (context, _) =>
controller.contentEndTick == 0 &&
!controller.isDragging
? TimelineEmptyDropZone(
primaryTop: controller.geometry.primaryTop
.toDouble(),
primaryHeight: controller
.geometry
.primaryHeight
.toDouble(),
verticalOffset:
controller.camera.verticalOffset,
)
: const SizedBox.shrink(),
),
],
),
),
),
),
),
),
],
),
),
);
}
}
class TimelineEmptyDropZone extends StatelessWidget {
const TimelineEmptyDropZone({
super.key,
required this.primaryTop,
required this.primaryHeight,
required this.verticalOffset,
});
final double primaryTop;
final double primaryHeight;
final double verticalOffset;
@override
Widget build(BuildContext context) => IgnorePointer(
child: LayoutBuilder(
builder: (context, constraints) {
final height = primaryHeight
.clamp(0.0, constraints.maxHeight)
.toDouble();
final top = (primaryTop - verticalOffset)
.clamp(0.0, constraints.maxHeight - height)
.toDouble();
return Stack(
children: [
Positioned(
top: top,
left: AppSpacing.medium,
right: AppSpacing.medium,
height: height,
child: CustomPaint(
key: const ValueKey('timeline-empty-drop-zone'),
painter: _DashedDropZonePainter(
color: AppTheme.sidebarDividerColor(context),
),
child: Center(
child: Text(
context.l10n.timelineDropToStart,
style: Theme.of(context).textTheme.labelLarge?.copyWith(
color: Theme.of(context).colorScheme.onSurface,
fontWeight: FontWeight.w600,
),
),
),
),
),
],
);
},
),
);
}
class _DashedDropZonePainter extends CustomPainter {
const _DashedDropZonePainter({required this.color});
final Color color;
static const _radius = Radius.circular(8);
static const _dash = 5.0;
static const _gap = 3.0;
@override
void paint(Canvas canvas, Size size) {
if (size.isEmpty) return;
final rect = RRect.fromRectAndRadius(
Rect.fromLTWH(1, 1, size.width - 2, size.height - 2),
_radius,
);
final path = Path()..addRRect(rect);
final paint = Paint()
..color = color
..style = PaintingStyle.stroke
..strokeWidth = 2;
for (final metric in path.computeMetrics()) {
var start = 0.0;
while (start < metric.length) {
canvas.drawPath(
metric.extractPath(start, (start + _dash).clamp(0, metric.length)),
paint,
);
start += _dash + _gap;
}
}
}
@override
bool shouldRepaint(_DashedDropZonePainter oldDelegate) =>
color != oldDelegate.color;
}