Files
cutdex/lib/features/properties/caption_properties.dart
T
lingjhf abc1868550
Gitea CI / Check code and tests (push) Successful in 6m37s
Gitea CI / Build Windows x64 app (push) Successful in 3m18s
Gitea CI / Build Android APK (push) Successful in 3m47s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m7s
Gitea CI / Assemble and validate CI artifacts (push) Successful in 50s
Gitea CI / Gitea CI passed (push) Successful in 2s
Gitea Release / Prepare draft Release (push) Successful in 9s
Gitea Release / Upload Android to draft Release (push) Successful in 16s
Gitea Release / Upload Windows to draft Release (push) Successful in 22s
Gitea Release / Verify and publish Release (push) Successful in 14s
feat(workspace): 桌面工作区、主题与交互更新,发布 0.1.2
2026-10-08 18:17:12 +00:00

934 lines
34 KiB
Dart

import '../../shared/widgets/listenable_selector.dart';
import '../../shared/widgets/presentation_list.dart';
import 'package:cutdex/shared/widgets/error_notification_host.dart';
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/icons.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) {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(
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();
final actionSize = AppTheme.isDesktop(context)
? AppInspectorMetrics.action
: 28.0;
return Column(
children: [
Padding(
padding: AppTheme.propertySectionPadding(context),
child: SizedBox(
height: AppTheme.propertyInputHeight(context),
child: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
child: TextField(
key: const ValueKey('caption-search'),
controller: _captionSearch,
style: AppTheme.inputTextStyle(context),
cursorHeight: AppTheme.inputCursorHeight(context),
textAlignVertical: TextAlignVertical.center,
textInputAction: TextInputAction.search,
decoration: InputDecoration(
hintText: context.l10n.searchOptions(
context.l10n.captions,
),
isDense: true,
constraints: BoxConstraints.tightFor(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.input
: 28,
),
contentPadding: const EdgeInsets.symmetric(
horizontal: 8,
vertical: 0,
),
prefixIcon: const Icon(AppIcons.search, size: 14),
prefixIconConstraints: const BoxConstraints(
minWidth: 28,
minHeight: 28,
),
),
onChanged: (value) => setState(
() => _captionQuery = value.trim().toLowerCase(),
),
),
),
const SizedBox(width: 4),
Align(
child: 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(AppIcons.textWrap, size: 16),
padding: EdgeInsets.zero,
style: IconButton.styleFrom(
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
visualDensity: VisualDensity.standard,
),
constraints: BoxConstraints.tightFor(
width: actionSize,
height: actionSize,
),
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: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context)
? AppInspectorMetrics.padding
: 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: actionSize,
height: actionSize,
child: IconButton(
key: ValueKey(
'caption-action-${cue.id}',
),
tooltip: context.l10n.select,
padding: EdgeInsets.zero,
constraints: BoxConstraints.tightFor(
width: actionSize,
height: actionSize,
),
icon: const Icon(
AppIcons.chevronRight,
size: 14,
),
onPressed: () => _selectCue(cue.id),
),
),
],
),
),
),
),
),
),
],
),
),
),
],
);
}
@override
Widget build(BuildContext context) => ListenableSelector<Object>(
listenable: widget.session,
select: () {
final query = widget.session.persistence
.timeline(widget.sequence)
.current
.query();
final handle = query.elementById(ElementId(widget.clipId));
if (handle == null) return (null, widget.session.acceptsEdits);
final clip = query.element(handle);
final role = clip.containerStoryline != null
? handle
: widget.session.captionRole(widget.sequence);
final child = role == null
? null
: query.element(role).containerStoryline;
return (
clip,
clip.payloadRef == null
? null
: widget.session.payloadFor(clip.payloadRef!),
query.localContext(handle).start,
widget.session.acceptsEdits,
widget.session.version,
PresentationList([
if (child != null)
for (final cue in query.storylineElements(child))
(
query.element(cue),
query.element(cue).payloadRef == null
? null
: widget.session.payloadFor(query.element(cue).payloadRef!),
),
]),
);
},
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: AppTheme.isDesktop(context)
? AppDesktopMetrics.panelHeader
: 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 editContext = (
widget.session,
widget.sequence,
widget.clipId,
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,
bool inlineLabel = false,
String? prefix,
required SetCaption Function(double, String) command,
}) => PropertyNumberInput(
key: ValueKey('caption-$field'),
label: label,
inlineLabel: inlineLabel,
prefix: prefix,
unit: unit,
decimalPlaces: decimalPlaces,
value: shown(field, value),
enabled: true,
readOnly: _scrubField != null,
scrubbing: _scrubField == field,
editContext: editContext,
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,
);
final baselineInput = number(
field: 'positionY',
inlineLabel: AppTheme.isDesktop(context),
prefix: AppTheme.isDesktop(context) ? 'Y' : null,
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,
),
);
final contentInput = _CaptionTextInput(
key: ValueKey(('caption-text', widget.clipId)),
editContext: editContext,
value: caption.text,
maxLines: 3,
onSubmit: (text) => _save(
SetCaption(
captionId: widget.clipId,
text: text,
expectedVersion: version,
),
),
);
final deleteAction = IconButton(
tooltip: context.l10n.deleteCaption,
icon: const Icon(AppIcons.delete),
onPressed: () {
try {
widget.session.commands.applyEdit(
widget.sequence,
DeleteClip(widget.clipId, expectedVersion: version),
);
} on CommandRejected {
ErrorNotificationHost.maybeOf(context)?.show(
ErrorNotification(content: Text(context.l10n.captionChanged)),
);
}
},
);
return panel(
ScrollEdgeFadeBuilder(
key: const ValueKey('caption-detail-scroll-fade'),
builder: (controller) => ListView(
controller: controller,
padding: const EdgeInsets.symmetric(vertical: AppSpacing.small),
children:
[
if (AppTheme.isDesktop(context))
AppPropertyGroup(
label: context.l10n.content,
actions: [deleteAction],
child: contentInput,
)
else ...[
Row(
children: [
Expanded(
child: Text(
context.l10n.textClip,
style: AppTheme.propertySectionTitleStyle(
context,
),
),
),
deleteAction,
],
),
SizedBox(height: AppTheme.propertyRowGap(context)),
Text(
context.l10n.content,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
contentInput,
],
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: 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,
),
),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
_CaptionColorInput(
key: ValueKey(('caption-color', widget.clipId)),
editContext: editContext,
value: caption.color,
label: context.l10n.color,
onSubmit: (color) => _save(
SetCaption(
captionId: widget.clipId,
color: color,
expectedVersion: version,
),
),
),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.small,
),
_CaptionColorInput(
key: ValueKey(('caption-strokeColor', widget.clipId)),
editContext: editContext,
value: caption.strokeColor,
label: context.l10n.outlineColor,
onSubmit: (color) => _save(
SetCaption(
captionId: widget.clipId,
strokeColor: color,
expectedVersion: version,
),
),
),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: 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?) ...[
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
const Divider(height: 1),
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
if (!AppTheme.isDesktop(context)) ...[
Text(
context.l10n.transform,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
],
transform,
],
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
if (AppTheme.isDesktop(context))
AppPropertyGroup(
label: context.l10n.captionBaseline,
child: baselineInput,
)
else ...[
Text(
context.l10n.captionBaseline,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
baselineInput,
],
SizedBox(
height: AppTheme.isDesktop(context)
? AppInspectorMetrics.groupGap
: AppSpacing.medium,
),
if (!AppTheme.isDesktop(context)) ...[
Text(
context.l10n.time,
style: AppTheme.propertySectionTitleStyle(context),
),
SizedBox(height: AppTheme.propertyRowGap(context)),
],
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 <
(AppTheme.isDesktop(context) ? 180 : 240)) {
return Column(
children: [
startField(),
SizedBox(
height: AppTheme.propertyRowGap(context),
),
durationField(),
],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: startField()),
SizedBox(width: AppTheme.propertyRowGap(context)),
Expanded(child: durationField()),
],
);
},
),
]
.map(
(item) =>
item is SizedBox ||
identical(item, widget.transformProperties)
? item
: Padding(
padding: EdgeInsets.symmetric(
horizontal: AppTheme.isDesktop(context)
? AppInspectorMetrics.padding
: AppSpacing.panelContentHorizontal,
),
child: item,
),
)
.toList(),
),
),
);
},
);
}
class _CaptionTextInput extends StatefulWidget {
const _CaptionTextInput({
super.key,
required this.value,
required this.editContext,
required this.onSubmit,
this.label,
this.maxLines = 1,
});
final String value;
final Object editContext;
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);
// A new callback carries the new authored version. Never let a draft from
// the previous binding borrow that version and overwrite a newer edit.
if (oldWidget.editContext != widget.editContext) {
_dirty = false;
_error = null;
}
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.editContext,
required this.label,
required this.onSubmit,
});
final String value;
final Object editContext;
final String label;
final bool Function(String) onSubmit;
@override
Widget build(BuildContext context) {
final desktop = AppTheme.isDesktop(context);
final controls = 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,
editContext: editContext,
label: desktop ? null : label,
onSubmit: onSubmit,
),
),
],
);
return desktop
? AppPropertyGroup(
label: label,
child: Semantics(label: label, child: controls),
)
: controls;
}
}