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,110 @@
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../workspace/projects.dart';
import '../../workspace/timeline_session.dart';
import '../media/media_asset_drag.dart';
import 'timeline_external_drop_target.dart';
class TimelineAssetDropTarget extends ConsumerStatefulWidget {
const TimelineAssetDropTarget({
super.key,
required this.projectId,
required this.session,
required this.sequenceId,
required this.child,
});
final String projectId;
final EditorTimelineSession session;
final SequenceId sequenceId;
final Widget child;
@override
ConsumerState<TimelineAssetDropTarget> createState() =>
_TimelineAssetDropTargetState();
}
class _TimelineAssetDropTargetState
extends ConsumerState<TimelineAssetDropTarget> {
final _target = GlobalKey<TimelineExternalDropTargetState>();
final _incoming = ValueNotifier<TimelineIncomingAsset?>(null);
MediaAssetDrag? _drag;
void _updateIncoming(DragTargetDetails<MediaAssetDrag> details) {
if (!_accepts(details.data)) return;
final asset = ref
.read(projectsProvider)
.asData
?.value
.assets
.where((asset) => asset.id == details.data.assetId)
.firstOrNull;
if (asset == null) return;
if (_drag != details.data) {
_clearIncoming();
_drag = details.data;
}
details.data.feedbackVisible.value = false;
_incoming.value = (asset: asset, globalPosition: details.offset);
}
void _clearIncoming() {
_drag?.feedbackVisible.value = true;
_drag = null;
_incoming.value = null;
}
@override
void dispose() {
_clearIncoming();
_incoming.dispose();
super.dispose();
}
bool _inserting = false;
bool _accepts(MediaAssetDrag data) {
final state = ref.read(projectsProvider).asData?.value;
return !_inserting &&
data.projectId == widget.projectId &&
state?.activeProject?.id == widget.projectId &&
state?.timeline?.id == widget.session.document.id &&
state?.projectBusy == false;
}
Future<void> _drop(DragTargetDetails<MediaAssetDrag> details) async {
if (!_accepts(details.data)) return;
_updateIncoming(details);
_inserting = true;
try {
await _target.currentState?.drop();
} finally {
if (mounted) {
_clearIncoming();
_inserting = false;
}
}
}
@override
Widget build(BuildContext context) => DragTarget<MediaAssetDrag>(
hitTestBehavior: HitTestBehavior.opaque,
onWillAcceptWithDetails: (details) {
final accepts = _accepts(details.data);
if (accepts) _updateIncoming(details);
return accepts;
},
onMove: _updateIncoming,
onLeave: (_) => _clearIncoming(),
onAcceptWithDetails: _drop,
builder: (context, candidates, rejected) => TimelineExternalDropTarget(
key: _target,
projectId: widget.projectId,
session: widget.session,
sequenceId: widget.sequenceId,
incoming: _incoming,
child: widget.child,
),
);
}
@@ -0,0 +1,252 @@
import 'package:cutdex/errors/app_failure.dart';
import 'dart:async';
import 'package:cutdex_sdk/project.dart';
import 'package:flutter/foundation.dart';
import 'package:cutdex_sdk/runtime.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../workspace/external_media_import.dart';
import '../../workspace/media_import.dart';
import '../../workspace/prepared_media_metadata.dart';
import '../../workspace/projects.dart';
import '../../workspace/preview_target.dart';
import '../../workspace/timeline_session.dart';
part 'timeline_drop_preparation.g.dart';
part 'timeline_drop_preparation.freezed.dart';
@freezed
sealed class TimelineDropSource with _$TimelineDropSource {
const factory TimelineDropSource.file(ExternalMediaFile file) = DroppedFile;
const factory TimelineDropSource.asset(AssetDocument asset) = DroppedAsset;
}
@freezed
abstract class PreparedTimelineMedia with _$PreparedTimelineMedia {
const factory PreparedTimelineMedia({
required TimelineDropSource source,
required MediaReference media,
required PreparedMediaMetadata metadata,
}) = _PreparedTimelineMedia;
}
@freezed
abstract class TimelineDropState with _$TimelineDropState {
const factory TimelineDropState({
@Default(AsyncData<PreparedTimelineMedia?>(null))
AsyncValue<PreparedTimelineMedia?> preparation,
@Default(AsyncData<void>(null)) AsyncValue<void> commit,
}) = _TimelineDropState;
}
/// Probing and importing share the captured project, independent of pointer movement.
@riverpod
class TimelineDropPreparation extends _$TimelineDropPreparation {
int _revision = 0;
Future<void>? _pending;
final _operations = <int, Set<Future<void>>>{};
@override
TimelineDropState build(
String projectId,
EditorTimelineSession session,
SequenceId sequence,
) => const TimelineDropState();
void reset() {
final revision = ++_revision;
scheduleMicrotask(() {
if (ref.mounted && revision == _revision) {
state = const TimelineDropState();
}
});
}
bool get _active {
if (!ref.mounted) return false;
final workspace = ref.read(projectsProvider).value;
return session.acceptsEdits &&
workspace?.activeProject?.id == projectId &&
workspace?.timeline?.id == session.document.id;
}
Future<void> waitForPreparation() => _pending ?? Future<void>.value();
/// Capture this drag's work before reset changes the current revision.
/// Errors remain visible to callers, while native access can always be released.
Future<void> waitForCompletion() =>
Future.wait(_operations[_revision]?.toList() ?? <Future<void>>[])
.then((_) {});
void _track(Future<void> work, int revision) {
final operations = _operations.putIfAbsent(revision, () => {});
final settled = work.then<void>(
(_) {},
onError: (Object _, StackTrace _) {},
);
operations.add(settled);
unawaited(
settled.then((_) {
operations.remove(settled);
if (operations.isEmpty) _operations.remove(revision);
}),
);
}
Future<void> probe(TimelineDropSource source) {
final revision = ++_revision;
state = const TimelineDropState(preparation: AsyncLoading());
final lease = ref.keepAlive();
final work = _probe(source, revision);
_pending = work;
final completion = work.whenComplete(() {
if (identical(_pending, work)) _pending = null;
lease.close();
});
_track(completion, revision);
return completion;
}
Future<void> _probe(TimelineDropSource source, int revision) async {
final runtime = ref.read(runtimeConnectionProvider);
try {
final image =
source is DroppedAsset && source.asset.metadata['kind'] == 'image';
Future<PreparedTimelineMedia> load(MediaReference media) async {
final metadata = image
? PreparedMediaMetadata.image()
: PreparedMediaMetadata.fromInfo(await runtime.probe(media));
return PreparedTimelineMedia(
source: source,
media: media,
metadata: metadata,
);
}
final value = switch (source) {
DroppedAsset(:final asset) =>
await ref
.read(projectsProvider.notifier)
.withAssetMedia(projectId, asset, load),
DroppedFile(:final file) => await load(
MediaReference(
id: file.localPath!,
uri: Uri.file(
file.localPath!,
windows:
!kIsWeb && defaultTargetPlatform == TargetPlatform.windows,
),
),
),
};
if (ref.mounted && revision == _revision && _active) {
state = state.copyWith(preparation: AsyncData(value));
}
} catch (error, stack) {
if (ref.mounted && revision == _revision) {
state = state.copyWith(preparation: AsyncError(error, stack));
}
}
}
Future<void> commit(
Future<void> Function(AssetDocument asset, MediaReference media) insert, {
required bool Function() isCurrent,
void Function()? validatePlacement,
}) {
if (state.commit.isLoading) return Future<void>.value();
final revision = _revision;
final work = _commit(
insert,
revision: revision,
isCurrent: isCurrent,
validatePlacement: validatePlacement,
);
_track(work, revision);
return work;
}
Future<void> _commit(
Future<void> Function(AssetDocument asset, MediaReference media) insert, {
required int revision,
required bool Function() isCurrent,
void Function()? validatePlacement,
}) async {
final lease = ref.keepAlive();
final release = session.retainViews();
state = state.copyWith(commit: const AsyncLoading());
try {
await waitForPreparation();
if (!ref.mounted || revision != _revision || !_active || !isCurrent()) {
return;
}
final preparation = state.preparation;
if (preparation.hasError) {
Error.throwWithStackTrace(
preparation.error!,
preparation.stackTrace ?? StackTrace.current,
);
}
final prepared = preparation.value;
if (prepared == null) {
throw AppException(AppErrorCode.mediaReadFailed);
}
validatePlacement?.call();
final AssetDocument? asset;
switch (prepared.source) {
case DroppedAsset(asset: final asAsset):
asset = asAsset;
case DroppedFile(:final file):
final imported = await ref
.read(externalMediaImportProvider(projectId).notifier)
.importFiles([file]);
asset = imported?.selected.firstOrNull;
if (asset == null) {
throw AppException.fromFailure(
imported?.result?.failures.firstOrNull?.failure ??
const AppFailure(AppErrorCode.mediaImportFailed),
);
}
}
if (!ref.mounted || revision != _revision || !_active || !isCurrent()) {
return;
}
await ref.read(projectsProvider.notifier).withAssetMedia(
projectId,
asset,
(media) async {
if (!ref.mounted ||
revision != _revision ||
!_active ||
!isCurrent()) {
return;
}
await insert(asset!, media);
},
);
if (ref.mounted && revision == _revision && _active && isCurrent()) {
ref
.read(
previewNavigationProvider(
projectId,
session.document.id,
).notifier,
)
.showTimeline();
}
} catch (error, stack) {
if (ref.mounted && revision == _revision) {
state = state.copyWith(commit: AsyncError(error, stack));
}
rethrow;
} finally {
if (ref.mounted && revision == _revision && state.commit.isLoading) {
state = state.copyWith(commit: const AsyncData(null));
}
release();
lease.close();
}
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,133 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'timeline_drop_preparation.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
/// Probing and importing share the captured project, independent of pointer movement.
@ProviderFor(TimelineDropPreparation)
final timelineDropPreparationProvider = TimelineDropPreparationFamily._();
/// Probing and importing share the captured project, independent of pointer movement.
final class TimelineDropPreparationProvider
extends $NotifierProvider<TimelineDropPreparation, TimelineDropState> {
/// Probing and importing share the captured project, independent of pointer movement.
TimelineDropPreparationProvider._({
required TimelineDropPreparationFamily super.from,
required (String, EditorTimelineSession, SequenceId) super.argument,
}) : super(
retry: null,
name: r'timelineDropPreparationProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$timelineDropPreparationHash();
@override
String toString() {
return r'timelineDropPreparationProvider'
''
'$argument';
}
@$internal
@override
TimelineDropPreparation create() => TimelineDropPreparation();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(TimelineDropState value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<TimelineDropState>(value),
);
}
@override
bool operator ==(Object other) {
return other is TimelineDropPreparationProvider &&
other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$timelineDropPreparationHash() =>
r'4b762178d02d2e5b002ea252d8d516cfc59231a8';
/// Probing and importing share the captured project, independent of pointer movement.
final class TimelineDropPreparationFamily extends $Family
with
$ClassFamilyOverride<
TimelineDropPreparation,
TimelineDropState,
TimelineDropState,
TimelineDropState,
(String, EditorTimelineSession, SequenceId)
> {
TimelineDropPreparationFamily._()
: super(
retry: null,
name: r'timelineDropPreparationProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
/// Probing and importing share the captured project, independent of pointer movement.
TimelineDropPreparationProvider call(
String projectId,
EditorTimelineSession session,
SequenceId sequence,
) => TimelineDropPreparationProvider._(
argument: (projectId, session, sequence),
from: this,
);
@override
String toString() => r'timelineDropPreparationProvider';
}
/// Probing and importing share the captured project, independent of pointer movement.
abstract class _$TimelineDropPreparation extends $Notifier<TimelineDropState> {
late final _$args = ref.$arg as (String, EditorTimelineSession, SequenceId);
String get projectId => _$args.$1;
EditorTimelineSession get session => _$args.$2;
SequenceId get sequence => _$args.$3;
TimelineDropState build(
String projectId,
EditorTimelineSession session,
SequenceId sequence,
);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<TimelineDropState, TimelineDropState>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<TimelineDropState, TimelineDropState>,
TimelineDropState,
Object?,
Object?
>;
return element.handleCreate(
ref,
() => build(_$args.$1, _$args.$2, _$args.$3),
);
}
}
@@ -0,0 +1,406 @@
import 'package:cutdex/errors/app_failure.dart';
import 'dart:async';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/project.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../integrations/app_failure_adapter.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../workspace/projects.dart';
import '../../workspace/media_import.dart';
import '../../workspace/timeline_session.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_native/cutdex_native.dart';
import '../../integrations/platform/native_file_drop_policy.dart';
import 'timeline_drop_preparation.dart';
typedef TimelineIncomingAsset = ({AssetDocument asset, Offset globalPosition});
/// OS and project drags share a provisional clip without publishing changes.
class TimelineExternalDropTarget extends ConsumerStatefulWidget {
const TimelineExternalDropTarget({
super.key,
required this.projectId,
required this.session,
required this.sequenceId,
required this.child,
this.incoming,
});
final String projectId;
final EditorTimelineSession session;
final SequenceId sequenceId;
final Widget child;
final ValueListenable<TimelineIncomingAsset?>? incoming;
@override
ConsumerState<TimelineExternalDropTarget> createState() =>
TimelineExternalDropTargetState();
}
class TimelineExternalDropTargetState
extends ConsumerState<TimelineExternalDropTarget> {
static const dropPolicy = NativeFileDropPolicy.timeline;
late final connection = NativeFileDropConnection(
regionId: 'timeline',
hidesSourceImage: true,
onEvent: event,
);
TimelineDropPreparationProvider get _preparationProvider =>
timelineDropPreparationProvider(
widget.projectId,
widget.session,
widget.sequenceId,
);
late TimelineDropPreparation _preparer;
final surface = GlobalKey();
int? sessionId;
int generation = 0;
ExternalMediaFile? file;
AssetDocument? projectAsset;
bool get hasPreview => file != null || projectAsset != null;
EditorIncomingClip? incomingClip;
({int tick, int top, ConnectionSide? side})? lastPlacement;
void updateClip() {
final prepared = preparedMedia;
if (!hasPreview || prepared == null || error != null) return;
final box = surface.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !box.hasSize) return;
final viewport = TimelineViewportRect(
width: box.size.width,
height: box.size.height,
);
final y = view.camera.worldYForScreen(position.dy, viewport);
final geometry = view.geometry;
final side = y < geometry.primaryTop
? ConnectionSide.above
: y >= geometry.primaryTop + geometry.primaryHeight
? ConnectionSide.below
: null;
final raw = view.camera.tickAtScreenX(
position.dx,
viewport,
rounding: TimelineTickRounding.nearest,
);
final frame = view.format.frameGrid.quantumTicks;
final tick = raw <= 0 ? 0 : ((raw + frame ~/ 2) ~/ frame) * frame;
final top = (y - 12).round();
final placement = (tick: tick, top: top, side: side);
try {
incomingClip ??= widget.session.beginIncomingClip(
sequence: widget.sequenceId,
name: projectAsset?.name ?? file!.displayName,
duration: prepared.metadata.duration,
kind: prepared.metadata.kind.name,
hasAudio: prepared.metadata.hasAudio,
media: prepared.media,
);
if (lastPlacement != placement || incomingClip!.layout == null) {
incomingClip!.update(start: tick, side: side, top: top);
lastPlacement = placement;
}
placementError = null;
view.showIncomingClip(
incomingClip!.layout!,
element: incomingClip!.incoming.source,
start: tick,
top: top,
audioOnly: incomingClip!.kind == 'audio',
position: position,
viewport: viewport,
);
} catch (e) {
placementError = appFailureFromError(e);
view.clearIncomingClip();
}
}
PreparedTimelineMedia? get preparedMedia =>
ref.read(_preparationProvider).preparation.value;
Offset position = Offset.zero;
late TimelineViewController view;
bool get busy => ref.read(_preparationProvider).commit.isLoading;
AppFailure? get error => ref.read(_preparationProvider).preparation.hasError
? const AppFailure(AppErrorCode.mediaReadFailed)
: null;
AppFailure? placementError;
Rect? region;
bool get windows =>
!kIsWeb && defaultTargetPlatform == TargetPlatform.windows;
bool get native =>
!kIsWeb && (defaultTargetPlatform == TargetPlatform.macOS || windows);
bool get enabled {
final s = ref.read(projectsProvider).asData?.value;
return !busy &&
s?.projectBusy == false &&
s?.activeProject?.id == widget.projectId &&
s?.timeline?.id == widget.session.document.id;
}
bool get active => enabled && TickerMode.valuesOf(context).enabled;
TimelineCamera? lastCamera;
void viewChanged() {
if (!hasPreview || busy) return;
if (incomingClip?.layout != null && !view.isDragging) {
final g = generation;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && g == generation && !busy) setState(clear);
});
return;
}
final camera = view.camera;
if (identical(lastCamera, camera)) return;
lastCamera = camera;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted || !hasPreview || busy) return;
setState(updateClip);
});
}
@override
void didUpdateWidget(covariant TimelineExternalDropTarget oldWidget) {
super.didUpdateWidget(oldWidget);
final changedView =
oldWidget.session != widget.session ||
oldWidget.sequenceId != widget.sequenceId;
if (oldWidget.incoming != widget.incoming) {
oldWidget.incoming?.removeListener(incomingChanged);
widget.incoming?.addListener(incomingChanged);
}
if (changedView) view.removeListener(viewChanged);
if (changedView ||
oldWidget.projectId != widget.projectId ||
oldWidget.incoming != widget.incoming && projectAsset != null) {
clear();
}
if (changedView || oldWidget.projectId != widget.projectId) {
_preparer = ref.read(_preparationProvider.notifier);
}
if (changedView) {
view = widget.session.view(widget.sequenceId)..addListener(viewChanged);
}
}
@override
void initState() {
super.initState();
_preparer = ref.read(_preparationProvider.notifier);
if (native) {
connection.bind();
}
widget.incoming?.addListener(incomingChanged);
view = widget.session.view(widget.sequenceId)..addListener(viewChanged);
}
void incomingChanged() {
final incoming = widget.incoming?.value;
if (!mounted) return;
if (incoming == null) {
if (projectAsset != null && !busy) setState(clear);
return;
}
if (!active) return;
final box = surface.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !box.hasSize) return;
position = box.globalToLocal(incoming.globalPosition);
if (projectAsset?.id == incoming.asset.id) {
setState(updateClip);
return;
}
setState(() {
clear();
projectAsset = incoming.asset;
});
prepareMedia();
}
void enterExternal(int id, String path, Offset localPosition) {
if (!active || !dropPolicy.accepts([ExternalMediaFile(path: path)])) {
return;
}
setState(() {
clear();
sessionId = id;
file = ExternalMediaFile(path: path);
position = localPosition;
});
prepareMedia();
}
void moveExternal(int id, Offset localPosition) {
if (!active || sessionId != id) return;
setState(() {
position = localPosition;
updateClip();
});
}
void exitExternal(int id) {
if (sessionId == id && !busy) setState(clear);
}
Future<void> dropExternal(int id, Offset localPosition) async {
if (!active || sessionId != id) return;
position = localPosition;
await drop();
}
Future<void> sendRegion(Rect? bounds) =>
connection.setRegion(bounds, dropPolicy.configuration);
void report(Rect r) {
if (!mounted || !connection.isOwner) return;
final next = active ? r : null;
if (region == next) return;
region = next;
unawaited(sendRegion(next));
if (next == null && hasPreview && !busy) setState(clear);
}
Future<void> release(int id, Future<void> pending) async {
await pending;
await connection.release(id);
}
void clear() {
if (incomingClip != null) {
view.clearIncomingClip();
}
incomingClip?.cancel();
incomingClip = null;
lastPlacement = null;
lastCamera = null;
if (native && sessionId != null) {
unawaited(release(sessionId!, _preparer.waitForCompletion()));
}
generation++;
sessionId = null;
file = null;
projectAsset = null;
_preparer.reset();
placementError = null;
}
Future<void> event(NativeFileDropEvent event) async {
if (!mounted || !connection.isOwner) return;
final id = event.session;
final localPosition = event.position;
switch (event.phase) {
case NativeFileDropPhase.enter:
final files = [
for (final path in event.paths) ExternalMediaFile(path: path),
];
if (!active || !dropPolicy.accepts(files)) {
await release(id, Future<void>.value());
return;
}
enterExternal(id, event.paths.single, localPosition);
case NativeFileDropPhase.move:
moveExternal(id, localPosition);
case NativeFileDropPhase.exit:
exitExternal(id);
case NativeFileDropPhase.drop:
await dropExternal(id, localPosition);
}
}
void prepareMedia() {
final source = projectAsset == null
? TimelineDropSource.file(file!)
: TimelineDropSource.asset(projectAsset!);
unawaited(_preparer.probe(source));
}
Future<void> drop() async {
if (!active || !hasPreview) return;
final box = surface.currentContext?.findRenderObject() as RenderBox?;
if (box == null || !(Offset.zero & box.size).contains(position)) {
setState(clear);
return;
}
final g = generation;
try {
await _preparer.commit(
(asset, media) async {
incomingClip!.commit(assetId: asset.id, uri: media.uri);
},
isCurrent: () => mounted && g == generation,
validatePlacement: () {
updateClip();
if (incomingClip?.layout == null ||
error != null ||
placementError != null) {
throw AppException.fromFailure(
error ??
placementError ??
const AppFailure(AppErrorCode.mediaReadFailed),
);
}
},
);
} catch (e) {
if (mounted) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(e))));
}
} finally {
if (mounted && g == generation) {
setState(clear);
}
}
}
@override
void dispose() {
widget.incoming?.removeListener(incomingChanged);
view.removeListener(viewChanged);
clear();
// Flutter mounts the replacement before disposing the old target. Only
// the current owner may unregister the shared native channel and region.
if (native) connection.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
TickerMode.valuesOf(context);
ref.watch(projectsProvider);
ref.watch(_preparationProvider);
ref.listen(_preparationProvider.select((state) => state.preparation), (
_,
next,
) {
if (mounted && hasPreview && !next.isLoading) setState(updateClip);
});
final preview = Stack(
key: surface,
fit: StackFit.expand,
children: [
widget.child,
if (busy || hasPreview && incomingClip == null && error == null)
const DelayedLoadingIndicator(
child: Align(
alignment: Alignment.topCenter,
child: LinearProgressIndicator(),
),
),
],
);
return native
? NativeBoundsReporter(onBounds: report, child: preview)
: preview;
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,412 @@
import 'dart:math' as math;
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
import 'package:flutter/material.dart';
import '../../l10n/l10n.dart';
import '../../workspace/timeline_session.dart';
import 'timeline_speed_layout.dart';
class TimelineSpeedEditor extends StatelessWidget {
const TimelineSpeedEditor({
super.key,
required this.session,
required this.sequence,
required this.controller,
});
final EditorTimelineSession session;
final SequenceId sequence;
final TimelineViewController controller;
static TimelineClipHeaderPainter headerPainter(
BuildContext context, {
required EditorTimelineSession session,
required SequenceId sequence,
}) {
final ink = Theme.of(context).colorScheme.onSurface;
final surface = TimelineThemeData.of(context).backgroundColor;
final background = Color.alphaBlend(ink.withValues(alpha: .08), surface);
final style = Theme.of(context).textTheme.labelSmall
?.copyWith(color: ink, fontSize: 10, height: 1.2);
final scaler = MediaQuery.textScalerOf(context);
return (canvas, clipLayout, clip, pixelsPerTick) {
if (!session.isCustomSpeedEnabled(sequence, clip.id)) return;
final segments = session.clipSpeedSegments(clip);
if (segments == null) return;
final layout = TimelineSpeedLayout(
clip: clipLayout,
segments: segments,
pixelsPerTick: pixelsPerTick,
);
canvas.save();
canvas.translate(clipLayout.bounds.left, clipLayout.bounds.top);
for (final segment in layout.segments) {
final bar = segment.bar;
if (bar.isEmpty) continue;
final speed = segment.speed;
canvas.drawRRect(
RRect.fromRectAndRadius(bar, const Radius.circular(5)),
Paint()..color = background,
);
if (!segment.label.isEmpty) {
final label = TextPainter(
text: TextSpan(text: '${(speed * 100).round()}%', style: style),
textDirection: TextDirection.ltr,
textScaler: scaler,
maxLines: 1,
ellipsis: '…',
)..layout(maxWidth: segment.label.width);
label.paint(
canvas,
Offset(
segment.label.center.dx - label.width / 2,
segment.label.top,
),
);
label.dispose();
}
canvas.save();
canvas.clipRect(bar);
canvas.drawRRect(
RRect.fromRectAndRadius(
segment.handle,
const Radius.circular(TimelineSpeedSegmentLayout.handleRadius),
),
Paint()..color = ink.withValues(alpha: .498),
);
canvas.restore();
}
canvas.restore();
};
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: Listenable.merge([session, controller.contentChanges]),
builder: (context, _) => LayoutBuilder(
builder: (context, constraints) {
final frame = controller.project(
TimelineViewportRect(
width: constraints.maxWidth,
height: constraints.maxHeight,
),
);
final query = frame.version.kernelVersion.query();
final viewportBounds =
Offset.zero & Size(constraints.maxWidth, constraints.maxHeight);
final bars = <Widget>[];
void addHeader(
ElementHandle handle,
TimelineClipLayout clipLayout, {
bool ghost = false,
}) {
final record = query.element(handle);
if (!session.isCustomSpeedEnabled(sequence, record.id)) return;
final segments = session.clipSpeedSegments(record);
if (segments == null) return;
final layout = TimelineSpeedLayout(
clip: clipLayout,
segments: segments,
pixelsPerTick: controller.camera.pixelsPerTick,
);
final bounds = clipLayout.toViewport(layout.bounds);
if (bounds.isEmpty || !bounds.overlaps(viewportBounds)) {
return;
}
bars.add(
Positioned(
key: ValueKey((sequence, record.id)),
left: bounds.left,
top: bounds.top,
width: bounds.width,
height: bounds.height,
child: IgnorePointer(
ignoring: ghost,
child: _ClipSpeedEditor(
session: session,
sequence: sequence,
clip: record.id,
controller: controller,
layout: layout,
),
),
),
);
}
for (var index = 0; index < frame.length; index++) {
if (frame.kindAt(index) == TimelineViewportItemKind.transition) {
continue;
}
final identity = frame.identityAt(index);
final handle = controller.elementForIdentity(identity);
if (handle == null) continue;
final bodyId = identity is LayoutBodyId
? identity
: LayoutBodyId.element(handle);
// The resident item is a landing reservation while the moving clip
// is painted separately at its pointer-following ghost coordinates.
if (controller.dragGhostFor(bodyId) != null) continue;
addHeader(handle, controller.clipLayoutAt(frame, index));
}
for (final ghost in controller.dragGhosts) {
final body = ghost.body;
addHeader(
body.id.owner,
controller.clipLayout(
controller.dragGhostBounds(ghost, frame.viewport),
owner: body.id.owner,
),
ghost: true,
);
}
return Stack(clipBehavior: Clip.none, children: bars);
},
),
);
}
class _ClipSpeedEditor extends StatefulWidget {
const _ClipSpeedEditor({
required this.session,
required this.sequence,
required this.clip,
required this.controller,
required this.layout,
});
final EditorTimelineSession session;
final SequenceId sequence;
final ElementId clip;
final TimelineViewController controller;
final TimelineSpeedLayout layout;
@override
State<_ClipSpeedEditor> createState() => _ClipSpeedEditorState();
}
class _ClipSpeedEditorState extends State<_ClipSpeedEditor> {
int? _dragDuration;
ClipSpeedSegment? _dragSegment;
TimelineVersion? _dragVersion;
LayoutConnectionEditPreview? _preview;
(Object, StackTrace)? _previewFailure;
int? _dragIndex;
double _dragPixels = 0;
void _startDrag(int index, ClipSpeedSegment segment) {
_previewFailure = null;
_dragIndex = index;
_dragVersion = widget.controller.version.kernelVersion;
_dragDuration = segment.projectDuration;
_dragSegment = segment;
_dragPixels = 0;
widget.controller.clearRetainedTrimOutline();
}
void _updateDrag(DragUpdateDetails details) {
final index = _dragIndex;
final segment = _dragSegment;
if (index == null || segment == null) return;
if (!identical(_dragVersion, widget.controller.version.kernelVersion)) {
_cancelDrag();
return;
}
_dragPixels += details.delta.dx;
final minimum = math.max(1, (segment.sourceDuration / 100).ceil());
final maximum = math.max(minimum, (segment.sourceDuration / 0.1).floor());
final ticks = (_dragPixels / widget.controller.camera.pixelsPerTick)
.round();
final duration = (segment.projectDuration + ticks).clamp(minimum, maximum);
if (_dragDuration == duration) return;
_dragDuration = duration;
_updatePreview(segmentIndex: index, duration: duration);
}
void _updatePreview({required int segmentIndex, required int duration}) {
_preview?.cancel();
_preview = null;
_previewFailure = null;
try {
if (!widget.session.isCustomSpeedEnabled(widget.sequence, widget.clip)) {
widget.controller.clearLayoutPreview();
return;
}
final preview = widget.session.previewClipSpeedSegmentDuration(
widget.sequence,
widget.clip,
segmentIndex,
duration,
);
_preview = preview;
if (preview == null) {
widget.controller.clearLayoutPreview();
} else {
widget.controller.showLayoutPreview(preview.result.version);
}
} catch (error, stack) {
_previewFailure = (error, stack);
widget.controller.clearLayoutPreview();
_showError(error);
}
}
void _endDrag() {
final index = _dragIndex;
final version = _dragVersion;
final preview = _preview;
final failure = _previewFailure;
final duration = _dragDuration;
_previewFailure = null;
_preview = null;
_clearDrag();
if (index == null || version == null) {
preview?.cancel();
widget.controller.clearLayoutPreview();
return;
}
if (!identical(version, widget.controller.version.kernelVersion)) {
preview?.cancel();
widget.controller.clearLayoutPreview();
return;
}
try {
widget.session.runEdit(
'setSpeedSegment',
widget.sequence,
() {
if (preview == null) {
widget.controller.clearLayoutPreview();
if (failure != null) {
widget.session.reportEditFailure(failure.$1, failure.$2);
}
} else {
widget.session.commitClipSpeedPreview(widget.sequence, preview);
}
},
context: {
'clipIds': [widget.clip.value],
'segmentIndex': index,
'durationTick': duration,
'entryPoint': 'timelineSpeed',
'playheadTick': widget.controller.playheadTick,
},
);
} catch (error) {
preview?.cancel();
widget.controller.clearLayoutPreview();
_showError(error);
}
}
void _cancelDrag() {
_previewFailure = null;
_preview?.cancel();
_preview = null;
widget.controller.clearLayoutPreview();
_clearDrag();
}
void _showError(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error))));
}
void _clearDrag() {
_dragIndex = null;
_dragVersion = null;
_dragDuration = null;
_dragSegment = null;
_dragPixels = 0;
}
@override
void dispose() {
if (_preview != null) {
_preview!.cancel();
widget.controller.clearLayoutPreview();
}
super.dispose();
}
@override
Widget build(BuildContext context) {
final cells = widget.layout.segments;
return ClipRect(
child: Stack(
children: [
for (var index = 0; index < cells.length; index++)
if (!cells[index].cell.isEmpty)
Positioned.fromRect(
rect: cells[index].cell.shift(-widget.layout.bounds.topLeft),
child: _SpeedSegmentBar(
index: index,
layout: cells[index],
onDragStart: (_) => _startDrag(index, cells[index].segment),
onDragUpdate: _updateDrag,
onDragEnd: (_) => _endDrag(),
onDragCancel: _cancelDrag,
),
),
],
),
);
}
}
class _SpeedSegmentBar extends StatelessWidget {
const _SpeedSegmentBar({
required this.index,
required this.layout,
required this.onDragStart,
required this.onDragUpdate,
required this.onDragEnd,
required this.onDragCancel,
});
final int index;
final TimelineSpeedSegmentLayout layout;
final GestureDragStartCallback onDragStart;
final GestureDragUpdateCallback onDragUpdate;
final GestureDragEndCallback onDragEnd;
final VoidCallback onDragCancel;
@override
Widget build(BuildContext context) {
return SizedBox(
key: ValueKey('speed-segment-$index'),
child: Semantics(
label: '${(layout.speed * 100).round()}%',
child: Stack(
fit: StackFit.expand,
children: [
Positioned.fromRect(
rect: layout.handleHit.shift(-layout.cell.topLeft),
child: MouseRegion(
cursor: SystemMouseCursors.resizeLeftRight,
child: GestureDetector(
key: ValueKey('speed-segment-handle-$index'),
behavior: HitTestBehavior.opaque,
// Own every drag direction; speed uses only horizontal motion.
onPanStart: onDragStart,
onPanUpdate: onDragUpdate,
onPanEnd: onDragEnd,
onPanCancel: onDragCancel,
child: const SizedBox.expand(),
),
),
),
],
),
),
);
}
}
@@ -0,0 +1,95 @@
import 'dart:math' as math;
import 'dart:ui';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline_ui.dart';
/// Speed segments in the clip's local coordinates. Paint and hit targets use
/// the same cells, including the minimum pixel width and clipping at low zoom.
final class TimelineSpeedLayout {
TimelineSpeedLayout({
required TimelineClipLayout clip,
required Iterable<ClipSpeedSegment> segments,
required double pixelsPerTick,
}) {
bounds = Rect.fromLTWH(
clip.header.left,
clip.header.top,
clip.header.width,
math.min(
clip.header.height,
EditorLayoutConfiguration.speedSectionHeight.toDouble(),
),
);
var left = bounds.left;
final cells = <TimelineSpeedSegmentLayout>[];
for (final segment in segments) {
final width = math.max(1.0, segment.projectDuration * pixelsPerTick);
final right = math.min(bounds.right, left + width);
final cell = Rect.fromLTWH(
math.min(left, bounds.right),
bounds.top,
math.max(0, right - left),
bounds.height,
);
cells.add(TimelineSpeedSegmentLayout(segment, cell));
left += width;
}
this.segments = List.unmodifiable(cells);
}
late final Rect bounds;
late final List<TimelineSpeedSegmentLayout> segments;
}
final class TimelineSpeedSegmentLayout {
TimelineSpeedSegmentLayout(this.segment, this.cell) {
bar = Rect.fromLTWH(
cell.left,
cell.top,
math.max(0, cell.width - segmentGap),
cell.height,
);
label = Rect.fromLTWH(
bar.left + math.min(labelPadding, bar.width / 2),
bar.top + 1,
math.max(0, bar.width - labelPadding * 2),
math.max(0, bar.height - 2),
);
final horizontalInset = math.min(handleInset, bar.width / 2);
final verticalInset = math.min(handleInset, bar.height / 2);
final handleRight = bar.right - horizontalInset;
final availableWidth = math.max(0.0, bar.width - horizontalInset * 2);
final handleTop = bar.top + verticalInset;
final handleHeight = math.max(0.0, bar.height - verticalInset * 2);
handle = Rect.fromLTWH(
handleRight - math.min(handleWidth, availableWidth),
handleTop,
math.min(handleWidth, availableWidth),
handleHeight,
);
final hitWidth = math.min(handleHitWidth, bar.width);
handleHit = Rect.fromLTWH(
(handle.center.dx - hitWidth / 2).clamp(bar.left, bar.right - hitWidth),
bar.top,
hitWidth,
bar.height,
);
}
static const segmentGap = 2.0;
static const labelPadding = 8.0;
static const handleInset = 3.0;
static const handleWidth = 2.0;
static const handleHitWidth = 10.0;
static const handleRadius = 1.0;
final ClipSpeedSegment segment;
final Rect cell;
late final Rect bar;
late final Rect label;
late final Rect handle;
late final Rect handleHit;
double get speed => segment.speed;
}