Files
cutdex/lib/features/properties/picture_properties.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

771 lines
27 KiB
Dart

import 'dart:async';
import 'package:cutdex/l10n/l10n.dart';
import 'dart:math' as math;
import 'package:cutdex/features/properties/animation_labels.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/preview.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_session.dart';
import '../preview/preview_panel.dart';
import 'property_number_input.dart';
import 'picture_edits.dart';
class PictureProperties extends ConsumerStatefulWidget {
const PictureProperties({
super.key,
required this.projectId,
required this.timelineId,
required this.session,
required this.sequence,
required this.clip,
this.animationView = false,
});
final String projectId;
final String timelineId;
final EditorTimelineSession session;
final SequenceId sequence;
final ElementRecord clip;
final bool animationView;
@override
ConsumerState<PictureProperties> createState() => _PicturePropertiesState();
}
class _PicturePropertiesState extends ConsumerState<PictureProperties> {
bool _locked = true;
PictureEditsProvider get _editProvider =>
pictureEditsProvider(widget.session, widget.sequence, widget.clip.id);
PictureEdits get _edits => ref.read(_editProvider.notifier);
bool get _saving => ref.read(_editProvider).isLoading;
bool Function() _guard() {
final session = widget.session;
final sequence = widget.sequence;
final clip = widget.clip.id;
return () =>
mounted &&
_scrubBase == null &&
identical(widget.session, session) &&
widget.sequence == sequence &&
widget.clip.id == clip;
}
String? get _error => switch (ref.read(_editProvider).error) {
PictureEditException(:final failure) => switch (failure) {
PictureEditFailure.keyframes => context.l10n.updateKeyframesFailed,
PictureEditFailure.alignment => context.l10n.alignClipFailed,
PictureEditFailure.invalidTransform => context.l10n.invalidTransform,
PictureEditFailure.transform => context.l10n.updatePictureFailed,
},
_ => null,
};
PreviewTransformEdit? _scrubEdit;
ClipTransform? _scrubBase;
ClipTransform? _scrubTimeline;
TimelineVersion? _scrubVersion;
int? _scrubTick;
String? _scrubField;
ClipTransform Function(ClipTransform, double)? _scrubChange;
bool _startScrub(
PreviewController? preview,
String field,
ClipTransform Function(ClipTransform, double) change,
) {
if (_scrubBase != null ||
_saving ||
preview?.transforms.hasPending == true ||
widget.session.activeSequenceId != widget.sequence) {
return false;
}
final base = _current();
if (base == null) return false;
_scrubBase = base;
_scrubField = field;
_scrubChange = change;
_scrubVersion = widget.session.view(widget.sequence).version.kernelVersion;
_scrubTick = widget.session.view(widget.sequence).playheadTick;
if (preview != null) {
final visual = preview.visualForProperties(widget.clip.id);
if (visual == null ||
(_scrubEdit = preview.transforms.begin(visual)) == null) {
_scrubBase = null;
_scrubField = null;
_scrubChange = null;
_scrubVersion = null;
return false;
}
_scrubBase = _scrubEdit!.value;
}
return true;
}
bool get _scrubValid =>
_scrubBase != null &&
_scrubEdit?.released != true &&
_scrubTick == widget.session.view(widget.sequence).playheadTick &&
widget.session.activeSequenceId == widget.sequence &&
identical(
_scrubVersion,
widget.session.view(widget.sequence).version.kernelVersion,
);
void _updateScrub(double distance) {
if (!_scrubValid) {
_cancelScrub();
return;
}
final value = _scrubChange!(_scrubBase!, distance);
if (!value.isValid) return;
setState(() => _scrubTimeline = value);
_scrubEdit?.update(value);
}
void _endScrub(PreviewController? preview) {
final value = _scrubTimeline;
if (!_scrubValid ||
value == null ||
(value.x == _scrubBase!.x &&
value.y == _scrubBase!.y &&
value.rotation == _scrubBase!.rotation &&
value.scale == _scrubBase!.scale &&
value.scaleY == _scrubBase!.scaleY)) {
_cancelScrub();
return;
}
final edit = _scrubEdit;
_scrubEdit = null;
_scrubBase = null;
_scrubField = null;
_scrubChange = null;
_scrubVersion = null;
setState(() => _scrubTimeline = null);
if (edit != null) {
unawaited(edit.end());
} else {
unawaited(_commit(preview, (_) => value));
}
}
void _cancelScrub() {
final edit = _scrubEdit;
_scrubEdit = null;
_scrubBase = null;
_scrubField = null;
_scrubChange = null;
_scrubVersion = null;
if (mounted) setState(() => _scrubTimeline = null);
edit?.cancel();
}
@override
void dispose() {
final edit = _scrubEdit;
_scrubEdit = null;
if (edit != null) scheduleMicrotask(edit.cancel);
super.dispose();
}
ClipAnimation? _animation() => _edits.animation();
ClipTransform? _current() => _animation()?.value;
Future<void> _editKeys(
PreviewController? preview,
TransformChannel channel, {
KeyframeAction? action,
ParameterInterpolation? interpolation,
}) {
FocusManager.instance.primaryFocus?.unfocus();
FocusManager.instance.applyFocusChangesIfNeeded();
return _edits.editKeys(
preview,
channel,
action: action,
interpolation: interpolation,
isCurrent: _guard(),
);
}
Future<void> _align(PreviewController preview, CanvasAlignment alignment) =>
_edits.align(preview, alignment, isCurrent: _guard());
Future<bool> _commit(
PreviewController? preview,
ClipTransform Function(ClipTransform) change,
) => _edits.commit(preview, change, isCurrent: _guard());
@override
Widget build(BuildContext context) {
ref.watch(_editProvider);
final preview = ref
.watch(editorPreviewProvider(widget.projectId, widget.timelineId))
.asData
?.value;
Widget contents() {
final animation = _animation();
final live = preview?.activeSequence() == widget.sequence
? preview?.transforms.valueFor(widget.clip.id)
: null;
final value =
(_scrubValid ? _scrubTimeline : null) ??
live ??
_current() ??
ClipTransform.fromRecord(widget.clip);
final locked = preview?.aspectRatioLocked ?? _locked;
final canvas = widget.session.canvas;
final enabled = !_saving;
final canvasDragging =
preview?.transforms.hasPending == true && _scrubEdit == null;
Widget keyButton(TransformChannel channel) {
final keyed = animation?.keyed(channel) == true;
final animated = animation?.animated(channel) == true;
return IconButton(
key: ValueKey('picture-key-${channel.name}'),
tooltip: context.l10n.toggleKeyframe(
keyed ? context.l10n.delete : context.l10n.addKeyframeAction,
channel.label(context),
),
isSelected: keyed,
color: animated ? Theme.of(context).colorScheme.primary : null,
icon: Transform.rotate(
angle: math.pi / 4,
child: Icon(keyed ? Icons.square : Icons.crop_square, size: 12),
),
onPressed:
enabled &&
_scrubBase == null &&
!canvasDragging &&
animation != null
? () => _editKeys(preview, channel)
: null,
);
}
Widget axes(TransformChannel channel, Widget first, Widget second) =>
LayoutBuilder(
builder: (context, constraints) => Row(
children: [
Expanded(
child: constraints.maxWidth < 240
? Column(
children: [
first,
const SizedBox(height: AppSpacing.small),
second,
],
)
: Row(
children: [
Expanded(child: first),
const SizedBox(width: AppSpacing.small),
Expanded(child: second),
],
),
),
const SizedBox(width: AppSpacing.small),
keyButton(channel),
],
),
);
Widget keyTools(TransformChannel channel) {
if (animation == null || !animation.animated(channel)) {
return const SizedBox.shrink();
}
final times = animation.keyTimes(channel);
final tick = animation.playhead;
final previous = times.where((t) => t < tick).lastOrNull;
final next = times.where((t) => t > tick).firstOrNull;
final canEdit = enabled && _scrubBase == null && !canvasDragging;
Future<void> seek(int target) async {
await preview?.pauseForCanvasInteraction();
if (mounted && widget.session.activeSequenceId == widget.sequence) {
widget.session.view(widget.sequence).seekTo(target);
}
}
return SizedBox(
height: AppControlSize.standard,
child: Row(
children: [
Text(
context.l10n.keyframeCount(times.length),
style: Theme.of(context).textTheme.bodySmall,
),
const Spacer(),
IconButton(
key: ValueKey('picture-key-previous-${channel.name}'),
tooltip: context.l10n.previousKeyframe(channel.label(context)),
onPressed: canEdit && previous != null
? () => seek(previous)
: null,
icon: const Icon(Icons.chevron_left, size: 16),
),
IconButton(
key: ValueKey('picture-key-next-${channel.name}'),
tooltip: context.l10n.nextKeyframe(channel.label(context)),
onPressed: canEdit && next != null ? () => seek(next) : null,
icon: const Icon(Icons.chevron_right, size: 16),
),
AppDropdownMenu(
key: ValueKey('picture-key-menu-${channel.name}'),
enabled: canEdit,
builder: (context, toggle, focus) => IconButton(
tooltip: context.l10n.keyframeSettings(
channel.label(context),
),
focusNode: focus,
onPressed: toggle,
icon: const Icon(Icons.more_horiz, size: 16),
),
items: [
for (final (mode, label) in [
(ParameterInterpolation.linear, context.l10n.linear),
(ParameterInterpolation.hold, context.l10n.hold),
(ParameterInterpolation.easeIn, context.l10n.easeIn),
(ParameterInterpolation.easeOut, context.l10n.easeOut),
(ParameterInterpolation.easeInOut, context.l10n.easeInOut),
])
AppMenuItem(
label: label,
selected: animation.interpolation(channel) == mode,
onPressed: animation.keyed(channel)
? () => _editKeys(
preview,
channel,
action: KeyframeAction.set,
interpolation: mode,
)
: null,
),
const AppMenuSeparator(),
AppMenuItem(
label: context.l10n.removeAllKeyframes,
destructive: true,
onPressed: animation.animated(channel)
? () => _editKeys(
preview,
channel,
action: KeyframeAction.clear,
)
: null,
),
],
),
],
),
);
}
Widget number(
String id,
String? label,
double value,
ClipTransform Function(ClipTransform, double) change, {
String? unit,
double min = double.negativeInfinity,
double max = double.infinity,
bool wrapRotation = false,
}) => PropertyNumberInput(
key: ValueKey(id),
label: label,
unit: unit,
value: value,
enabled: !_saving,
readOnly: _scrubBase != null || preview?.transforms.hasPending == true,
submit: (v) => _commit(preview, (current) => change(current, v)),
onScrubStart: () => _startScrub(
preview,
id,
(base, distance) => change(
base,
wrapRotation
? normalizeRotationDegrees(value + distance)
: (value + distance).clamp(min, max),
),
),
onScrubUpdate: _updateScrub,
onScrubEnd: () => _endScrub(preview),
onScrubCancel: _cancelScrub,
scrubbing: _scrubField == id,
editContext: (
widget.session.view(widget.sequence).version.kernelVersion,
widget.session.view(widget.sequence).playheadTick,
),
);
Widget section(List<Widget> children) => Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
final content = Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (widget.animationView && animation != null) ...[
section([
_KeyframeTimeline(
animation: animation,
enabled: enabled && !canvasDragging && _scrubBase == null,
onSeek: (tick) async {
await preview?.pauseForCanvasInteraction();
if (mounted &&
widget.session.activeSequenceId == widget.sequence) {
widget.session.view(widget.sequence).seekTo(tick);
}
},
),
]),
],
if (!widget.animationView) ...[
section([
Text(
context.l10n.alignment,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
LayoutBuilder(
builder: (context, constraints) => Wrap(
spacing: AppSpacing.small,
runSpacing: AppSpacing.small,
children: [
for (final group in [
[
(
CanvasAlignment.left,
context.l10n.alignLeft,
Icons.align_horizontal_left,
),
(
CanvasAlignment.horizontalCenter,
context.l10n.alignHorizontalCenter,
Icons.align_horizontal_center,
),
(
CanvasAlignment.right,
context.l10n.alignRight,
Icons.align_horizontal_right,
),
],
[
(
CanvasAlignment.top,
context.l10n.alignTop,
Icons.align_vertical_top,
),
(
CanvasAlignment.verticalCenter,
context.l10n.alignVerticalCenter,
Icons.align_vertical_center,
),
(
CanvasAlignment.bottom,
context.l10n.alignBottom,
Icons.align_vertical_bottom,
),
],
])
SizedBox(
width: constraints.maxWidth < 200
? constraints.maxWidth
: (constraints.maxWidth - AppSpacing.small) / 2,
child: AppButtonGroup(
expanded: true,
label: context.l10n.alignment,
children: [
for (final (alignment, label, icon) in group)
IconButton(
key: ValueKey(
'picture-align-${alignment.name}',
),
tooltip: label,
icon: Icon(icon, size: AppIconSize.standard),
onPressed: () {
if (!enabled ||
canvasDragging ||
preview == null ||
preview.busy ||
preview.visualForProperties(
widget.clip.id,
) ==
null) {
return;
}
unawaited(_align(preview, alignment));
},
),
],
),
),
],
),
),
]),
],
section([
Text(
context.l10n.position,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
axes(
TransformChannel.position,
number(
'picture-x',
'X',
value.x * canvas.width,
(c, v) => c.copyWith(x: v / canvas.width),
),
number(
'picture-y',
'Y',
value.y * canvas.height,
(c, v) => c.copyWith(y: v / canvas.height),
),
),
keyTools(TransformChannel.position),
]),
section([
Row(
children: [
Expanded(
child: number(
'picture-rotation',
context.l10n.rotation,
value.rotation,
(c, v) => c.copyWith(rotation: v),
unit: '°',
wrapRotation: true,
),
),
const SizedBox(width: AppSpacing.small),
keyButton(TransformChannel.rotation),
],
),
keyTools(TransformChannel.rotation),
]),
section([
Row(
children: [
Expanded(
child: Text(
context.l10n.scale,
style: AppTheme.propertySectionTitleStyle(context),
),
),
IconButton(
key: const Key('picture-lock'),
tooltip: context.l10n.keepAspectRatio,
icon: const Icon(Icons.lock_open_outlined),
selectedIcon: const Icon(Icons.lock_outline),
isSelected: locked,
onPressed: enabled
? () {
if (preview?.transforms.hasPending == true) return;
preview?.setAspectRatioLocked(!locked);
setState(() => _locked = !locked);
}
: null,
),
],
),
const SizedBox(height: AppSpacing.small),
axes(
TransformChannel.scale,
number(
'picture-scale-x',
'W',
value.scale * 100,
(c, v) => c.copyWith(
scale: v / 100,
scaleY: locked ? c.scaleY * v / 100 / c.scale : c.scaleY,
),
unit: '%',
min: locked ? math.max(1.0, value.scale / value.scaleY) : 1,
max: locked
? math.min(10000.0, 10000 * value.scale / value.scaleY)
: 10000,
),
number(
'picture-scale-y',
'H',
value.scaleY * 100,
(c, v) => c.copyWith(
scaleY: v / 100,
scale: locked ? c.scale * v / 100 / c.scaleY : c.scale,
),
unit: '%',
min: locked ? math.max(1.0, value.scaleY / value.scale) : 1,
max: locked
? math.min(10000.0, 10000 * value.scaleY / value.scale)
: 10000,
),
),
keyTools(TransformChannel.scale),
]),
if (_error != null)
section([
Text(
_error!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
]),
],
);
// Canvas gestures own edits temporarily, without changing control colors.
return ExcludeFocus(
excluding: canvasDragging,
child: IgnorePointer(ignoring: canvasDragging, child: content),
);
}
return ListenableBuilder(
listenable: Listenable.merge([
widget.session.view(widget.sequence),
if (preview != null) ...[preview, preview.transforms],
]),
builder: (_, _) => contents(),
);
}
}
class _KeyframeTimeline extends StatelessWidget {
const _KeyframeTimeline({
required this.animation,
required this.enabled,
required this.onSeek,
});
final ClipAnimation animation;
final bool enabled;
final ValueChanged<int> onSeek;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final end = animation.lastTick;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Text(
context.l10n.keyframes,
style: AppTheme.propertySectionTitleStyle(context),
),
const Spacer(),
Text(
'${(animation.localTick / TimelineClock.ticksPerSecond).toStringAsFixed(2)} s',
style: Theme.of(context).textTheme.bodySmall,
),
],
),
const SizedBox(height: AppSpacing.small),
for (final channel in TransformChannel.values)
SizedBox(
height: 32,
child: Row(
children: [
SizedBox(
width: 36,
child: Text(
channel.label(context),
style: Theme.of(context).textTheme.bodySmall,
),
),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) {
final extent = (constraints.maxWidth - 20).clamp(
1.0,
double.infinity,
);
double x(int tick) =>
10 +
(end == 0 ? 0 : (tick - animation.start) / end).clamp(
0.0,
1.0,
) *
extent;
return GestureDetector(
key: ValueKey('picture-key-track-${channel.name}'),
behavior: HitTestBehavior.opaque,
onTapDown: !enabled
? null
: (details) {
final fraction =
((details.localPosition.dx - 10) / extent)
.clamp(0.0, 1.0);
final tick =
((fraction * end / animation.frameTicks)
.round() *
animation.frameTicks)
.clamp(0, end);
onSeek(animation.start + tick);
},
child: Stack(
children: [
Positioned(
left: 10,
right: 10,
top: 15,
height: 1,
child: ColoredBox(color: colors.outlineVariant),
),
if (animation.containsPlayhead)
Positioned(
left: x(animation.playhead),
top: 3,
bottom: 3,
width: 1,
child: ColoredBox(color: colors.primary),
),
for (final tick in animation.keyTimes(channel))
Positioned(
left: x(tick) - AppControlSize.compact / 2,
top: 4,
width: AppControlSize.compact,
height: AppControlSize.compact,
child: IconButton(
key: ValueKey(
'picture-key-marker-${channel.name}-$tick',
),
tooltip:
'${channel.label(context)} ${((tick - animation.start) / TimelineClock.ticksPerSecond).toStringAsFixed(2)} s',
padding: EdgeInsets.zero,
onPressed: enabled
? () => onSeek(tick)
: null,
icon: Transform.rotate(
angle: math.pi / 4,
child: Icon(
Icons.square,
size: 9,
color: tick == animation.playhead
? colors.primary
: colors.onSurfaceVariant,
),
),
),
),
],
),
);
},
),
),
],
),
),
],
);
}
}