import 'dart:async'; import 'dart:math' as math; import 'package:cutdex_core/editor.dart'; import 'package:flutter/material.dart'; import 'package:flutter/gestures.dart'; import 'package:flutter/services.dart'; import 'preview_controller.dart'; import 'selection_decoration.dart'; import 'preview_geometry.dart'; class MaskInteractionOverlay extends StatefulWidget { const MaskInteractionOverlay({ super.key, required this.controller, required this.canvasRect, this.obscure = false, }); final PreviewController controller; final Rect canvasRect; final bool obscure; @override State createState() => _MaskInteractionOverlayState(); } class _MaskInteractionOverlayState extends State { final _focus = FocusNode(); late final _label = SelectionLabel( onChanged: () { if (mounted) setState(() {}); }, ); ClipMask? _base; _MaskGeometry? _geometry; Offset? _down; int _handle = -1; MouseCursor _cursor = SystemMouseCursors.basic; int? _generation; int get generation => widget.obscure ? widget.controller.obscureEditGeneration : widget.controller.maskEditGeneration; void cancel() => widget.obscure ? widget.controller.cancelObscureEdit() : widget.controller.cancelMaskEdit(); void _cancel() { if (_base == null) return; _base = null; if (_generation == generation) { cancel(); } } @override void dispose() { _label.dispose(); final controller = widget.controller; final generation = _generation; final obscure = widget.obscure; if (_base != null) { scheduleMicrotask(() { if (generation == (obscure ? controller.obscureEditGeneration : controller.maskEditGeneration)) { if (obscure) { controller.cancelObscureEdit(); } else { controller.cancelMaskEdit(); } } }); } _focus.dispose(); super.dispose(); } @override Widget build(BuildContext context) => ListenableBuilder( listenable: Listenable.merge([ widget.controller, widget.controller.positionChanges, ]), builder: (context, _) { final c = widget.controller; final id = widget.obscure ? c.obscureEditingElement : c.maskEditingElement; final mask = id == null ? null : (widget.obscure ? c.obscureFor(id) : c.maskFor(id)); final visual = id == null ? null : c.visualsForSelection({id}).firstOrNull; if (mask == null || visual == null) { return const SizedBox.shrink(); } final geometry = _MaskGeometry(visual, widget.canvasRect, c.canvas.width); final points = geometry.handles(mask).take(4).toList(); return Focus( focusNode: _focus, onFocusChange: (focused) { if (!focused) _cancel(); }, onKeyEvent: (_, event) { if (event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape && _base != null) { _cancel(); return KeyEventResult.handled; } return KeyEventResult.ignored; }, child: MouseRegion( cursor: _cursor, onHover: (event) { final cursor = selectionCursor(points, event.localPosition); if (cursor != _cursor) setState(() => _cursor = cursor); }, child: GestureDetector( dragStartBehavior: DragStartBehavior.down, key: widget.obscure ? const Key('obscure-interaction') : null, behavior: HitTestBehavior.translucent, onPanStart: c.canPlay ? (details) { final p = details.localPosition; _handle = selectionResizeCorner(points, p); if (_handle < 0 && !widget.obscure && selectionRotationCorner(points, p) >= 0) { _handle = 4; } if (_handle < 0 && !geometry.path(mask).contains(p)) return; _focus.requestFocus(); _base = mask; _geometry = geometry; _down = p; final preparing = widget.obscure ? c.beginObscureEdit() : c.beginMaskEdit(); final started = _generation = generation; unawaited( preparing .then((ready) { if (!ready && started == generation) _cancel(); return ready; }) .catchError((Object _) { if (started == _generation && started == generation) { _cancel(); } return false; }), ); } : null, onPanUpdate: (details) { final base = _base; final g = _geometry; if (base == null || g == null || _generation != generation) { return; } final p = g.local(details.localPosition); final start = g.local(_down!); ClipMask value; if (_handle == 4) { final a = math.atan2(p.dy - base.y, (p.dx - base.x) * g.aspect); final b = math.atan2( start.dy - base.y, (start.dx - base.x) * g.aspect, ); var angle = base.rotation + (a - b) * 180 / math.pi; if (HardwareKeyboard.instance.isShiftPressed) { angle = (angle / 15).round() * 15.0; } value = base.copyWith( rotation: normalizeRotationDegrees(angle), ); } else if (_handle >= 0) { final angle = base.rotation * math.pi / 180; final d = Offset((p.dx - base.x) * g.aspect, p.dy - base.y); final x = d.dx * math.cos(angle) + d.dy * math.sin(angle); final y = -d.dx * math.sin(angle) + d.dy * math.cos(angle); value = base.copyWith( width: (x.abs() * 2 / g.aspect).clamp( ClipMask.minExtent, widget.obscure ? ClipObscureAnimation.maxExtent : ClipMask.maxExtent, ), height: (y.abs() * 2).clamp( ClipMask.minExtent, widget.obscure ? ClipObscureAnimation.maxExtent : ClipMask.maxExtent, ), ); } else { value = base.copyWith( x: (base.x + p.dx - start.dx).clamp( ClipMask.minPosition, ClipMask.maxPosition, ), y: (base.y + p.dy - start.dy).clamp( ClipMask.minPosition, ClipMask.maxPosition, ), ); } if (widget.obscure) { c.updateObscure(value); } else { c.updateMask(value); } }, onPanEnd: (_) { if (_base != null) { _base = null; if (_generation == generation) { if (widget.obscure) { c.endObscureEdit(); } else { c.endMaskEdit(); } } } }, onPanCancel: _cancel, child: CustomPaint( painter: _MaskPainter( geometry, mask, MediaQuery.devicePixelRatioOf(context), _label, ), size: Size.infinite, ), ), ), ); }, ); } class _MaskGeometry { _MaskGeometry(PreviewVisual visual, Rect canvas, double canvasWidth) { final scale = canvas.width / canvasWidth; outputScale = scale; final corners = visual.geometry.corners; origin = canvas.topLeft + corners[0] * scale; xAxis = (corners[1] - corners[0]) * scale; yAxis = (corners[3] - corners[0]) * scale; aspect = (visual.geometry.size.width / visual.transform.scale) / (visual.geometry.size.height / visual.transform.scaleY); } late final Offset origin, xAxis, yAxis; late final double aspect, outputScale; Offset project(Offset p) => origin + xAxis * p.dx + yAxis * p.dy; Offset local(Offset p) { final d = p - origin; final det = xAxis.dx * yAxis.dy - xAxis.dy * yAxis.dx; if (det.abs() < 1e-9) return const Offset(.5, .5); return Offset( (d.dx * yAxis.dy - d.dy * yAxis.dx) / det, (xAxis.dx * d.dy - xAxis.dy * d.dx) / det, ); } Offset point(ClipMask mask, double x, double y) { final angle = mask.rotation * math.pi / 180; final dx = x * mask.width * aspect, dy = y * mask.height; return project( Offset( mask.x + (dx * math.cos(angle) - dy * math.sin(angle)) / aspect, mask.y + dx * math.sin(angle) + dy * math.cos(angle), ), ); } List handles(ClipMask mask) { return [ point(mask, -.5, -.5), point(mask, .5, -.5), point(mask, .5, .5), point(mask, -.5, .5), ]; } Path path(ClipMask mask) { final points = mask.shape == ClipMaskShape.ellipse ? [ for (var i = 0; i < 96; i++) point( mask, math.cos(i * math.pi / 48) / 2, math.sin(i * math.pi / 48) / 2, ), ] : handles(mask).take(4).toList(); return Path()..addPolygon(points, true); } } class _MaskPainter extends CustomPainter { _MaskPainter(this.geometry, this.mask, this.devicePixelRatio, this.label) : labelRevision = label.revision; final int labelRevision; final SelectionLabel label; final _MaskGeometry geometry; final ClipMask mask; final double devicePixelRatio; @override void paint(Canvas canvas, Size size) { final corners = geometry.handles(mask); if (mask.shape == ClipMaskShape.ellipse) { canvas.drawPath( geometry.path(mask), Paint() ..color = selectionBlue ..style = PaintingStyle.stroke ..strokeWidth = 1, ); } paintSelectionDecoration( canvas, corners, devicePixelRatio: devicePixelRatio, labelLayout: label, dimensions: Size( (corners[1] - corners[0]).distance / geometry.outputScale, (corners[3] - corners[0]).distance / geometry.outputScale, ), ); } @override bool shouldRepaint(covariant _MaskPainter oldDelegate) => labelRevision != oldDelegate.labelRevision || devicePixelRatio != oldDelegate.devicePixelRatio || geometry.origin != oldDelegate.geometry.origin || geometry.xAxis != oldDelegate.geometry.xAxis || geometry.yAxis != oldDelegate.geometry.yAxis || geometry.aspect != oldDelegate.geometry.aspect || geometry.outputScale != oldDelegate.geometry.outputScale || mask.shape != oldDelegate.mask.shape || mask.x != oldDelegate.mask.x || mask.y != oldDelegate.mask.y || mask.width != oldDelegate.mask.width || mask.height != oldDelegate.mask.height || mask.rotation != oldDelegate.mask.rotation; }