import '../../shared/widgets/listenable_selector.dart'; import '../../shared/widgets/presentation_list.dart'; import '../../shared/state/operation_scope.dart'; import 'dart:async'; import 'package:cutdex/l10n/l10n.dart'; import 'dart:math' as math; import 'package:cutdex/features/properties/animation_labels.dart'; import 'package:cutdex_core/editor.dart'; import 'package:cutdex_preview/cutdex_preview.dart'; import 'package:cutdex_core/timeline/model.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:cutdex_ui/icons.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 createState() => _MaskPropertiesState(); } class _MaskPropertiesState extends ConsumerState { Object get _editIdentity => (widget.projectId, widget.timelineId, widget.element, _preview); late final _operations = OperationScope(_editIdentity); PreviewController? _preview; Object? _boundContext; Object? _maskOwner; String? _error; int? _gestureGeneration; bool _hasFocusedControl = false; String? _scrubField; ClipMask Function(double)? _scrubChange; double _scrubValue = 0; Future? _pendingValueCommit; @override void dispose() { _operations.dispose(); final preview = _preview; final owner = _maskOwner; if (owner != null) { scheduleMicrotask(() => preview?.releaseMaskEditing(owner)); } 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 _submitValue( PreviewController preview, double value, double min, double max, ClipMask Function(double) change, ) { final operation = Future.sync( () => value.isFinite && value >= min && value <= max && _apply(preview, change(value)), ); _pendingValueCommit = operation; return operation.whenComplete(() { if (identical(_pendingValueCommit, operation)) _pendingValueCommit = null; }); } Future _editKeys(PreviewController preview, List ids) async { final isCurrent = _operations.capture(); 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 || !isCurrent() || 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 void didUpdateWidget(covariant MaskProperties oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.projectId != widget.projectId || oldWidget.timelineId != widget.timelineId || oldWidget.element != widget.element) { _scrubField = null; _scrubChange = null; _gestureGeneration = null; _pendingValueCommit = null; _error = null; } _operations.bind(_editIdentity); } @override Widget build(BuildContext context) { final preview = ref .watch(editorPreviewProvider(widget.projectId, widget.timelineId)) .value; if (preview == null) { final previous = _preview; final owner = _maskOwner; _preview = null; _boundContext = null; _maskOwner = null; _operations.bind(_editIdentity); if (previous != null && owner != null) { scheduleMicrotask(() => previous.releaseMaskEditing(owner)); } return const SizedBox.shrink(); } final identity = ( widget.projectId, widget.timelineId, widget.element, preview, ); if (_boundContext != identity) { final previous = _preview; final previousOwner = _maskOwner; if (previous != null && previousOwner != null) { scheduleMicrotask(() => previous.releaseMaskEditing(previousOwner)); } _preview = preview; _boundContext = identity; _operations.bind(_editIdentity); final isCurrent = _operations.capture(); final element = widget.element; final owner = _maskOwner = Object(); WidgetsBinding.instance.addPostFrameCallback((_) { if (mounted && isCurrent()) { preview.setMaskEditing(element, owner: owner); } }); } return Focus( onFocusChange: (focused) { if (mounted && focused != _hasFocusedControl) { setState(() => _hasFocusedControl = focused); } }, child: ListenableSelector( listenable: Listenable.merge([preview, preview.positionChanges]), select: () { final mask = preview.maskFor(widget.element); final animation = preview.maskAnimation(widget.element); final stack = preview.maskStackFor(widget.element); return ( stack?.record, _hasFocusedControl || _scrubField != null ? stack?.localTick : null, preview.selectedMaskId, preview.canPlay, preview.maskEditingElement, mask?.shape, mask?.x, mask?.y, mask?.width, mask?.height, mask?.rotation, mask?.feather, mask?.inverted, animation?.containsPlayhead, PresentationList( ClipMask.channels.map((ids) => animation?.keyed(ids)), ), PresentationList( (stack?.layers ?? []).map( (layer) => ( layer.id, layer.order, layer.enabled, layer.mode, layer.mask.shape, ), ), ), ); }, 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 ?? []; 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 ? AppIcons.squareFilled : AppIcons.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, bool inlineLabel = false, }) => PropertyNumberInput( key: ValueKey((selectedId, label)), label: label, inlineLabel: inlineLabel || AppTheme.isDesktop(context), prefix: AppTheme.isDesktop(context) && !inlineLabel ? '' : null, prefixIcon: AppTheme.isDesktop(context) && wrapRotation ? AppIcons.angle : null, unit: unit, value: value, enabled: enabled, readOnly: _scrubField != null, scrubbing: _scrubField == label, editContext: ( _editIdentity, selectedId, stack?.record, stack?.localTick, ), submit: (v) => _submitValue(preview, v, min, max, change), onScrubStart: () { if (_scrubField != null) return false; final preparing = preview.beginMaskEdit(); final isCurrent = _operations.capture(); final generation = _gestureGeneration = preview.maskEditGeneration; _scrubChange = change; _scrubValue = value; setState(() => _scrubField = label); unawaited( preparing .then((ready) { if (!ready && isCurrent() && generation == preview.maskEditGeneration) { preview.cancelMaskEdit(); if (mounted) setState(() => _scrubField = null); } }) .catchError((Object error) { if (isCurrent() && 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, { Widget? additional, }) => LayoutBuilder( builder: (context, constraints) { final desktop = AppTheme.isDesktop(context); final gap = AppTheme.propertyRowGap(context); if (desktop) { return AppPropertyGroup( label: label, padChild: false, child: Column( children: [ AppPropertyRow( trailing: key(label), children: [first, second], ), ?additional, ], ), ); } final pair = constraints.maxWidth < 240 ? Column( children: [ first, SizedBox(height: gap), second, ], ) : Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Expanded(child: first), SizedBox(width: gap), Expanded(child: second), ], ); return Row( children: [ Expanded(child: pair), SizedBox(width: gap), key(label), ], ); }, ); Widget singleField(String label, Widget input) => AppTheme.isDesktop(context) ? AppPropertyGroup( label: label, padChild: false, child: AppPropertyRow( trailing: key(label), children: [input], ), ) : Row( children: [ Expanded(child: input), SizedBox(width: AppTheme.propertyRowGap(context)), key(label), ], ); Widget heading(String label) => AppTheme.isDesktop(context) ? const SizedBox.shrink() : Padding( padding: EdgeInsets.only( bottom: AppTheme.propertyRowGap(context), ), child: Text( label, style: AppTheme.propertySectionTitleStyle(context), ), ); Widget section(List children) => AppPropertySection( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: children, ), ); Widget shapeSelector() => AppButtonGroup( expanded: true, label: context.l10n.mask, children: [ for (final entry in [ ( ClipMaskShape.rectangle, AppIcons.square, context.l10n.rectangle, ), (ClipMaskShape.ellipse, AppIcons.circle, 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), ), ], ); Widget shapeReset() => IconButton( tooltip: context.l10n.resetMask, onPressed: enabled ? () => _apply(preview, ClipMask(shape: mask!.shape)) : null, icon: const Icon(AppIcons.reset), ); 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(AppIcons.arrowUp, 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(AppIcons.arrowDown, 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(AppIcons.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 ? AppIcons.visible : AppIcons.hidden, 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 ? AppIcons.maskRegion : switch (layers[i].mode) { ClipMaskMode.add => AppIcons.add, ClipMaskMode.intersect => AppIcons.maskIntersect, ClipMaskMode.subtract => AppIcons.remove, }, size: AppIconSize.standard, ), onPressed: toggle, ), ), IconButton( tooltip: context.l10n.deleteMask, icon: const Icon(AppIcons.delete, 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([ if (AppTheme.isDesktop(context)) AppPropertyGroup( label: context.l10n.type, padChild: false, child: AppPropertyRow( trailing: shapeReset(), children: [shapeSelector()], ), ) else Row( children: [ Expanded(child: shapeSelector()), SizedBox(width: AppTheme.propertyRowGap(context)), shapeReset(), ], ), ]), 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: '%', inlineLabel: true, ), field( 'Y', mask.y * 100, ClipMask.minPosition * 100, ClipMask.maxPosition * 100, (v) => mask.copyWith(y: v / 100), unit: '%', inlineLabel: true, ), additional: AppTheme.isDesktop(context) ? AppPropertyRow( trailing: key(context.l10n.rotation), children: [ field( context.l10n.rotation, mask.rotation, -180, 180, (v) => mask.copyWith(rotation: v), unit: '°', wrapRotation: true, ), const SizedBox.shrink(), ], ) : null, ), ]), if (!AppTheme.isDesktop(context)) 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: '%', inlineLabel: true, ), field( 'H', mask.height * 100, ClipMask.minExtent * 100, ClipMask.maxExtent * 100, (v) => mask.copyWith(height: v / 100), unit: '%', inlineLabel: true, ), ), ]), 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, ), ), ]), ], ); }, ), ); } }