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,26 @@
import 'package:flutter/widgets.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
extension TransformChannelLabel on TransformChannel {
String label(BuildContext context) => switch (this) {
TransformChannel.position => context.l10n.position,
TransformChannel.rotation => context.l10n.rotation,
TransformChannel.scale => context.l10n.scale,
};
}
Map<String, List<String>> localizedMaskChannels(BuildContext context) => {
context.l10n.position: ['center.x', 'center.y'],
context.l10n.size: ['width', 'height'],
context.l10n.rotation: ['rotation'],
context.l10n.feather: ['feather'],
};
// Stable channel identifiers are independent of the interface language.
const maskChannels = {
'position': ['center.x', 'center.y'],
'size': ['width', 'height'],
'rotation': ['rotation'],
'feather': ['feather'],
};
@@ -0,0 +1,27 @@
/// Slider travel is a presentation choice, independent of authored gain.
abstract final class AudioGainScale {
static const decimalPlaces = 1;
static double quantizeDb(double db) => double.parse(formatDb(db));
static String formatDb(double db) {
final text = db.toStringAsFixed(decimalPlaces);
return text == '-0.0' ? '0.0' : text;
}
// Reserve 70% of travel for -24...+6 dB. Zero is a separate mute endpoint.
static double dbAt(double position) {
if (!position.isFinite) throw ArgumentError.value(position);
final p = position.clamp(0.0, 1.0);
if (p <= .01) return -90;
if (p <= .2) return -90 + (p - .01) / .19 * 66;
if (p <= .9) return -24 + (p - .2) / .7 * 30;
return 6 + (p - .9) / .1 * 6;
}
static double positionAt(double db) {
if (!db.isFinite) throw ArgumentError.value(db);
final value = db.clamp(-90.0, 12.0);
if (value <= -24) return .01 + (value + 90) / 66 * .19;
if (value <= 6) return .2 + (value + 24) / 30 * .7;
return .9 + (value - 6) / 6 * .1;
}
}
@@ -0,0 +1,362 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex/features/properties/audio_gain_scale.dart';
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/timeline_session.dart';
import 'package:cutdex_sdk/editor.dart';
export 'package:cutdex_sdk/editor.dart' show ClipAudioGain;
class AudioProperties extends StatefulWidget {
const AudioProperties({
super.key,
required this.session,
required this.sequence,
required this.clip,
required this.hasAudio,
});
final EditorTimelineSession session;
final SequenceId sequence;
final ElementRecord clip;
final bool hasAudio;
@override
State<AudioProperties> createState() => _AudioPropertiesState();
}
class _AudioPropertiesState extends State<AudioProperties> {
final _text = TextEditingController();
final _focus = FocusNode();
ClipAudioGain? _timeline;
Object? _editVersion;
int? _editTick;
String? _error;
bool _dirty = false;
@override
void initState() {
super.initState();
_focus.addListener(_focusChanged);
}
void _focusChanged() {
if (_focus.hasFocus) {
_beginEdit();
} else if (_dirty) {
_submit(_text.text);
}
}
@override
void dispose() {
widget.session.clearAudioGainPreview(widget.clip.id);
_focus.removeListener(_focusChanged);
_focus.dispose();
_text.dispose();
super.dispose();
}
void _beginEdit() {
final view = widget.session.view(widget.sequence);
_editVersion = view.version.kernelVersion;
_editTick = view.playheadTick;
}
bool get _editValid {
final view = widget.session.view(widget.sequence);
return widget.session.activeSequenceId == widget.sequence &&
(_editVersion == null ||
identical(_editVersion, view.version.kernelVersion)) &&
(_editTick == null || _editTick == view.playheadTick);
}
bool _commit(ClipAudioGain value) {
widget.session.clearAudioGainPreview(widget.clip.id);
final view = widget.session.view(widget.sequence);
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip.id);
if (handle == null || !_editValid) {
setState(() {
_timeline = null;
_dirty = false;
_error = null;
});
return false;
}
try {
widget.session.commands.setAudio(
sequence: widget.sequence,
clip: widget.clip.id,
tick: _editTick ?? view.playheadTick,
db: value.db,
muted: value.muted,
);
setState(() {
_timeline = null;
_dirty = false;
_editVersion = null;
_editTick = null;
_error = null;
});
return true;
} catch (_) {
setState(() => _error = context.l10n.updateVolumeFailed);
return false;
}
}
bool _submit(String text) {
final db = double.tryParse(text.trim());
if (db == null || !db.isFinite || db < -90 || db > 12) {
setState(() => _error = context.l10n.invalidGain);
return false;
}
return _commit(ClipAudioGain(AudioGainScale.quantizeDb(db)));
}
@override
Widget build(BuildContext context) {
final view = widget.session.view(widget.sequence);
return ListenableBuilder(
listenable: view,
builder: (context, _) {
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip.id);
final record = handle == null ? widget.clip : query.element(handle);
final localTick = handle == null
? 0
: view.playheadTick - query.absoluteStart(handle);
final sourceTick = TimelineSourceClock(record).nearestSourceTick(
localTick.clamp(0, record.duration > 0 ? record.duration - 1 : 0),
);
final saved = ClipAudioGain.fromRecord(record, sourceTick: sourceTick);
final keyed =
record.parameters?[ClipAudioGain.gainId]?.keyframeAt(sourceTick) !=
null;
final value = _editValid ? _timeline ?? saved : saved;
final enabled = widget.hasAudio && handle != null;
if (!_dirty) {
final text = value.muted ? '-∞' : AudioGainScale.formatDb(value.db);
if (_text.text != text) _text.text = text;
}
if (ClipAudioGain.isDetached(record)) {
return Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
context.l10n.audioDetached,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
OutlinedButton.icon(
key: const Key('audio-restore'),
icon: const Icon(Icons.volume_up_outlined),
label: Text(context.l10n.restoreAudio),
onPressed: !enabled || !widget.session.acceptsEdits
? null
: () {
try {
widget.session.commands.setAudio(
sequence: widget.sequence,
clip: record.id,
muted: false,
);
setState(() {
_timeline = null;
_dirty = false;
_editVersion = null;
_error = null;
});
} catch (_) {
setState(
() => _error = context.l10n.updateVolumeFailed,
);
}
},
),
if (_error != null) Text(_error!),
],
),
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
widget.hasAudio
? context.l10n.volume
: context.l10n.unboundAudio,
style: AppTheme.propertySectionTitleStyle(context),
),
),
IconButton(
key: const Key('audio-key'),
tooltip: context.l10n.toggleKeyframe(
keyed
? context.l10n.delete
: context.l10n.addKeyframeAction,
context.l10n.volume,
),
isSelected: keyed,
icon: Transform.rotate(
angle: 0.7853981633974483,
child: Icon(
keyed ? Icons.square : Icons.crop_square,
size: 12,
),
),
onPressed: !enabled
? null
: () {
if (_dirty && !_submit(_text.text)) return;
_focus.unfocus();
FocusManager.instance
.applyFocusChangesIfNeeded();
try {
widget.session.commands.editKeyframeChannel(
sequence: widget.sequence,
clip: widget.clip.id,
tick: view.playheadTick,
parameterIds: [ClipAudioGain.gainId],
);
} catch (_) {
setState(
() => _error =
context.l10n.updateKeyframesFailed,
);
}
},
),
IconButton(
key: const Key('audio-mute'),
tooltip: value.muted
? context.l10n.unmute
: context.l10n.mute,
isSelected: value.muted,
icon: Icon(
value.muted ? Icons.volume_off : Icons.volume_up,
),
onPressed: !enabled
? null
: () {
_editVersion = null;
_editTick = null;
_commit(
ClipAudioGain(saved.db, muted: !saved.muted),
);
},
),
IconButton(
key: const Key('audio-reset'),
tooltip: context.l10n.resetVolume,
icon: const Icon(Icons.restart_alt),
onPressed: !enabled
? null
: () {
_editVersion = null;
_editTick = null;
_commit(const ClipAudioGain(0));
},
),
],
),
const SizedBox(height: AppSpacing.small),
Row(
children: [
Expanded(
child: AppSlider(
key: const Key('audio-slider'),
value: value.muted
? 0
: AudioGainScale.positionAt(value.db),
semanticFormatterCallback: (p) => p == 0
? context.l10n.mute
: '${AudioGainScale.formatDb(AudioGainScale.dbAt(p))} dB',
onChangeStart: !enabled
? null
: (_) {
_focus.unfocus();
FocusManager.instance
.applyFocusChangesIfNeeded();
_beginEdit();
},
onChanged: !enabled
? null
: (p) => setState(() {
if (!_editValid) {
widget.session.clearAudioGainPreview(
widget.clip.id,
);
_timeline = null;
return;
}
_dirty = false;
_timeline = p == 0
? ClipAudioGain(saved.db, muted: true)
: ClipAudioGain(
AudioGainScale.quantizeDb(
AudioGainScale.dbAt(p),
),
);
widget.session.previewAudioGain(
widget.sequence,
widget.clip.id,
_timeline!,
);
}),
onChangeEnd: !enabled
? null
: (_) => _commit(_timeline ?? saved),
),
),
const SizedBox(width: AppSpacing.small),
SizedBox(
width: 84,
child: AppTextField(
key: const Key('audio-db'),
controller: _text,
focusNode: _focus,
label: null,
unit: 'dB',
enabled: enabled,
errorText: _error,
keyboardType: const TextInputType.numberWithOptions(
signed: true,
decimal: true,
),
onChanged: (_) {
if (!_dirty) {
_beginEdit();
}
_dirty = true;
},
onSubmitted: _submit,
),
),
],
),
],
),
),
],
);
},
);
}
}
@@ -0,0 +1,23 @@
import 'package:flutter/widgets.dart';
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
abstract final class ProjectCanvasPresets {
static const values = {
'16:9': ProjectCanvas.widescreen,
'4:3': ProjectCanvas(1440, 1080),
'1:1': ProjectCanvas(1080, 1080),
'9:16': ProjectCanvas(1080, 1920),
};
}
extension ProjectCanvasLabel on ProjectCanvas {
String label(BuildContext context) {
for (final entry in ProjectCanvasPresets.values.entries) {
if ((entry.value.aspectRatio - aspectRatio).abs() < 0.000001) {
return entry.key;
}
}
return context.l10n.custom;
}
}
@@ -0,0 +1,797 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_session.dart';
import 'property_number_input.dart';
enum _CaptionPropertyCategory {
captions,
text;
String label(BuildContext context) => switch (this) {
captions => context.l10n.captions,
text => context.l10n.text,
};
}
/// Presentation only: validation, publication and history belong to editor.
class CaptionProperties extends StatefulWidget {
const CaptionProperties({
super.key,
required this.session,
required this.sequence,
required this.clipId,
this.transformProperties,
});
final EditorTimelineSession session;
final SequenceId sequence;
final String clipId;
final Widget? transformProperties;
@override
State<CaptionProperties> createState() => _CaptionPropertiesState();
}
class _CaptionPropertiesState extends State<CaptionProperties> {
static const _maximumCommandSeconds = 9000000000000.0;
_CaptionPropertyCategory _selected = _CaptionPropertyCategory.text;
final _captionSearch = TextEditingController();
String _captionQuery = '';
bool _wrapCaptions = false;
String? _scrubField;
double? _scrubBase;
double? _scrubTimeline;
double _scrubScale = 1;
String? _scrubVersion;
bool _save(SetCaption command) {
try {
widget.session.setCaption(widget.sequence, command);
return true;
} on CommandRejected catch (error) {
ScaffoldMessenger.maybeOf(context)?.showSnackBar(
SnackBar(
content: Text(
error.code == 'staleVersion'
? context.l10n.captionEditChanged
: context.l10n.editFailed,
),
),
);
return false;
}
}
CommandTime _seconds(double value) =>
CommandTime((value * 1000).round(), 1000);
bool _startScrub(String field, double value, double scale) {
if (_scrubField != null) return false;
setState(() {
_scrubField = field;
_scrubBase = value;
_scrubTimeline = value;
_scrubScale = scale;
_scrubVersion = widget.session.version;
});
return true;
}
void _updateScrub(double distance, double min, double max) {
final base = _scrubBase;
if (base == null || _scrubVersion != widget.session.version) {
_cancelScrub();
return;
}
setState(() {
_scrubTimeline = (base + distance * _scrubScale).clamp(min, max);
});
}
void _endScrub() {
final field = _scrubField;
final value = _scrubTimeline;
final base = _scrubBase;
final version = _scrubVersion;
_clearScrub();
if (field == null || value == null || value == base || version == null) {
return;
}
final command = switch (field) {
'fontSize' => SetCaption(
captionId: widget.clipId,
fontSize: value,
expectedVersion: version,
),
'strokeWidth' => SetCaption(
captionId: widget.clipId,
strokeWidth: value,
expectedVersion: version,
),
'positionY' => SetCaption(
captionId: widget.clipId,
positionY: value,
expectedVersion: version,
),
'start' => SetCaption(
captionId: widget.clipId,
start: _seconds(value),
expectedVersion: version,
),
'duration' => SetCaption(
captionId: widget.clipId,
duration: _seconds(value),
expectedVersion: version,
),
_ => null,
};
if (command != null) _save(command);
}
void _clearScrub() {
if (!mounted) return;
setState(() {
_scrubField = null;
_scrubBase = null;
_scrubTimeline = null;
_scrubVersion = null;
});
}
void _cancelScrub() => _clearScrub();
@override
void didUpdateWidget(covariant CaptionProperties oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.clipId == widget.clipId &&
oldWidget.sequence == widget.sequence) {
return;
}
if (oldWidget.sequence != widget.sequence ||
oldWidget.session != widget.session) {
_selected = _CaptionPropertyCategory.text;
}
_scrubField = null;
_scrubBase = null;
_scrubTimeline = null;
_scrubVersion = null;
}
@override
void dispose() {
_captionSearch.dispose();
super.dispose();
}
void _selectCue(String id) {
final query = widget.session.persistence
.timeline(widget.sequence)
.current
.query();
final cue = query.elementById(ElementId(id));
if (cue == null) return;
final identity = widget.session.captionComponentFor(widget.sequence, cue);
widget.session.view(widget.sequence).setSelection([identity ?? cue]);
}
Widget _captionList(
BuildContext context,
List<({String id, String text})> cues,
) {
final matches = cues.indexed
.where((entry) => entry.$2.text.toLowerCase().contains(_captionQuery))
.toList();
return Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
vertical: AppSpacing.small,
),
child: SizedBox(
height: 28,
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: TextField(
key: const ValueKey('caption-search'),
controller: _captionSearch,
style: Theme.of(context).textTheme.bodyMedium,
cursorHeight: AppTheme.inputCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: context.l10n.searchOptions(
context.l10n.captions,
),
isDense: true,
constraints: const BoxConstraints.tightFor(height: 28),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 0,
),
prefixIcon: const Icon(Icons.search, size: 14),
prefixIconConstraints: const BoxConstraints(
minWidth: 28,
minHeight: 28,
),
),
onChanged: (value) => setState(
() => _captionQuery = value.trim().toLowerCase(),
),
),
),
const SizedBox(width: 4),
IconButton(
key: const ValueKey('caption-wrap-toggle'),
tooltip: _wrapCaptions
? context.l10n.captionSingleLine
: context.l10n.captionWrapLines,
isSelected: _wrapCaptions,
color: _wrapCaptions
? Theme.of(context).colorScheme.primary
: null,
icon: const Icon(Icons.wrap_text, size: 16),
padding: EdgeInsets.zero,
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.standard,
),
constraints: const BoxConstraints.tightFor(
width: 28,
height: 28,
),
onPressed: () =>
setState(() => _wrapCaptions = !_wrapCaptions),
),
],
),
),
),
Expanded(
child: matches.isEmpty
? Center(
child: Text(
context.l10n.noMatchingCaptions,
style: Theme.of(context).textTheme.bodySmall,
),
)
: ScrollEdgeFadeBuilder(
key: const ValueKey('caption-scroll-fade'),
builder: (controller) => ListView(
key: const ValueKey('caption-scroll-list'),
controller: controller,
padding: EdgeInsets.zero,
physics: const ClampingScrollPhysics(),
children: [
for (final (index, cue) in matches)
Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
vertical: AppSpacing.hairline,
),
child: Material(
borderRadius: BorderRadius.circular(
AppRadius.menuItem,
),
color: cue.id == widget.clipId
? Theme.of(context).colorScheme.onSurface
.withValues(alpha: .05)
: Colors.transparent,
child: InkWell(
key: ValueKey('caption-list-${cue.id}'),
onTap: () => _selectCue(cue.id),
borderRadius: BorderRadius.circular(
AppRadius.menuItem,
),
child: ConstrainedBox(
constraints: const BoxConstraints(
minHeight: 28,
),
child: Padding(
padding: EdgeInsets.zero,
child: Row(
children: [
SizedBox(
width:
cues.length.toString().length * 8.0,
child: Text(
'${index + 1}',
key: ValueKey(
'caption-number-${cue.id}',
),
textAlign: TextAlign.center,
style: Theme.of(context)
.textTheme
.bodySmall,
),
),
const SizedBox(width: 6),
Expanded(
child: Text(
cue.text,
key: ValueKey(
'caption-content-${cue.id}',
),
style: Theme.of(context)
.textTheme
.bodyMedium,
maxLines: _wrapCaptions ? null : 1,
softWrap: _wrapCaptions,
overflow: _wrapCaptions
? TextOverflow.visible
: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
SizedBox(
width: 28,
height: 28,
child: IconButton(
key: ValueKey(
'caption-action-${cue.id}',
),
tooltip: context.l10n.select,
padding: EdgeInsets.zero,
constraints:
const BoxConstraints.tightFor(
width: 28,
height: 28,
),
icon: const Icon(
Icons.chevron_right,
size: 14,
),
onPressed: () => _selectCue(cue.id),
),
),
],
),
),
),
),
),
),
],
),
),
),
],
);
}
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.session,
builder: (context, _) {
final q = widget.session.persistence
.timeline(widget.sequence)
.current
.query();
final handle = q.elementById(ElementId(widget.clipId));
if (handle == null) return Text(context.l10n.captionDeleted);
final clip = q.element(handle);
final isRole = clip.containerStoryline != null;
final role = isRole
? handle
: widget.session.captionRole(widget.sequence);
final child = role == null ? null : q.element(role).containerStoryline;
final cues = <({String id, String text})>[
if (child != null)
for (final cue in q.storylineElements(child))
if (q.element(cue).payloadRef case final payload?)
if (widget.session.payloadFor(payload)?.type == 'caption')
(
id: q.element(cue).id.value,
text: widget.session
.caption(widget.sequence, q.element(cue).id.value)
.text,
),
];
final categories = [
_CaptionPropertyCategory.captions,
if (!isRole) _CaptionPropertyCategory.text,
];
final selected = isRole ? _CaptionPropertyCategory.captions : _selected;
Widget panel(Widget content) => WorkspacePanel(
paintBackground: false,
headerHeight: CompactPanelTabs.height,
headerPadding: EdgeInsets.zero,
showHeaderDivider: false,
controls: CompactPanelTabs<_CaptionPropertyCategory>(
values: categories,
selected: selected,
labelBuilder: (category) => category.label(context),
tabKeyBuilder: (category) =>
ValueKey('caption-property-tab-${category.name}'),
onSelected: (category) => setState(() => _selected = category),
),
child: content,
);
if (selected == _CaptionPropertyCategory.captions) {
return panel(_captionList(context, cues));
}
final caption = widget.session.caption(widget.sequence, widget.clipId);
final version = widget.session.version;
final start = RationalTime.timelineTicks(q.localContext(handle).start)
.seconds;
final duration = RationalTime.timelineTicks(clip.duration).seconds;
double shown(String field, double value) =>
_scrubField == field ? _scrubTimeline ?? value : value;
Widget number({
required String field,
required String label,
required double value,
required double min,
required double max,
required double scale,
String? unit,
int decimalPlaces = 2,
required SetCaption Function(double, String) command,
}) => PropertyNumberInput(
key: ValueKey('caption-$field'),
label: label,
unit: unit,
decimalPlaces: decimalPlaces,
value: shown(field, value),
enabled: true,
readOnly: _scrubField != null,
scrubbing: _scrubField == field,
editContext: (widget.clipId, version),
submit: (next) async {
if (!next.isFinite || next < min || next > max) return false;
return _save(command(next, version));
},
onScrubStart: () => _startScrub(field, value, scale),
onScrubUpdate: (distance) => _updateScrub(distance, min, max),
onScrubEnd: _endScrub,
onScrubCancel: _cancelScrub,
);
return panel(
ScrollEdgeFadeBuilder(
key: const ValueKey('caption-detail-scroll-fade'),
builder: (controller) => ListView(
controller: controller,
padding: const EdgeInsets.symmetric(vertical: AppSpacing.small),
children:
[
Row(
children: [
Expanded(
child: Text(
context.l10n.textClip,
style: AppTheme.propertySectionTitleStyle(
context,
),
),
),
IconButton(
tooltip: context.l10n.deleteCaption,
icon: const Icon(Icons.delete_outline),
onPressed: () {
try {
widget.session.commands.applyEdit(
widget.sequence,
DeleteClip(
widget.clipId,
expectedVersion: version,
),
);
} on CommandRejected {
ScaffoldMessenger.maybeOf(
context,
)?.showSnackBar(
SnackBar(
content: Text(context.l10n.captionChanged),
),
);
}
},
),
],
),
const SizedBox(height: AppSpacing.small),
Text(
context.l10n.content,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
_CaptionTextInput(
key: ValueKey(('caption-text', widget.clipId)),
value: caption.text,
maxLines: 3,
onSubmit: (text) => _save(
SetCaption(
captionId: widget.clipId,
text: text,
expectedVersion: version,
),
),
),
const SizedBox(height: AppSpacing.small),
number(
field: 'fontSize',
label: context.l10n.fontSize,
value: caption.fontSize,
min: 1,
max: 1024,
scale: .2,
unit: 'px',
command: (value, expected) => SetCaption(
captionId: widget.clipId,
fontSize: value,
expectedVersion: expected,
),
),
const SizedBox(height: AppSpacing.small),
_CaptionColorInput(
key: ValueKey(('caption-color', widget.clipId)),
value: caption.color,
label: context.l10n.color,
onSubmit: (color) => _save(
SetCaption(
captionId: widget.clipId,
color: color,
expectedVersion: version,
),
),
),
const SizedBox(height: AppSpacing.small),
_CaptionColorInput(
key: ValueKey(('caption-strokeColor', widget.clipId)),
value: caption.strokeColor,
label: context.l10n.outlineColor,
onSubmit: (color) => _save(
SetCaption(
captionId: widget.clipId,
strokeColor: color,
expectedVersion: version,
),
),
),
const SizedBox(height: AppSpacing.small),
number(
field: 'strokeWidth',
label: context.l10n.outlineWidth,
value: caption.strokeWidth,
min: 0,
max: caption.fontSize,
scale: .05,
unit: 'px',
command: (value, expected) => SetCaption(
captionId: widget.clipId,
strokeWidth: value,
expectedVersion: expected,
),
),
if (widget.transformProperties case final transform?) ...[
const SizedBox(height: AppSpacing.medium),
const Divider(height: 1),
const SizedBox(height: AppSpacing.medium),
Text(
context.l10n.transform,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
transform,
],
const SizedBox(height: AppSpacing.medium),
Text(
context.l10n.captionBaseline,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
number(
field: 'positionY',
label: context.l10n.vertical,
value: caption.positionY,
min: -.5,
max: .5,
scale: .002,
decimalPlaces: 3,
command: (value, expected) => SetCaption(
captionId: widget.clipId,
positionY: value,
expectedVersion: expected,
),
),
const SizedBox(height: AppSpacing.medium),
Text(
context.l10n.time,
style: AppTheme.propertySectionTitleStyle(context),
),
const SizedBox(height: AppSpacing.small),
LayoutBuilder(
builder: (context, constraints) {
Widget startField() => number(
field: 'start',
label: context.l10n.start,
value: start,
min: 0,
max: _maximumCommandSeconds,
scale: .01,
unit: context.l10n.seconds,
decimalPlaces: 3,
command: (value, expected) => SetCaption(
captionId: widget.clipId,
start: _seconds(value),
expectedVersion: expected,
),
);
Widget durationField() => number(
field: 'duration',
label: context.l10n.duration,
value: duration,
min: .001,
max: _maximumCommandSeconds,
scale: .01,
unit: context.l10n.seconds,
decimalPlaces: 3,
command: (value, expected) => SetCaption(
captionId: widget.clipId,
duration: _seconds(value),
expectedVersion: expected,
),
);
if (constraints.maxWidth < 240) {
return Column(
children: [
startField(),
const SizedBox(height: AppSpacing.small),
durationField(),
],
);
}
return Row(
children: [
Expanded(child: startField()),
const SizedBox(width: AppSpacing.small),
Expanded(child: durationField()),
],
);
},
),
]
.map(
(item) =>
item is SizedBox ||
identical(item, widget.transformProperties)
? item
: Padding(
padding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
),
child: item,
),
)
.toList(),
),
),
);
},
);
}
class _CaptionTextInput extends StatefulWidget {
const _CaptionTextInput({
super.key,
required this.value,
required this.onSubmit,
this.label,
this.maxLines = 1,
});
final String value;
final String? label;
final int maxLines;
final bool Function(String) onSubmit;
@override
State<_CaptionTextInput> createState() => _CaptionTextInputState();
}
class _CaptionTextInputState extends State<_CaptionTextInput> {
late final _controller = TextEditingController(text: widget.value);
final _focus = FocusNode();
bool _dirty = false;
String? _error;
@override
void initState() {
super.initState();
_focus.addListener(_handleFocus);
}
void _handleFocus() {
if (!_focus.hasFocus) _submit();
}
void _submit() {
if (!_dirty) return;
final accepted = widget.onSubmit(_controller.text);
if (!mounted) return;
setState(() {
_dirty = false;
_error = accepted ? null : context.l10n.notApplied;
if (!accepted) _controller.text = widget.value;
});
}
@override
void didUpdateWidget(covariant _CaptionTextInput oldWidget) {
super.didUpdateWidget(oldWidget);
if (!_dirty && _controller.text != widget.value) {
_controller.text = widget.value;
}
}
@override
void dispose() {
_focus.removeListener(_handleFocus);
_focus.dispose();
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => AppTextField(
controller: _controller,
focusNode: _focus,
label: widget.label,
minLines: widget.maxLines,
maxLines: widget.maxLines,
textInputAction: TextInputAction.done,
errorText: _error,
onChanged: (_) {
_dirty = true;
if (_error != null) setState(() => _error = null);
},
onEditingComplete: () {},
onSubmitted: (_) => _submit(),
onTapOutside: (_) => _focus.unfocus(),
);
}
class _CaptionColorInput extends StatelessWidget {
const _CaptionColorInput({
super.key,
required this.value,
required this.label,
required this.onSubmit,
});
final String value;
final String label;
final bool Function(String) onSubmit;
@override
Widget build(BuildContext context) => Row(
children: [
Container(
width: 20,
height: 20,
decoration: BoxDecoration(
color: Color(int.parse('FF${value.substring(1)}', radix: 16)),
border: Border.all(color: Theme.of(context).colorScheme.outline),
borderRadius: BorderRadius.circular(AppRadius.extraSmall),
),
),
const SizedBox(width: AppSpacing.small),
Expanded(
child: _CaptionTextInput(
value: value,
label: label,
onSubmit: onSubmit,
),
),
],
);
}
@@ -0,0 +1,103 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/runtime.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/media_color_interpretation.dart';
import '../../workspace/timeline_session.dart';
import '../preview/preview_panel.dart';
class ColorInterpretationProperties extends ConsumerWidget {
const ColorInterpretationProperties({
super.key,
required this.projectId,
required this.timelineId,
required this.session,
required this.assetId,
required this.trackIndex,
});
final String projectId;
final String timelineId;
final EditorTimelineSession session;
final String assetId;
final int trackIndex;
@override
Widget build(BuildContext context, WidgetRef ref) {
final preview = ref
.watch(editorPreviewProvider(projectId, timelineId))
.asData
?.value;
Widget contents() {
final selected = session.mediaColorInterpretation(assetId, trackIndex);
final colors = preview?.videoColorSpaces(assetId);
final detected = colors?.elementAtOrNull(trackIndex);
final reported =
colors != null && trackIndex >= 0 && trackIndex < colors.length;
final status = selected != null
? context.l10n.manualColorSpace(selected.label(context.l10n))
: detected != null
? context.l10n.detectedColorSpace(detected.label(context.l10n))
: reported
? context.l10n.unknownColorSpace
: context.l10n.colorInfoNotLoaded;
return Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: AppSpacing.gap,
children: [
Row(
children: [
Expanded(
child: Text(
context.l10n.mediaColorSpace,
style: AppTheme.propertySectionTitleStyle(context),
),
),
Flexible(
child: AppSelect<String>(
emptyLabel: context.l10n.noMatchingOptions,
key: const Key('media-color-menu'),
outlined: false,
label: context.l10n.mediaColorInterpretation,
value: selected?.name ?? 'auto',
onChanged: !reported
? null
: (value) => session.commands.setMediaColor(
assetId,
trackIndex,
value == 'auto'
? null
: MediaColorSpace.values.byName(value),
),
options: [
AppSelectOption('auto', context.l10n.auto),
for (final color in RenderColorSpace.values)
AppSelectOption(color.name, color.label(context.l10n)),
],
),
),
],
),
Text(
status,
key: const Key('media-color-status'),
style: Theme.of(context).textTheme.bodySmall,
),
],
),
);
}
return ListenableBuilder(
listenable: Listenable.merge([session, ?preview]),
builder: (_, _) => contents(),
);
}
}
@@ -0,0 +1,579 @@
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/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 '../preview/preview_panel.dart';
import 'property_number_input.dart';
class MaskProperties extends ConsumerStatefulWidget {
const MaskProperties({
super.key,
required this.projectId,
required this.timelineId,
required this.element,
});
final String projectId, timelineId;
final ElementId element;
@override
ConsumerState<MaskProperties> createState() => _MaskPropertiesState();
}
class _MaskPropertiesState extends ConsumerState<MaskProperties> {
PreviewController? _preview;
ElementId? _boundElement;
String? _error;
int? _gestureGeneration;
String? _scrubField;
ClipMask Function(double)? _scrubChange;
double _scrubValue = 0;
Future<bool>? _pendingValueCommit;
@override
void dispose() {
final preview = _preview;
scheduleMicrotask(() => preview?.releaseMaskEditing(this));
super.dispose();
}
bool _apply(PreviewController preview, ClipMask mask) {
try {
preview.applyMask(mask);
setState(() => _error = null);
return true;
} catch (_) {
setState(() => _error = context.l10n.updateMaskFailed);
return false;
}
}
Future<bool> _submitValue(
PreviewController preview,
double value,
double min,
double max,
ClipMask Function(double) change,
) {
final operation = Future<bool>.sync(
() =>
value.isFinite &&
value >= min &&
value <= max &&
_apply(preview, change(value)),
);
_pendingValueCommit = operation;
return operation.whenComplete(() {
if (identical(_pendingValueCommit, operation)) _pendingValueCommit = null;
});
}
Future<void> _editKeys(PreviewController preview, List<String> ids) async {
final element = widget.element;
final maskId = preview.selectedMaskId;
final tick = preview.positionTick;
FocusManager.instance.primaryFocus?.unfocus();
FocusManager.instance.applyFocusChangesIfNeeded();
final pending = _pendingValueCommit;
if (pending != null && !await pending) return;
if (!mounted ||
widget.element != element ||
_preview != preview ||
preview.maskEditingElement != element ||
preview.selectedMaskId != maskId ||
preview.positionTick != tick ||
_scrubField != null) {
return;
}
try {
preview.toggleMaskKeys(ids);
} catch (_) {
setState(() => _error = context.l10n.updateKeyframesFailed);
}
}
@override
Widget build(BuildContext context) {
final preview = ref
.watch(editorPreviewProvider(widget.projectId, widget.timelineId))
.value;
if (preview == null) return const SizedBox.shrink();
if (_preview != preview || _boundElement != widget.element) {
final previous = _preview;
if (previous != null && previous != preview) {
scheduleMicrotask(() => previous.releaseMaskEditing(this));
}
_preview = preview;
_boundElement = widget.element;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && identical(_preview, preview)) {
preview.setMaskEditing(widget.element, owner: this);
}
});
}
return ListenableBuilder(
listenable: preview,
builder: (context, _) {
final mask = preview.maskFor(widget.element);
final animation = preview.maskAnimation(widget.element);
final stack = preview.maskStackFor(widget.element);
final layers =
preview.maskStackFor(widget.element)?.layers ?? <ClipMaskLayer>[];
final selectedId = preview.selectedMaskId;
final initialId = layers.where((e) => e.enabled).firstOrNull?.id;
final enabled =
preview.canPlay &&
stack != null &&
preview.maskEditingElement == widget.element;
Widget key(String label) {
final ids = localizedMaskChannels(context)[label]!;
return IconButton(
key: ValueKey('mask-key-$label'),
tooltip: context.l10n.keyframeLabel(label),
isSelected: animation?.keyed(ids) == true,
onPressed: enabled && _scrubField == null && animation != null
? () => _editKeys(preview, ids)
: null,
icon: Transform.rotate(
angle: math.pi / 4,
child: Icon(
animation?.keyed(ids) == true
? Icons.square
: Icons.crop_square,
size: 12,
color: animation?.keyed(ids) == true
? Theme.of(context).colorScheme.primary
: null,
),
),
);
}
Widget field(
String label,
double value,
double min,
double max,
ClipMask Function(double) change, {
String? unit,
bool wrapRotation = false,
}) => PropertyNumberInput(
key: ValueKey((selectedId, label)),
label: label,
unit: unit,
value: value,
enabled: enabled,
readOnly: _scrubField != null,
scrubbing: _scrubField == label,
editContext: (
widget.element,
selectedId,
stack?.record,
stack?.localTick,
),
submit: (v) => _submitValue(preview, v, min, max, change),
onScrubStart: () {
if (_scrubField != null) return false;
final preparing = preview.beginMaskEdit();
final generation = _gestureGeneration = preview.maskEditGeneration;
_scrubChange = change;
_scrubValue = value;
setState(() => _scrubField = label);
unawaited(
preparing
.then((ready) {
if (!ready && generation == preview.maskEditGeneration) {
preview.cancelMaskEdit();
if (mounted) setState(() => _scrubField = null);
}
})
.catchError((Object error) {
if (generation == preview.maskEditGeneration) {
preview.cancelMaskEdit();
if (mounted) {
setState(() {
_scrubField = null;
_error = context.l10n.maskPreviewFailed;
});
}
}
}),
);
return true;
},
onScrubUpdate: (distance) {
if (_gestureGeneration == preview.maskEditGeneration) {
preview.updateMask(
_scrubChange!(
wrapRotation
? normalizeRotationDegrees(_scrubValue + distance)
: (_scrubValue + distance).clamp(min, max),
),
);
}
},
onScrubEnd: () {
if (_gestureGeneration == preview.maskEditGeneration) {
preview.endMaskEdit();
}
if (mounted) setState(() => _scrubField = null);
},
onScrubCancel: () {
if (_gestureGeneration == preview.maskEditGeneration) {
preview.cancelMaskEdit();
}
if (mounted) setState(() => _scrubField = null);
},
);
Widget axes(String label, 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),
key(label),
],
),
);
Widget singleField(String label, Widget input) => Row(
children: [
Expanded(child: input),
const SizedBox(width: AppSpacing.small),
key(label),
],
);
Widget heading(String label) => Padding(
padding: const EdgeInsets.only(bottom: AppSpacing.small),
child: Text(
label,
style: AppTheme.propertySectionTitleStyle(context),
),
);
Widget section(List<Widget> children) => Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
section([
Row(
children: [
Expanded(
child: Text(
context.l10n.mask,
style: AppTheme.propertySectionTitleStyle(context),
),
),
IconButton(
tooltip: context.l10n.moveMaskUp,
icon: const Icon(Icons.arrow_upward, size: 18),
onPressed:
enabled &&
layers.indexWhere((e) => e.id == selectedId) > 0
? () {
final ids = layers.map((e) => e.id).toList();
final i = ids.indexOf(selectedId!);
ids.insert(i - 1, ids.removeAt(i));
preview.reorderMasks(ids);
}
: null,
),
IconButton(
tooltip: context.l10n.moveMaskDown,
icon: const Icon(Icons.arrow_downward, size: 18),
onPressed:
enabled &&
selectedId != null &&
layers.lastOrNull?.id != selectedId
? () {
final ids = layers.map((e) => e.id).toList();
final i = ids.indexOf(selectedId);
ids.insert(i + 1, ids.removeAt(i));
preview.reorderMasks(ids);
}
: null,
),
AppDropdownMenu(
enabled: enabled,
items: [
AppMenuItem(
label: context.l10n.rectangle,
onPressed: () =>
preview.addMask(ClipMaskShape.rectangle),
),
AppMenuItem(
label: context.l10n.ellipse,
onPressed: () => preview.addMask(ClipMaskShape.ellipse),
),
],
builder: (context, toggle, focusNode) => IconButton(
focusNode: focusNode,
tooltip: context.l10n.addMask,
icon: const Icon(Icons.add),
onPressed: toggle,
),
),
],
),
]),
section([
AppItemGroup(
children: [
for (var i = 0; i < layers.length; i++)
AppItem(
key: ValueKey('mask-row-${layers[i].id}'),
selected: layers[i].id == selectedId,
onPressed: () => preview.selectMask(layers[i].id),
leading: IconButton(
tooltip: layers[i].enabled
? context.l10n.disableMask
: context.l10n.enableMask,
icon: Icon(
layers[i].enabled
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
size: 18,
),
onPressed: enabled
? () => preview.configureMask(
layers[i].id,
enabled: !layers[i].enabled,
)
: null,
),
actions: [
AppDropdownMenu(
enabled: enabled && layers[i].id != initialId,
items: [
for (final mode in ClipMaskMode.values)
AppMenuItem(
label: [
context.l10n.add,
context.l10n.intersect,
context.l10n.subtract,
][mode.index],
selected: layers[i].mode == mode,
onPressed: () => preview.configureMask(
layers[i].id,
mode: mode,
),
),
],
builder: (context, toggle, focusNode) => IconButton(
focusNode: focusNode,
tooltip: layers[i].id == initialId
? context.l10n.initialRegion
: context.l10n.maskMode(
[
context.l10n.add,
context.l10n.intersect,
context.l10n.subtract,
][layers[i].mode.index],
),
icon: Icon(
layers[i].id == initialId
? Icons.crop_free
: switch (layers[i].mode) {
ClipMaskMode.add => Icons.add,
ClipMaskMode.intersect =>
Icons.filter_center_focus,
ClipMaskMode.subtract => Icons.remove,
},
size: AppIconSize.standard,
),
onPressed: toggle,
),
),
IconButton(
tooltip: context.l10n.deleteMask,
icon: const Icon(Icons.delete_outline, size: 18),
onPressed: enabled
? () => preview.removeMask(layers[i].id)
: null,
),
],
child: Text(
'${[context.l10n.rectangle, context.l10n.ellipse][layers[i].mask.shape.index]} ${i + 1}',
),
),
],
),
]),
if (mask != null && animation != null) ...[
section([
Row(
children: [
Expanded(
child: AppButtonGroup(
expanded: true,
label: context.l10n.mask,
children: [
for (final entry in [
(
ClipMaskShape.rectangle,
Icons.crop_square,
context.l10n.rectangle,
),
(
ClipMaskShape.ellipse,
Icons.circle_outlined,
context.l10n.ellipse,
),
])
IconButton(
key: ValueKey('mask-shape-${entry.$1.name}'),
tooltip: entry.$3,
isSelected: mask.shape == entry.$1,
onPressed: enabled
? () => _apply(
preview,
mask.copyWith(shape: entry.$1),
)
: null,
icon: Icon(entry.$2),
),
],
),
),
const SizedBox(width: AppSpacing.small),
IconButton(
tooltip: context.l10n.resetMask,
onPressed: enabled
? () => _apply(preview, ClipMask(shape: mask.shape))
: null,
icon: const Icon(Icons.restart_alt),
),
],
),
]),
section([
heading(context.l10n.position),
axes(
context.l10n.position,
field(
'X',
mask.x * 100,
ClipMask.minPosition * 100,
ClipMask.maxPosition * 100,
(v) => mask.copyWith(x: v / 100),
unit: '%',
),
field(
'Y',
mask.y * 100,
ClipMask.minPosition * 100,
ClipMask.maxPosition * 100,
(v) => mask.copyWith(y: v / 100),
unit: '%',
),
),
]),
section([
singleField(
context.l10n.rotation,
field(
context.l10n.rotation,
mask.rotation,
-180,
180,
(v) => mask.copyWith(rotation: v),
unit: '°',
wrapRotation: true,
),
),
]),
section([
heading(context.l10n.size),
axes(
context.l10n.size,
field(
'W',
mask.width * 100,
ClipMask.minExtent * 100,
ClipMask.maxExtent * 100,
(v) => mask.copyWith(width: v / 100),
unit: '%',
),
field(
'H',
mask.height * 100,
ClipMask.minExtent * 100,
ClipMask.maxExtent * 100,
(v) => mask.copyWith(height: v / 100),
unit: '%',
),
),
]),
section([
singleField(
context.l10n.feather,
field(
context.l10n.feather,
mask.feather * 100,
0,
100,
(v) => mask.copyWith(feather: v / 100),
unit: '%',
),
),
]),
section([
Row(
children: [
Expanded(
child: Text(
context.l10n.invert,
style: AppTheme.propertySectionTitleStyle(context),
),
),
AppSwitch(
value: mask.inverted,
onChanged: enabled
? (v) => _apply(preview, mask.copyWith(inverted: v))
: null,
),
],
),
]),
],
if (_error != null)
section([
Text(
_error!,
style: TextStyle(color: Theme.of(context).colorScheme.error),
),
]),
],
);
},
);
}
}
+215
View File
@@ -0,0 +1,215 @@
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:freezed_annotation/freezed_annotation.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
import '../../workspace/timeline_session.dart';
part 'picture_edits.g.dart';
part 'picture_edits.freezed.dart';
enum PictureEditFailure { keyframes, alignment, invalidTransform, transform }
@freezed
abstract class PictureEditTarget with _$PictureEditTarget {
const factory PictureEditTarget({
required TimelineVersion version,
required int tick,
}) = _PictureEditTarget;
}
@freezed
abstract class PictureEditException
with _$PictureEditException
implements Exception {
const factory PictureEditException(PictureEditFailure failure) =
_PictureEditException;
}
@riverpod
class PictureEdits extends _$PictureEdits {
Future<bool>? _pending;
@override
AsyncValue<void> build(
EditorTimelineSession session,
SequenceId sequence,
ElementId clip,
) => const AsyncData(null);
PictureEditTarget _capture() {
final view = session.view(sequence);
return PictureEditTarget(
version: view.version.kernelVersion,
tick: view.playheadTick,
);
}
bool _valid(
PictureEditTarget target,
bool Function() isCurrent,
PreviewController? preview,
) {
if (!ref.mounted ||
!isCurrent() ||
session.activeSequenceId != sequence ||
preview?.transforms.hasPending == true) {
return false;
}
final view = session.view(sequence);
return target.tick == view.playheadTick &&
identical(target.version, view.version.kernelVersion);
}
ClipAnimation? animation() {
final view = session.view(sequence);
final query = view.version.kernelVersion.query();
final handle = query.elementById(clip);
return handle == null
? null
: ClipAnimation.at(
query,
handle,
view.playheadTick,
TimelineClock.standard.toTicks(
session.persistence.timeline(sequence).format.frameDuration,
),
);
}
Future<bool> commit(
PreviewController? preview,
ClipTransform Function(ClipTransform) change, {
required bool Function() isCurrent,
}) {
if (state.isLoading || preview?.transforms.hasPending == true) {
return Future.value(false);
}
final target = _capture();
final work = _run(PictureEditFailure.transform, () async {
await preview?.pauseForCanvasInteraction();
if (!_valid(target, isCurrent, preview)) return false;
final current = animation()?.value;
if (current == null) return false;
final value = change(current);
if (!value.isValid) {
throw const PictureEditException(PictureEditFailure.invalidTransform);
}
if (value.x == current.x &&
value.y == current.y &&
value.scale == current.scale &&
value.scaleY == current.scaleY &&
value.rotation == current.rotation) {
return true;
}
session.commands.setTransform(
sequence: sequence,
clip: clip,
tick: target.tick,
change: (_) => value,
);
return true;
});
_pending = work;
return work.whenComplete(() {
if (identical(_pending, work)) _pending = null;
});
}
Future<void> editKeys(
PreviewController? preview,
TransformChannel channel, {
KeyframeAction? action,
ParameterInterpolation? interpolation,
required bool Function() isCurrent,
}) async {
final pending = _pending;
if (pending != null && !await pending) return;
if (!ref.mounted ||
!isCurrent() ||
state.isLoading ||
preview?.transforms.hasPending == true) {
return;
}
final target = _capture();
await _run(PictureEditFailure.keyframes, () async {
await preview?.pauseForCanvasInteraction();
if (!_valid(target, isCurrent, preview)) return false;
session.commands.editKeyframeChannel(
sequence: sequence,
clip: clip,
tick: target.tick,
parameterIds: channel.ids,
action: action,
interpolation: interpolation,
);
return true;
});
}
Future<void> align(
PreviewController preview,
CanvasAlignment alignment, {
required bool Function() isCurrent,
}) async {
if (state.isLoading || preview.transforms.hasPending) return;
final target = _capture();
final current = animation();
if (current == null) return;
final command = AlignClip(
clipId: clip.value,
at: CommandTime(
current.start + current.localTick,
TimelineClock.ticksPerSecond,
),
alignment: alignment,
expectedVersion: session.version,
);
await _run(PictureEditFailure.alignment, () async {
await preview.pauseForCanvasInteraction();
await session.alignClip(
sequence,
command,
isCancelled: () => !_valid(target, isCurrent, preview),
);
return true;
});
}
Future<bool> _run(
PictureEditFailure failure,
Future<bool> Function() action,
) async {
final lease = ref.keepAlive();
state = const AsyncLoading();
try {
final applied = await session.runEditAsync(
switch (failure) {
PictureEditFailure.keyframes => 'editKeyframes',
PictureEditFailure.alignment => 'alignClip',
_ => 'setTransform',
},
sequence,
action,
context: {
'clipIds': [clip.value],
'entryPoint': 'property',
'playheadTick': session.view(sequence).playheadTick,
},
);
if (ref.mounted) state = const AsyncData(null);
return applied;
} catch (error, stack) {
if (ref.mounted) {
state = AsyncError(
error is PictureEditException ? error : PictureEditException(failure),
stack,
);
}
return false;
} finally {
lease.close();
}
}
}
@@ -0,0 +1,627 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'picture_edits.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$PictureEditTarget {
TimelineVersion get version;
int get tick;
/// Create a copy of PictureEditTarget
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$PictureEditTargetCopyWith<PictureEditTarget> get copyWith =>
_$PictureEditTargetCopyWithImpl<PictureEditTarget>(
this as PictureEditTarget,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as PictureEditTarget;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is PictureEditTarget &&
(identical(other.version, _this.version) ||
other.version == _this.version) &&
(identical(other.tick, _this.tick) || other.tick == _this.tick));
}
@override
int get hashCode {
final _this = this as PictureEditTarget;
return Object.hash(runtimeType, _this.version, _this.tick);
}
@override
String toString() {
final _this = this as PictureEditTarget;
return 'PictureEditTarget(version: ${_this.version}, tick: ${_this.tick})';
}
}
/// @nodoc
abstract mixin class $PictureEditTargetCopyWith<$Res> {
factory $PictureEditTargetCopyWith(
PictureEditTarget value,
$Res Function(PictureEditTarget) _then,
) = _$PictureEditTargetCopyWithImpl;
@useResult
$Res call({TimelineVersion version, int tick});
}
/// @nodoc
class _$PictureEditTargetCopyWithImpl<$Res>
implements $PictureEditTargetCopyWith<$Res> {
_$PictureEditTargetCopyWithImpl(this._self, this._then);
final PictureEditTarget _self;
final $Res Function(PictureEditTarget) _then;
/// Create a copy of PictureEditTarget
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? version = null, Object? tick = null}) {
return _then(
PictureEditTarget(
version: null == version
? _self.version
: version // ignore: cast_nullable_to_non_nullable
as TimelineVersion,
tick: null == tick
? _self.tick
: tick // ignore: cast_nullable_to_non_nullable
as int,
),
);
}
}
/// Adds pattern-matching-related methods to [PictureEditTarget].
extension PictureEditTargetPatterns on PictureEditTarget {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_PictureEditTarget value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _PictureEditTarget() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_PictureEditTarget value) $default,
) {
final _that = this;
switch (_that) {
case _PictureEditTarget():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_PictureEditTarget value)? $default,
) {
final _that = this;
switch (_that) {
case _PictureEditTarget() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(TimelineVersion version, int tick)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _PictureEditTarget() when $default != null:
return $default(_that.version, _that.tick);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(TimelineVersion version, int tick) $default,
) {
final _that = this;
switch (_that) {
case _PictureEditTarget():
return $default(_that.version, _that.tick);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(TimelineVersion version, int tick)? $default,
) {
final _that = this;
switch (_that) {
case _PictureEditTarget() when $default != null:
return $default(_that.version, _that.tick);
case _:
return null;
}
}
}
/// @nodoc
class _PictureEditTarget implements PictureEditTarget {
const _PictureEditTarget({required this.version, required this.tick});
@override
final TimelineVersion version;
@override
final int tick;
/// Create a copy of PictureEditTarget
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$PictureEditTargetCopyWith<_PictureEditTarget> get copyWith =>
__$PictureEditTargetCopyWithImpl<_PictureEditTarget>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _PictureEditTarget &&
(identical(other.version, version) || other.version == version) &&
(identical(other.tick, tick) || other.tick == tick));
}
@override
int get hashCode {
return Object.hash(runtimeType, version, tick);
}
@override
String toString() {
return 'PictureEditTarget(version: $version, tick: $tick)';
}
}
/// @nodoc
abstract mixin class _$PictureEditTargetCopyWith<$Res>
implements $PictureEditTargetCopyWith<$Res> {
factory _$PictureEditTargetCopyWith(
_PictureEditTarget value,
$Res Function(_PictureEditTarget) _then,
) = __$PictureEditTargetCopyWithImpl;
@override
@useResult
$Res call({TimelineVersion version, int tick});
}
/// @nodoc
class __$PictureEditTargetCopyWithImpl<$Res>
implements _$PictureEditTargetCopyWith<$Res> {
__$PictureEditTargetCopyWithImpl(this._self, this._then);
final _PictureEditTarget _self;
final $Res Function(_PictureEditTarget) _then;
/// Create a copy of PictureEditTarget
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? version = null, Object? tick = null}) {
return _then(
_PictureEditTarget(
version: null == version
? _self.version
: version // ignore: cast_nullable_to_non_nullable
as TimelineVersion,
tick: null == tick
? _self.tick
: tick // ignore: cast_nullable_to_non_nullable
as int,
),
);
}
}
/// @nodoc
mixin _$PictureEditException {
PictureEditFailure get failure;
/// Create a copy of PictureEditException
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$PictureEditExceptionCopyWith<PictureEditException> get copyWith =>
_$PictureEditExceptionCopyWithImpl<PictureEditException>(
this as PictureEditException,
_$identity,
);
@override
bool operator ==(Object other) {
final _this = this as PictureEditException;
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is PictureEditException &&
(identical(other.failure, _this.failure) ||
other.failure == _this.failure));
}
@override
int get hashCode {
final _this = this as PictureEditException;
return Object.hash(runtimeType, _this.failure);
}
@override
String toString() {
final _this = this as PictureEditException;
return 'PictureEditException(failure: ${_this.failure})';
}
}
/// @nodoc
abstract mixin class $PictureEditExceptionCopyWith<$Res> {
factory $PictureEditExceptionCopyWith(
PictureEditException value,
$Res Function(PictureEditException) _then,
) = _$PictureEditExceptionCopyWithImpl;
@useResult
$Res call({PictureEditFailure failure});
}
/// @nodoc
class _$PictureEditExceptionCopyWithImpl<$Res>
implements $PictureEditExceptionCopyWith<$Res> {
_$PictureEditExceptionCopyWithImpl(this._self, this._then);
final PictureEditException _self;
final $Res Function(PictureEditException) _then;
/// Create a copy of PictureEditException
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({Object? failure = null}) {
return _then(
PictureEditException(
null == failure
? _self.failure
: failure // ignore: cast_nullable_to_non_nullable
as PictureEditFailure,
),
);
}
}
/// Adds pattern-matching-related methods to [PictureEditException].
extension PictureEditExceptionPatterns on PictureEditException {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeMap<TResult extends Object?>(
TResult Function(_PictureEditException value)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _PictureEditException() when $default != null:
return $default(_that);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult map<TResult extends Object?>(
TResult Function(_PictureEditException value) $default,
) {
final _that = this;
switch (_that) {
case _PictureEditException():
return $default(_that);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? mapOrNull<TResult extends Object?>(
TResult? Function(_PictureEditException value)? $default,
) {
final _that = this;
switch (_that) {
case _PictureEditException() when $default != null:
return $default(_that);
case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs
TResult maybeWhen<TResult extends Object?>(
TResult Function(PictureEditFailure failure)? $default, {
required TResult orElse(),
}) {
final _that = this;
switch (_that) {
case _PictureEditException() when $default != null:
return $default(_that.failure);
case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs
TResult when<TResult extends Object?>(
TResult Function(PictureEditFailure failure) $default,
) {
final _that = this;
switch (_that) {
case _PictureEditException():
return $default(_that.failure);
case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs
TResult? whenOrNull<TResult extends Object?>(
TResult? Function(PictureEditFailure failure)? $default,
) {
final _that = this;
switch (_that) {
case _PictureEditException() when $default != null:
return $default(_that.failure);
case _:
return null;
}
}
}
/// @nodoc
class _PictureEditException implements PictureEditException {
const _PictureEditException(this.failure);
@override
final PictureEditFailure failure;
/// Create a copy of PictureEditException
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$PictureEditExceptionCopyWith<_PictureEditException> get copyWith =>
__$PictureEditExceptionCopyWithImpl<_PictureEditException>(
this,
_$identity,
);
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _PictureEditException &&
(identical(other.failure, failure) || other.failure == failure));
}
@override
int get hashCode {
return Object.hash(runtimeType, failure);
}
@override
String toString() {
return 'PictureEditException(failure: $failure)';
}
}
/// @nodoc
abstract mixin class _$PictureEditExceptionCopyWith<$Res>
implements $PictureEditExceptionCopyWith<$Res> {
factory _$PictureEditExceptionCopyWith(
_PictureEditException value,
$Res Function(_PictureEditException) _then,
) = __$PictureEditExceptionCopyWithImpl;
@override
@useResult
$Res call({PictureEditFailure failure});
}
/// @nodoc
class __$PictureEditExceptionCopyWithImpl<$Res>
implements _$PictureEditExceptionCopyWith<$Res> {
__$PictureEditExceptionCopyWithImpl(this._self, this._then);
final _PictureEditException _self;
final $Res Function(_PictureEditException) _then;
/// Create a copy of PictureEditException
/// with the given fields replaced by the non-null parameter values.
@override
@pragma('vm:prefer-inline')
$Res call({Object? failure = null}) {
return _then(
_PictureEditException(
null == failure
? _self.failure
: failure // ignore: cast_nullable_to_non_nullable
as PictureEditFailure,
),
);
}
}
@@ -0,0 +1,120 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'picture_edits.dart';
// **************************************************************************
// RiverpodGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// ignore_for_file: type=lint, type=warning
@ProviderFor(PictureEdits)
final pictureEditsProvider = PictureEditsFamily._();
final class PictureEditsProvider
extends $NotifierProvider<PictureEdits, AsyncValue<void>> {
PictureEditsProvider._({
required PictureEditsFamily super.from,
required (EditorTimelineSession, SequenceId, ElementId) super.argument,
}) : super(
retry: null,
name: r'pictureEditsProvider',
isAutoDispose: true,
dependencies: null,
$allTransitiveDependencies: null,
);
@override
String debugGetCreateSourceHash() => _$pictureEditsHash();
@override
String toString() {
return r'pictureEditsProvider'
''
'$argument';
}
@$internal
@override
PictureEdits create() => PictureEdits();
/// {@macro riverpod.override_with_value}
Override overrideWithValue(AsyncValue<void> value) {
return $ProviderOverride(
origin: this,
providerOverride: $SyncValueProvider<AsyncValue<void>>(value),
);
}
@override
bool operator ==(Object other) {
return other is PictureEditsProvider && other.argument == argument;
}
@override
int get hashCode {
return argument.hashCode;
}
}
String _$pictureEditsHash() => r'6385f3bd53094d57ed054681d142591e059e8b08';
final class PictureEditsFamily extends $Family
with
$ClassFamilyOverride<
PictureEdits,
AsyncValue<void>,
AsyncValue<void>,
AsyncValue<void>,
(EditorTimelineSession, SequenceId, ElementId)
> {
PictureEditsFamily._()
: super(
retry: null,
name: r'pictureEditsProvider',
dependencies: null,
$allTransitiveDependencies: null,
isAutoDispose: true,
);
PictureEditsProvider call(
EditorTimelineSession session,
SequenceId sequence,
ElementId clip,
) => PictureEditsProvider._(argument: (session, sequence, clip), from: this);
@override
String toString() => r'pictureEditsProvider';
}
abstract class _$PictureEdits extends $Notifier<AsyncValue<void>> {
late final _$args =
ref.$arg as (EditorTimelineSession, SequenceId, ElementId);
EditorTimelineSession get session => _$args.$1;
SequenceId get sequence => _$args.$2;
ElementId get clip => _$args.$3;
AsyncValue<void> build(
EditorTimelineSession session,
SequenceId sequence,
ElementId clip,
);
@$mustCallSuper
@override
WhenComplete runBuild() {
final ref = this.ref as $Ref<AsyncValue<void>, AsyncValue<void>>;
final element =
ref.element
as $ClassProviderElement<
AnyNotifier<AsyncValue<void>, AsyncValue<void>>,
AsyncValue<void>,
Object?,
Object?
>;
return element.handleCreate(
ref,
() => build(_$args.$1, _$args.$2, _$args.$3),
);
}
}
@@ -0,0 +1,770 @@
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,
),
),
),
),
],
),
);
},
),
),
],
),
),
],
);
}
}
@@ -0,0 +1,116 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/runtime/contracts.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_session.dart';
import 'canvas_presets.dart';
import 'project_settings_dialog.dart';
/// Project information uses the live editing session, including unsaved edits.
class ProjectProperties extends StatelessWidget {
const ProjectProperties({super.key, required this.session});
final EditorTimelineSession session;
@override
Widget build(BuildContext context) {
final sequence = session.activeSequenceId;
final timeline = sequence == null
? null
: session.persistence.timeline(sequence);
final duration = sequence == null
? 0
: session.sequenceDurationTicks(sequence);
final frame = timeline?.format.frameDuration;
final fps = frame == null ? null : frame.denominator / frame.numerator;
final canvas = session.canvas;
String number(double value) => value == value.roundToDouble()
? value.toStringAsFixed(0)
: value.toStringAsFixed(3).replaceFirst(RegExp(r'0+$'), '');
return WorkspacePanel(
paintBackground: false,
title: context.l10n.projectProperties,
trailing: TextButton(
key: const ValueKey('project-settings-edit'),
onPressed: () => showAppDialog<void>(
context: context,
builder: (_) => ProjectSettingsDialog(session: session),
),
child: Text(context.l10n.modify),
),
headerHeight: AppControlSize.panelToolbar,
headerPadding: const EdgeInsets.symmetric(
horizontal: AppSpacing.panelContentHorizontal,
),
showHeaderDivider: false,
child: ScrollEdgeFadeBuilder(
builder: (controller) => SingleChildScrollView(
controller: controller,
physics: const ClampingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_Info(context.l10n.timelineName, session.document.name),
_Info(
context.l10n.canvasSize,
'${number(canvas.width)} × ${number(canvas.height)} px',
),
_Info(context.l10n.canvasRatio, canvas.label(context)),
_Info(
context.l10n.projectColorSpace,
switch (session.projectColorSpace) {
RenderColorSpace.rec2020HLG => 'HDR · Rec.2020 HLG',
RenderColorSpace.rec2020PQ => 'HDR · Rec.2020 PQ',
_ => 'SDR · Rec.709',
},
),
_Info(
context.l10n.currentSequence,
timeline?.name ?? context.l10n.none,
),
_Info(
context.l10n.frameRate,
fps == null ? '—' : '${number(fps)} fps',
),
_Info(
context.l10n.totalDuration,
'${(duration / TimelineClock.ticksPerSecond).toStringAsFixed(2)} ${context.l10n.seconds}',
),
],
),
),
),
);
}
}
class _Info extends StatelessWidget {
const _Info(this.label, this.value);
final String label;
final String value;
@override
Widget build(BuildContext context) => Padding(
padding: AppSpacing.panelSection,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: AppSpacing.small,
children: [
Text(label, style: Theme.of(context).textTheme.bodySmall),
Expanded(
child: Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium,
),
),
],
),
);
}
@@ -0,0 +1,227 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:cutdex_sdk/editor.dart';
import 'package:cutdex_sdk/runtime/contracts.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cutdex_ui/widgets.dart';
import 'package:cutdex_ui/theme.dart';
import '../../workspace/timeline_session.dart';
class ProjectSettingsDialog extends StatefulWidget {
const ProjectSettingsDialog({super.key, required this.session});
final EditorTimelineSession session;
@override
State<ProjectSettingsDialog> createState() => _ProjectSettingsDialogState();
}
class _ProjectSettingsDialogState extends State<ProjectSettingsDialog> {
static final _rates = <String, RationalTime>{
'23.976': RationalTime(1001, 24000),
'24': RationalTime(1, 24),
'25': RationalTime(1, 25),
'29.97': RationalTime(1001, 30000),
'30': RationalTime(1, 30),
'50': RationalTime(1, 50),
'59.94': RationalTime(1001, 60000),
'60': RationalTime(1, 60),
'120': RationalTime(1, 120),
};
static const _sizes = <String, (int, int)>{
'1920 × 1080': (1920, 1080),
'3840 × 2160': (3840, 2160),
'1280 × 720': (1280, 720),
'1080 × 1920': (1080, 1920),
'1080 × 1080': (1080, 1080),
};
final _form = GlobalKey<FormState>();
late final TextEditingController _width;
late final TextEditingController _height;
late RationalTime _frame;
late RenderColorSpace _color;
String? _preset;
@override
void initState() {
super.initState();
final canvas = widget.session.canvas;
_width = TextEditingController(text: canvas.width.toStringAsFixed(0));
_height = TextEditingController(text: canvas.height.toStringAsFixed(0));
_frame = widget.session.activeSequenceId == null
? TimelineFormat.fps24.frameDuration
: widget.session.persistence
.timeline(widget.session.activeSequenceId!)
.format
.frameDuration;
_color = widget.session.projectColorSpace;
_preset = _sizes.entries
.where((e) => e.value.$1 == canvas.width && e.value.$2 == canvas.height)
.firstOrNull
?.key;
}
@override
void dispose() {
_width.dispose();
_height.dispose();
super.dispose();
}
void _save() {
if (!_form.currentState!.validate()) return;
widget.session.setProjectProperties(
sequence: widget.session.activeSequenceId,
canvas: ProjectCanvas(
double.parse(_width.text),
double.parse(_height.text),
),
frameDuration: _frame,
colorSpace: _color,
);
Navigator.of(context).pop();
}
Widget _dimension(
TextEditingController controller,
String label,
String key,
) => FormField<String>(
initialValue: controller.text,
validator: (_) {
final value = int.tryParse(controller.text);
return value == null || !ProjectCanvas.isValidDimension(value.toDouble())
? context.l10n.projectResolutionInvalid
: null;
},
builder: (field) => AppTextField(
key: ValueKey(key),
controller: controller,
label: label,
errorText: field.errorText,
keyboardType: TextInputType.number,
inputFormatters: [FilteringTextInputFormatter.digitsOnly],
onChanged: (value) {
field.didChange(value);
setState(() => _preset = null);
},
),
);
@override
Widget build(BuildContext context) {
final l10n = context.l10n;
final rates = {..._rates};
if (!rates.values.contains(_frame)) {
rates[(_frame.denominator / _frame.numerator).toStringAsFixed(3)] =
_frame;
}
return AppDialog(
title: l10n.projectSettings,
width: 440,
description: l10n.projectSettingsDescription,
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: Text(l10n.cancel),
),
FilledButton(
key: const ValueKey('project-settings-save'),
onPressed: _save,
child: Text(l10n.save),
),
],
child: SingleChildScrollView(
child: Form(
key: _form,
child: AppFieldGroup(
children: [
AppField(
label: l10n.canvasSize,
child: AppFieldGroup(
children: [
AppSelect<String>(
emptyLabel: context.l10n.noMatchingOptions,
key: const ValueKey('project-resolution'),
value: _preset ?? 'custom',
label: l10n.canvasSize,
options: [
for (final name in _sizes.keys)
AppSelectOption(name, name),
AppSelectOption('custom', l10n.custom),
],
onChanged: (value) => setState(() {
_preset = value == 'custom' ? null : value;
final size = _sizes[value];
if (size != null) {
_width.text = '${size.$1}';
_height.text = '${size.$2}';
}
}),
),
Row(
spacing: AppSpacing.compact,
children: [
Expanded(
child: _dimension(
_width,
l10n.projectWidth,
'project-width',
),
),
Expanded(
child: _dimension(
_height,
l10n.projectHeight,
'project-height',
),
),
],
),
],
),
),
AppField(
label: l10n.frameRate,
child: AppSelect<RationalTime>(
emptyLabel: context.l10n.noMatchingOptions,
key: const ValueKey('project-frame-rate'),
value: _frame,
label: l10n.frameRate,
options: [
for (final rate in rates.entries)
AppSelectOption(rate.value, '${rate.key} fps'),
],
onChanged: (value) => setState(() => _frame = value),
),
),
AppField(
label: l10n.projectColorSpace,
child: AppSelect<RenderColorSpace>(
emptyLabel: context.l10n.noMatchingOptions,
key: const ValueKey('project-color-space'),
value: _color,
label: l10n.projectColorSpace,
options: const [
AppSelectOption(RenderColorSpace.rec709, 'SDR · Rec.709'),
AppSelectOption(
RenderColorSpace.rec2020HLG,
'HDR · Rec.2020 HLG',
),
AppSelectOption(
RenderColorSpace.rec2020PQ,
'HDR · Rec.2020 PQ',
),
],
onChanged: (value) => setState(() => _color = value),
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,331 @@
import 'package:cutdex/l10n/l10n.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 'properties_inspector_controller.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/timeline_session.dart';
import 'audio_properties.dart';
import 'caption_properties.dart';
import 'color_interpretation_properties.dart';
import 'mask_properties.dart';
import 'picture_properties.dart';
import 'project_properties.dart';
import 'properties_presentation_state.dart';
import 'speed_properties.dart';
export 'properties_presentation_state.dart';
typedef PropertyCategoryControls = Widget Function(
BuildContext context,
List<PropertyCategory> categories,
PropertyCategory selected,
ValueChanged<PropertyCategory> onSelected,
);
class PropertiesContent extends ConsumerWidget {
const PropertiesContent({
super.key,
required this.projectId,
required this.timelineId,
required this.categoryControls,
required this.categoryHeaderHeight,
});
final String projectId;
final String timelineId;
final PropertyCategoryControls categoryControls;
final double categoryHeaderHeight;
@override
Widget build(BuildContext context, WidgetRef ref) {
final state = ref.watch(editorTimelineProvider(projectId, timelineId));
final content = state.when(
error: (_, _) => WorkspacePanel(
paintBackground: false,
child: _Message(context.l10n.loadClipPropertiesFailed),
),
data: (session) {
final inspector = ref.watch(
propertiesInspectorProvider((projectId, timelineId)),
);
if (inspector == null) return const SizedBox.shrink();
return ListenableBuilder(
listenable: inspector,
builder: (context, _) => _selection(context, inspector, ref),
);
},
loading: () => const WorkspacePanel(
key: Key('properties-pending'),
paintBackground: false,
child: SizedBox.expand(),
),
);
return Theme(
data: AppTheme.propertiesPanelTheme(Theme.of(context)),
child: content,
);
}
Widget _selection(
BuildContext context,
PropertiesInspectorController inspector,
WidgetRef ref,
) {
final session = inspector.session;
final sequence = inspector.sequence;
final clips = inspector.selectedClips;
if (sequence == null || clips.isEmpty) {
return ProjectProperties(session: session);
}
if (clips.length > 1) {
return WorkspacePanel(
paintBackground: false,
child: _Message(context.l10n.selectedClipsHint(clips.length)),
);
}
final clip = clips.single;
final payload = clip.payloadRef == null
? null
: session.payloadFor(clip.payloadRef!);
final binding = clip.payloadRef == null
? null
: session.mediaBinding(clip.payloadRef!);
final hasAudio = binding?.audioSelection != null;
if (payload?.type == 'caption' || payload?.type == 'caption-role') {
return CaptionProperties(
session: session,
sequence: sequence,
clipId: clip.id.value,
transformProperties: payload?.type == 'caption'
? PictureProperties(
key: ValueKey((sequence, clip.id, 'caption-transform')),
projectId: projectId,
timelineId: timelineId,
session: session,
sequence: sequence,
clip: clip,
)
: null,
);
}
return _ClipProperties(
key: ValueKey((sequence, clip.id)),
categoryControls: categoryControls,
categoryHeaderHeight: categoryHeaderHeight,
category: ref.watch(
propertyCategoryProvider((
projectId,
timelineId,
'${sequence.value}/${clip.id.value}',
)),
),
session: session,
sequence: sequence,
clip: clip,
mask: MaskProperties(
projectId: projectId,
timelineId: timelineId,
element: clip.id,
),
speed: SpeedProperties(
session: session,
sequence: sequence,
clip: clip.id,
),
audio: AudioProperties(
key: ValueKey((sequence, clip.id, 'audio')),
session: session,
sequence: sequence,
clip: clip,
hasAudio: hasAudio,
),
picture: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (payload?.type == 'video' && binding?.videoTrackIndex != null)
ColorInterpretationProperties(
projectId: projectId,
timelineId: timelineId,
session: session,
assetId: payload!.assetIds.single,
trackIndex: binding!.videoTrackIndex!,
),
PictureProperties(
key: ValueKey((sequence, clip.id)),
projectId: projectId,
timelineId: timelineId,
session: session,
sequence: sequence,
clip: clip,
),
],
),
animation: PictureProperties(
key: ValueKey((sequence, clip.id, 'animation')),
projectId: projectId,
timelineId: timelineId,
session: session,
sequence: sequence,
clip: clip,
animationView: true,
),
type: payload?.type,
hasAudio: hasAudio,
);
}
}
class _ClipProperties extends StatefulWidget {
const _ClipProperties({
super.key,
required this.session,
required this.sequence,
required this.clip,
required this.picture,
required this.mask,
required this.audio,
required this.speed,
required this.animation,
required this.type,
required this.hasAudio,
required this.categoryControls,
required this.categoryHeaderHeight,
required this.category,
});
final EditorTimelineSession session;
final SequenceId sequence;
final ElementRecord clip;
final Widget picture;
final Widget mask;
final Widget audio;
final Widget speed;
final Widget animation;
final String? type;
final bool hasAudio;
final PropertyCategoryControls categoryControls;
final double categoryHeaderHeight;
final ValueNotifier<PropertyCategory?> category;
@override
State<_ClipProperties> createState() => _ClipPropertiesState();
}
class _ClipPropertiesState extends State<_ClipProperties> {
PropertyCategory get _selected {
final categories = categoriesForClip(widget.clip, widget.type);
return categories.contains(widget.category.value)
? widget.category.value!
: categories.first;
}
void _selectCategory(PropertyCategory category) =>
widget.category.value = category;
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: widget.category,
builder: (context, _) => _buildProperties(context),
);
Widget _buildProperties(BuildContext context) {
final clip = widget.clip;
return WorkspacePanel(
paintBackground: false,
headerHeight: widget.categoryHeaderHeight,
headerPadding: EdgeInsets.zero,
showHeaderDivider: false,
controls: widget.categoryControls(
context,
categoriesForClip(clip, widget.type),
_selected,
_selectCategory,
),
child: ScrollEdgeFadeBuilder(
key: PageStorageKey((clip.id, _selected)),
builder: (controller) => SingleChildScrollView(
controller: controller,
// Inspector controls stop at their bounds; macOS's default elastic
// physics repeatedly displaces the content during edge scrolling.
physics: const ClampingScrollPhysics(),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
...switch (_selected) {
PropertyCategory.picture => [widget.picture],
PropertyCategory.mask => [widget.mask],
PropertyCategory.audio => [widget.audio],
PropertyCategory.speed => [widget.speed],
PropertyCategory.animation => [widget.animation],
PropertyCategory.basic => [
_Property(context.l10n.type, switch (clip.structure) {
ElementStructure.gap => context.l10n.gap,
ElementStructure.container => context.l10n.compoundClip,
ElementStructure.content =>
widget.type ?? context.l10n.unboundMedia,
}),
_Property(
context.l10n.status,
clip.enabled ? context.l10n.enable : context.l10n.disable,
),
],
},
],
),
),
),
);
}
}
class _Property extends StatelessWidget {
const _Property(this.label, this.value);
final String label;
final String value;
@override
Widget build(BuildContext context) => Padding(
padding: AppSpacing.panelSection,
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
spacing: AppSpacing.small,
children: [
Expanded(
child: Text(
label,
style: AppTheme.propertySectionTitleStyle(context),
),
),
Expanded(
child: Text(
value,
textAlign: TextAlign.right,
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
],
),
);
}
class _Message extends StatelessWidget {
const _Message(this.text);
final String text;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: AppSpacing.panelSection,
child: Text(
text,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodySmall,
),
),
);
}
@@ -0,0 +1,76 @@
import 'package:flutter/material.dart';
import 'properties_content.dart';
class PropertiesEditorPage extends StatelessWidget {
const PropertiesEditorPage({
super.key,
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context) => PropertiesContent(
key: const Key('properties-editor-page'),
projectId: projectId,
timelineId: timelineId,
categoryHeaderHeight: 48,
categoryControls: (context, categories, selected, onSelected) => Padding(
padding: const EdgeInsets.symmetric(horizontal: 16),
child: DropdownButton<PropertyCategory>(
key: const Key('property-category-picker'),
isExpanded: true,
underline: const SizedBox.shrink(),
value: selected,
items: [
for (final category in categories)
DropdownMenuItem(
value: category,
child: Text(category.label(context)),
),
],
onChanged: (category) {
if (category != null) onSelected(category);
},
),
),
);
}
class PropertiesToolPanel extends StatelessWidget {
const PropertiesToolPanel({
super.key,
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context) => PropertiesContent(
key: const Key('properties-tool-panel'),
projectId: projectId,
timelineId: timelineId,
categoryHeaderHeight: 48,
categoryControls: (context, categories, selected, onSelected) =>
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
for (final category in categories)
TextButton(
key: ValueKey('property-tab-${category.name}'),
style: TextButton.styleFrom(
minimumSize: const Size(64, 48),
foregroundColor: selected == category
? Theme.of(context).colorScheme.primary
: null,
),
onPressed: () => onSelected(category),
child: Text(category.label(context)),
),
],
),
),
);
}
@@ -0,0 +1,94 @@
import 'package:cutdex_sdk/timeline/engine.dart';
import 'package:cutdex_sdk/timeline/layout.dart';
import 'package:cutdex_sdk/timeline/model.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../workspace/timeline_provider.dart';
import '../../workspace/timeline_session.dart';
import 'properties_presentation_state.dart';
final propertiesInspectorProvider = Provider.autoDispose
.family<PropertiesInspectorController?, (String, String)>((ref, identity) {
final session = ref
.watch(editorTimelineProvider(identity.$1, identity.$2))
.value;
if (session == null) return null;
final controller = PropertiesInspectorController(session);
ref.onDispose(controller.dispose);
return controller;
});
/// Resolves the shared editing selection without prescribing a device layout.
class PropertiesInspectorController extends ChangeNotifier {
PropertiesInspectorController(this.session) {
session.addListener(_sessionChanged);
_bindView();
}
final EditorTimelineSession session;
Listenable? _editingChanges;
SequenceId? get sequence => session.activeSequenceId;
void _bindView() {
final id = sequence;
final next = id == null ? null : session.view(id).editingChanges;
if (identical(next, _editingChanges)) return;
_editingChanges?.removeListener(notifyListeners);
_editingChanges = next;
_editingChanges?.addListener(notifyListeners);
}
void _sessionChanged() {
_bindView();
notifyListeners();
}
List<ElementRecord> get selectedClips {
final id = sequence;
if (id == null) return const [];
final view = session.view(id);
final query = view.version.kernelVersion.query();
final handles = <ElementHandle>{};
for (final identity in view.selectedIdentities) {
final handle = switch (identity) {
ElementHandle handle => handle,
LayoutBodyId body => view.elementForIdentity(body),
_ => null,
};
if (handle != null && query.ownerOf(handle) != null) handles.add(handle);
}
final clips = [for (final handle in handles) query.element(handle)];
return clips.any((clip) => clip.structure != ElementStructure.gap)
? clips
: const [];
}
@override
void dispose() {
session.removeListener(_sessionChanged);
_editingChanges?.removeListener(notifyListeners);
super.dispose();
}
}
List<PropertyCategory> categoriesForClip(ElementRecord clip, String? type) {
if (clip.structure != ElementStructure.content) {
return [PropertyCategory.basic];
}
return switch (type) {
'video' => [
PropertyCategory.picture,
PropertyCategory.mask,
PropertyCategory.audio,
PropertyCategory.speed,
PropertyCategory.animation,
],
'audio' => [PropertyCategory.audio, PropertyCategory.speed],
'image' => [
PropertyCategory.picture,
PropertyCategory.mask,
PropertyCategory.animation,
],
_ => [PropertyCategory.basic],
};
}
@@ -0,0 +1,32 @@
import 'package:flutter/material.dart';
import 'package:cutdex_ui/widgets.dart';
import 'properties_content.dart';
export 'properties_presentation_state.dart';
/// Desktop inspector uses compact category tabs over shared property editors.
class EditorPropertiesPanel extends StatelessWidget {
const EditorPropertiesPanel({
super.key,
required this.projectId,
required this.timelineId,
});
final String projectId;
final String timelineId;
@override
Widget build(BuildContext context) => PropertiesContent(
projectId: projectId,
timelineId: timelineId,
categoryHeaderHeight: CompactPanelTabs.height,
categoryControls: (context, categories, selected, onSelected) =>
CompactPanelTabs<PropertyCategory>(
values: categories,
selected: selected,
labelBuilder: (category) => category.label(context),
tabKeyBuilder: (category) =>
ValueKey('property-tab-${category.name}'),
onSelected: onSelected,
),
);
}
@@ -0,0 +1,31 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../l10n/l10n.dart';
final propertyCategoryProvider =
Provider.family<ValueNotifier<PropertyCategory?>, (String, String, String)>(
(ref, identity) {
final category = ValueNotifier<PropertyCategory?>(null);
ref.onDispose(category.dispose);
return category;
},
);
enum PropertyCategory {
picture,
mask,
audio,
speed,
animation,
basic;
String label(BuildContext context) => switch (this) {
picture => context.l10n.pictureProperties,
mask => context.l10n.mask,
audio => context.l10n.audio,
speed => context.l10n.speedChange,
animation => context.l10n.animation,
basic => context.l10n.basic,
};
}
@@ -0,0 +1,152 @@
import 'package:cutdex/l10n/l10n.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:cutdex_ui/widgets.dart';
class PropertyNumberInput extends StatefulWidget {
const PropertyNumberInput({
super.key,
required this.label,
required this.value,
required this.enabled,
required this.readOnly,
required this.submit,
this.unit,
this.decimalPlaces = 2,
this.onScrubStart,
required this.onScrubUpdate,
required this.onScrubEnd,
required this.onScrubCancel,
required this.scrubbing,
required this.editContext,
}) : assert(decimalPlaces >= 0 && decimalPlaces <= 20);
final String? label;
final String? unit;
final int decimalPlaces;
final bool Function()? onScrubStart;
final ValueChanged<double> onScrubUpdate;
final VoidCallback onScrubEnd;
final VoidCallback onScrubCancel;
final bool scrubbing;
final Object editContext;
final double value;
final bool enabled;
final bool readOnly;
final Future<bool> Function(double) submit;
@override
State<PropertyNumberInput> createState() => _PropertyNumberInputState();
}
class _PropertyNumberInputState extends State<PropertyNumberInput> {
late final _text = TextEditingController(text: _format(widget.value));
final _focus = FocusNode();
bool _dirty = false;
String? _error;
String _format(double value) {
var text = value.toStringAsFixed(widget.decimalPlaces);
if (text.contains('.')) text = text.replaceFirst(RegExp(r'\.?0+$'), '');
return text == '-0' ? '0' : text;
}
@override
void initState() {
super.initState();
_focus.addListener(_blur);
}
void _blur() {
if (!_focus.hasFocus) _submit();
}
Future<void> _submit() async {
if (!_dirty || !widget.enabled || widget.readOnly) return;
final value = double.tryParse(_text.text);
if (value == null || !value.isFinite) {
setState(() => _error = context.l10n.invalidNumber);
return;
}
_dirty = false;
final accepted = await widget.submit(value);
if (!mounted) return;
setState(() {
_error = accepted ? null : context.l10n.notApplied;
_text.text = _format(widget.value);
});
}
@override
void didUpdateWidget(covariant PropertyNumberInput oldWidget) {
super.didUpdateWidget(oldWidget);
if ((oldWidget.enabled && !widget.enabled) ||
oldWidget.editContext != widget.editContext ||
(!oldWidget.readOnly && widget.readOnly)) {
_dirty = false;
_error = null;
}
final text = _format(widget.value);
// A no-op assignment still resets selection and asks EditableText to
// reveal its caret, competing with the user's scroll on preview updates.
if (!_dirty && _text.text != text) _text.text = text;
}
@override
void dispose() {
_focus.removeListener(_blur);
_focus.dispose();
_text.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) => Focus(
onKeyEvent: (_, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
setState(() {
_dirty = false;
_error = null;
_text.text = _format(widget.value);
});
_focus.unfocus();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: AppTextField(
controller: _text,
focusNode: _focus,
enabled: widget.enabled,
readOnly: widget.readOnly,
canRequestFocus: widget.enabled && !widget.readOnly,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
signed: true,
),
label: widget.label,
leading: widget.onScrubStart == null
? null
: AppScrubLabel(
label: widget.label!,
enabled: widget.enabled && (!widget.readOnly || widget.scrubbing),
onStart: () {
_dirty = false;
_error = null;
_text.text = _format(widget.value);
return widget.onScrubStart!();
},
onUpdate: widget.onScrubUpdate,
onEnd: widget.onScrubEnd,
onCancel: widget.onScrubCancel,
),
unit: widget.unit,
errorText: _error,
onChanged: (_) {
_dirty = true;
if (_error != null) setState(() => _error = null);
},
onEditingComplete: () {},
onSubmitted: (_) => _submit(),
),
);
}
@@ -0,0 +1,318 @@
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:flutter/material.dart';
import '../../l10n/l10n.dart';
import 'package:cutdex_ui/theme.dart';
import 'package:cutdex_ui/widgets.dart';
import '../../workspace/timeline_session.dart';
class SpeedProperties extends StatefulWidget {
const SpeedProperties({
super.key,
required this.session,
required this.sequence,
required this.clip,
});
final EditorTimelineSession session;
final SequenceId sequence;
final ElementId clip;
@override
State<SpeedProperties> createState() => _SpeedPropertiesState();
}
class _SpeedPropertiesState extends State<SpeedProperties> {
double? _timeline;
TimelineVersion? _version;
LayoutConnectionEditPreview? _preview;
double? _previewSpeed;
(Object, StackTrace)? _previewFailure;
double _speed(double position) =>
(math.pow(10, position * 3 - 1).toDouble() * 100).round() / 100;
void _updatePreview(double speed) {
final view = widget.session.view(widget.sequence);
_preview?.cancel();
_preview = null;
_previewSpeed = null;
_previewFailure = null;
try {
final preview = widget.session.previewClipSpeed(
widget.sequence,
widget.clip,
speed,
);
_preview = preview;
_previewSpeed = preview == null ? null : speed;
if (preview == null) {
view.clearLayoutPreview();
} else {
view.showLayoutPreview(preview.result.version);
}
} catch (error, stack) {
_previewFailure = (error, stack);
view.clearLayoutPreview();
_showError(error);
}
}
void _commit(double speed) {
final view = widget.session.view(widget.sequence);
if (widget.session.activeSequenceId == widget.sequence &&
(_version == null || identical(_version, view.version.kernelVersion))) {
try {
widget.session.runEdit(
'setSpeed',
widget.sequence,
() {
if (_previewSpeed != speed) _updatePreview(speed);
final preview = _preview;
final failure = _previewFailure;
_preview = null;
_previewSpeed = null;
_previewFailure = null;
if (preview == null) {
view.clearLayoutPreview();
if (failure != null) {
widget.session.reportEditFailure(failure.$1, failure.$2);
}
} else {
widget.session.commitClipSpeedPreview(widget.sequence, preview);
}
},
context: {
'clipIds': [widget.clip.value],
'entryPoint': 'property',
'playheadTick': view.playheadTick,
},
);
} catch (error) {
_preview?.cancel();
_preview = null;
_previewSpeed = null;
view.clearLayoutPreview();
_showError(error);
}
} else {
_discardPreview();
}
setState(() {
_timeline = null;
_version = null;
});
}
void _discardPreview() {
_preview?.cancel();
_preview = null;
_previewSpeed = null;
_previewFailure = null;
widget.session.view(widget.sequence).clearLayoutPreview();
}
void _showError(Object error) {
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(context.l10n.errorMessage(error))));
}
@override
void dispose() {
_discardPreview();
super.dispose();
}
@override
Widget build(BuildContext context) {
final view = widget.session.view(widget.sequence);
return ListenableBuilder(
listenable: Listenable.merge([view, widget.session]),
builder: (context, _) {
final query = view.version.kernelVersion.query();
final handle = query.elementById(widget.clip);
final record = handle == null ? null : query.element(handle);
final segments = record == null
? null
: widget.session.clipSpeedSegments(record);
final saved = segments?.length == 1 ? segments!.single.speed : null;
final enabled =
saved != null && widget.session.acceptsEdits && !view.isDragging;
final canReset =
segments != null && widget.session.acceptsEdits && !view.isDragging;
final localPlayhead = handle == null
? 0
: view.playheadTick - query.absoluteStart(handle);
final custom = widget.session.isCustomSpeedEnabled(
widget.sequence,
widget.clip,
);
final canSplit =
custom &&
segments != null &&
localPlayhead > 0 &&
localPlayhead < (record?.duration ?? 0) &&
!segments.any((segment) => segment.projectStart == localPlayhead) &&
widget.session.acceptsEdits &&
!view.isDragging;
final value =
_version == null || identical(_version, view.version.kernelVersion)
? _timeline ?? saved ?? 1
: saved ?? 1;
return Padding(
padding: AppSpacing.panelSection,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Row(
children: [
Expanded(
child: Text(
context.l10n.speed,
style: AppTheme.propertySectionTitleStyle(context),
),
),
Text(
saved == null && segments != null
? context.l10n.segmentedSpeed
: '${value.toStringAsFixed(2)}×',
key: const Key('clip-speed-value'),
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
const SizedBox(width: AppSpacing.small),
TextButton(
onPressed: canReset
? () {
_version = null;
_commit(1);
}
: null,
child: const Text('1×'),
),
],
),
if (saved != null) ...[
const SizedBox(height: AppSpacing.small),
AppSlider(
key: const Key('clip-speed-slider'),
value: ((math.log(value.clamp(0.1, 100)) / math.ln10 + 1) / 3)
.clamp(0, 1),
semanticFormatterCallback: (position) =>
'${_speed(position).toStringAsFixed(2)}×',
onChangeStart: enabled
? (_) {
_discardPreview();
_version = view.version.kernelVersion;
}
: null,
onChanged: enabled
? (position) {
if (_version != null &&
!identical(
_version,
view.version.kernelVersion,
)) {
_discardPreview();
setState(() => _timeline = null);
return;
}
final speed = _speed(position);
setState(() => _timeline = speed);
_updatePreview(speed);
}
: null,
onChangeEnd: enabled
? (position) => _commit(_speed(position))
: null,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('0.1×', style: Theme.of(context).textTheme.bodySmall),
Text('100×', style: Theme.of(context).textTheme.bodySmall),
],
),
] else if (segments != null)
Text(
context.l10n.speedSegmentCount(segments.length),
style: Theme.of(context).textTheme.bodySmall,
),
const SizedBox(height: AppSpacing.small),
Row(
children: [
Expanded(
child: Text(
context.l10n.custom,
style: AppTheme.propertySectionTitleStyle(context),
),
),
AppSwitch(
key: const Key('clip-custom-speed-toggle'),
value: custom,
semanticLabel: context.l10n.custom,
onChanged: canReset
? (value) {
_discardPreview();
setState(() {
_timeline = null;
_version = null;
});
widget.session.setCustomSpeedEnabled(
widget.sequence,
widget.clip,
value,
);
}
: null,
),
],
),
const SizedBox(height: AppSpacing.small),
SizedBox(
width: double.infinity,
height: AppControlSize.propertyControl,
child: OutlinedButton.icon(
key: const Key('split-speed-segment'),
onPressed: canSplit
? () {
try {
widget.session.splitClipSpeedAt(
widget.sequence,
widget.clip,
localPlayhead,
);
} catch (error) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(context.l10n.errorMessage(error)),
),
);
}
}
: null,
icon: const Icon(Icons.content_cut),
label: Text(context.l10n.splitSpeedAtPlayhead),
),
),
if (segments == null)
Text(
context.l10n.speedNotAvailable,
style: Theme.of(context).textTheme.bodySmall,
),
],
),
);
},
);
}
}