Move editor UI into the app and release verified Core dependencies (#14)
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m47s
Gitea CI / Check code and tests (push) Successful in 7m15s
Gitea CI / Build Android APK (push) Successful in 4m6s
Gitea CI / Build Windows x64 app (push) Successful in 3m34s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m29s
Gitea CI / Gitea CI passed (push) Successful in 1s
Gitea Release / Prepare draft Release (push) Failing after 8s
Gitea Release / Upload Android to draft Release (push) Skipped
Gitea Release / Upload Windows to draft Release (push) Skipped
Gitea Release / Verify and publish Release (push) Skipped
This commit was merged in pull request #14.
This commit is contained in:
1 parent
abc1868550
commit
06f1c26681
452 files changed
+43806
-2329
No files matched your search
@@ -0,0 +1,41 @@
|
||||
# cutdex_preview
|
||||
|
||||
Application-owned Flutter preview controllers, canvas and transform/mask interactions. Core provides editing and execution semantics; this package binds the native session to Flutter and owns preview lifecycle. The package has no App, Riverpod, workspace, platform-grant or localization dependency.
|
||||
|
||||
- `PreviewController` accepts an `EditorSession`, the active-sequence getter and the host's existing `TimelineViewController` resolver. When selection changes, the host notifies the editor session.
|
||||
- It owns one runtime session and attaches that same target to editor-owned execution coordination. Playback and seek go directly to runtime. Authored transforms and masks commit through editor; timelines remain local.
|
||||
- `SourcePreviewController` uses runtime directly. `PreviewMediaLoader` binds the source outside the package and retains its access until the callback finishes, including native session cleanup. No editor is needed for source playback.
|
||||
- `PreviewCanvas`, `PreviewInteractionOverlay` and `MaskInteractionOverlay` provide reusable presentation. The App supplies padding, background, error feedback and toolbars. `PreviewPolicy` supplies viewing assumptions; project settings override timeline defaults.
|
||||
- `PreviewPolicy.skimmingMode` uses runtime's `SkimmingMode` directly: `audible` by default, or `silent`. Both preview controllers pass this policy to the runtime without Boolean adapters.
|
||||
- Errors remain original objects. Unavailable assets carry runtime error codes; `unavailableAtPlayhead` returns clip names for the host to format.
|
||||
|
||||
```dart
|
||||
final preview = PreviewController(
|
||||
timeline: editor,
|
||||
runtime: runtime,
|
||||
activeSequence: () => selectedSequence,
|
||||
viewForSequence: timelineViewFor,
|
||||
);
|
||||
await preview.initialize();
|
||||
// Mount RuntimePreview(session: preview.session!) inside PreviewCanvas.
|
||||
// Detach widgets before closing and keep host timeline views alive until close.
|
||||
await preview.close(); // releases preview; does not close editor
|
||||
```
|
||||
|
||||
Concurrent `initialize` calls share one startup; initialization after close is rejected. Public runtime and playback state is read-only. The host reports preparation failures through `reportFailure`, without assigning controller fields. `PreviewController.close` releases its notifier too; after `SourcePreviewController.close`, dispose its notifier. Closing waits for pending startup, playback and native cleanup, even when a host callback or cleanup action fails; it reports the first failure after releasing other resources. Clearing the active sequence detaches the old view, cancels seek and pauses output. The host must close preview before releasing the project's media grants.
|
||||
|
||||
Run `flutter test packages/cutdex_preview/test` from the application workspace. App tests retain inspector/MCP/preview integration coverage.
|
||||
|
||||
PreviewController implements EditorPreviewService and registers a non-owning port on EditorSession during initialization, unregistering before close. Tools query or control this existing timeline preview by explicit sequence ID. Controls reject inactive sequences, preserve authored history and reuse native synchronization. Explicit pause is sent even before the native playing event arrives. Source preview remains independent.
|
||||
|
||||
EditorAlignmentService resolves canvas alignment at explicit sequence time using the synchronized execution geometry. It rejects stale, missing or ambiguous geometry and active timelines; the editor owns the final version check and authored commit. CanvasAlignment is defined by editor and re-exported by preview.
|
||||
|
||||
SourcePreviewController.control provides explicit play, pause and exact seek, serialized with UI playback and drained on close. The App PreviewTarget owns the selected controller and source navigation; both tools and the panel reuse it. Explicit pause reaches native playback even before a playing event arrives.
|
||||
|
||||
Editor selection decorations are painted by Flutter over native video output. Material and mask selections share blue bounds, white corner squares and an output-pixel dimension label. Drag a corner square to resize; drag just outside any corner to rotate, with Shift snapping to 15 degrees. Transform bounds follow acknowledged native renders. Selection and style changes do not acquire a paused native frame or submit native decorations.
|
||||
|
||||
Selection strokes use an integer physical-pixel width based on display density. Axis-aligned bounds and corner squares align their stroke boundaries to physical pixels. Rotated outlines use vertex opacity ramps across a physical-pixel fringe, preserving subpixel geometry while smoothing shallow diagonals. These adjustments affect painting only.
|
||||
|
||||
Move and resize snapping uses 1% of the displayed canvas's shorter side, capped at six logical pixels. Release distance is 5/3 of the entry distance. Both distances are converted to output pixels before evaluating geometry.
|
||||
|
||||
Canvas and property rotation drags share `normalizeRotationDegrees`, wrapping to [-180, 180) from the fixed gesture baseline so crossing the boundary or reversing direction remains continuous.
|
||||
@@ -0,0 +1,11 @@
|
||||
analyzer:
|
||||
exclude:
|
||||
- build/**
|
||||
include: package:flutter_lints/flutter.yaml
|
||||
|
||||
linter:
|
||||
rules:
|
||||
unnecessary_lambdas: true
|
||||
unnecessary_parenthesis: true
|
||||
unnecessary_statements: true
|
||||
prefer_const_constructors: true
|
||||
@@ -0,0 +1,11 @@
|
||||
/// Flutter preview resources and interactions for Cutdex.
|
||||
library;
|
||||
|
||||
export 'src/preview_controller.dart';
|
||||
export 'src/source_preview_controller.dart';
|
||||
export 'src/preview_transform_session.dart';
|
||||
export 'src/preview_geometry.dart';
|
||||
export 'src/preview_canvas.dart';
|
||||
export 'src/preview_interaction_overlay.dart';
|
||||
export 'src/mask_interaction_overlay.dart';
|
||||
export 'src/preview_policy.dart';
|
||||
@@ -0,0 +1,16 @@
|
||||
import 'dart:async';
|
||||
|
||||
/// Release every owned resource, then report the first cleanup failure.
|
||||
Future<void> completeCleanup(List<FutureOr<void> Function()> actions) async {
|
||||
Object? failure;
|
||||
StackTrace? trace;
|
||||
for (final action in actions) {
|
||||
try {
|
||||
await action();
|
||||
} catch (error, stack) {
|
||||
failure ??= error;
|
||||
trace ??= stack;
|
||||
}
|
||||
}
|
||||
if (failure != null) Error.throwWithStackTrace(failure, trace!);
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
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<MaskInteractionOverlay> createState() => _MaskInteractionOverlayState();
|
||||
}
|
||||
|
||||
class _MaskInteractionOverlayState extends State<MaskInteractionOverlay> {
|
||||
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<Offset> 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;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Fits the output canvas within the workspace; native rendering fits media
|
||||
/// within this canvas using its own source geometry (including rotation).
|
||||
class PreviewCanvas extends StatelessWidget {
|
||||
const PreviewCanvas({
|
||||
super.key,
|
||||
required this.aspectRatio,
|
||||
required this.child,
|
||||
this.overlayBuilder,
|
||||
this.horizontalPadding = 16,
|
||||
this.alignment = Alignment.topCenter,
|
||||
this.backgroundColor = Colors.black,
|
||||
});
|
||||
|
||||
final double aspectRatio;
|
||||
final double horizontalPadding;
|
||||
final Alignment alignment;
|
||||
final Color backgroundColor;
|
||||
final Widget child;
|
||||
final Widget Function(Rect canvasRect)? overlayBuilder;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => RepaintBoundary(
|
||||
child: ColoredBox(
|
||||
key: const Key('preview-surface'),
|
||||
color: Theme.of(context).colorScheme.surface,
|
||||
child: LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final available = Size(
|
||||
(constraints.maxWidth - horizontalPadding * 2).clamp(
|
||||
0,
|
||||
double.infinity,
|
||||
),
|
||||
constraints.maxHeight,
|
||||
);
|
||||
final fitted = applyBoxFit(
|
||||
BoxFit.contain,
|
||||
Size(aspectRatio, 1),
|
||||
available,
|
||||
).destination;
|
||||
final rect = alignment.inscribe(
|
||||
fitted,
|
||||
Offset.zero & constraints.biggest,
|
||||
);
|
||||
return Stack(
|
||||
fit: StackFit.expand,
|
||||
clipBehavior: Clip.hardEdge,
|
||||
children: [
|
||||
Positioned.fromRect(
|
||||
rect: rect,
|
||||
child: ColoredBox(
|
||||
key: const Key('preview-canvas'),
|
||||
color: backgroundColor,
|
||||
child: ClipRect(child: child),
|
||||
),
|
||||
),
|
||||
if (overlayBuilder != null && rect.width > 0 && rect.height > 0)
|
||||
Positioned.fill(child: overlayBuilder!(rect)),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
part of 'preview_controller.dart';
|
||||
|
||||
enum PreviewCanvasEditMode { mask, obscure, distortion }
|
||||
|
||||
/// A single canvas tool owns a clip until release, explicit selection change or removal.
|
||||
@immutable
|
||||
class PreviewCanvasEditing {
|
||||
const PreviewCanvasEditing({
|
||||
required this.mode,
|
||||
required this.element,
|
||||
this.owner,
|
||||
this.perspective = false,
|
||||
});
|
||||
|
||||
final PreviewCanvasEditMode mode;
|
||||
final ElementId element;
|
||||
final Object? owner;
|
||||
final bool perspective;
|
||||
}
|
||||
|
||||
extension on PreviewController {
|
||||
ElementId? _editingElement(PreviewCanvasEditMode mode) =>
|
||||
_canvasEditing?.mode == mode ? _canvasEditing?.element : null;
|
||||
|
||||
void _setCanvasEditing(
|
||||
PreviewCanvasEditMode mode,
|
||||
ElementId? element, {
|
||||
Object? owner,
|
||||
bool perspective = false,
|
||||
}) {
|
||||
if (_closed) return;
|
||||
final current = _canvasEditing;
|
||||
if (element == null) {
|
||||
if (current?.mode != mode) return;
|
||||
} else if (current?.mode == mode &&
|
||||
current?.element == element &&
|
||||
identical(current?.owner, owner) &&
|
||||
current?.perspective == perspective) {
|
||||
return;
|
||||
}
|
||||
// Invalidate preparation and discard pending gestures before changing tools.
|
||||
cancelTransform();
|
||||
_selectedMaskId = null;
|
||||
_canvasEditing = element == null
|
||||
? null
|
||||
: PreviewCanvasEditing(
|
||||
mode: mode,
|
||||
element: element,
|
||||
owner: owner,
|
||||
perspective: perspective,
|
||||
);
|
||||
if (element != null) selectVisual(element);
|
||||
_notify();
|
||||
}
|
||||
|
||||
void _releaseCanvasEditing(PreviewCanvasEditMode mode, Object owner) {
|
||||
if (_canvasEditing?.mode == mode &&
|
||||
identical(_canvasEditing?.owner, owner)) {
|
||||
_setCanvasEditing(mode, null);
|
||||
}
|
||||
}
|
||||
|
||||
void _clearCanvasEditing() {
|
||||
_canvasEditing = null;
|
||||
_selectedMaskId = null;
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,460 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
|
||||
export 'package:cutdex_core/editor/commands.dart' show CanvasAlignment;
|
||||
|
||||
/// Canonical angle for interactive rotation, in the range [-180, 180).
|
||||
double normalizeRotationDegrees(double degrees) => (degrees + 180) % 360 - 180;
|
||||
|
||||
ClipTransform alignToCanvas(
|
||||
PreviewVisual visual,
|
||||
Size canvas,
|
||||
CanvasAlignment alignment,
|
||||
) {
|
||||
final bounds = visual.geometry.bounds;
|
||||
final delta = switch (alignment) {
|
||||
CanvasAlignment.left => Offset(-bounds.left, 0),
|
||||
CanvasAlignment.horizontalCenter => Offset(
|
||||
canvas.width / 2 - bounds.center.dx,
|
||||
0,
|
||||
),
|
||||
CanvasAlignment.right => Offset(canvas.width - bounds.right, 0),
|
||||
CanvasAlignment.top => Offset(0, -bounds.top),
|
||||
CanvasAlignment.verticalCenter => Offset(
|
||||
0,
|
||||
canvas.height / 2 - bounds.center.dy,
|
||||
),
|
||||
CanvasAlignment.bottom => Offset(0, canvas.height - bounds.bottom),
|
||||
};
|
||||
final local = visual.geometry.localDelta(delta);
|
||||
return visual.transform.copyWith(
|
||||
x: visual.transform.x + local.dx / canvas.width,
|
||||
y: visual.transform.y + local.dy / canvas.height,
|
||||
);
|
||||
}
|
||||
|
||||
/// Geometry in output pixels, independent of widget size and device pixel ratio.
|
||||
class PreviewGeometry {
|
||||
const PreviewGeometry({
|
||||
required this.center,
|
||||
required this.size,
|
||||
this.rotation = 0,
|
||||
this.distortion = const ClipDistortion(),
|
||||
}) : _execution = null;
|
||||
|
||||
factory PreviewGeometry.fromExecution(ExecutionVisualGeometry geometry) {
|
||||
final points = geometry.corners;
|
||||
final x = points[1] - points[0];
|
||||
final y = points[3] - points[0];
|
||||
return PreviewGeometry._(
|
||||
Offset((points[0].x + points[2].x) / 2, (points[0].y + points[2].y) / 2),
|
||||
Size(x.magnitude, y.magnitude),
|
||||
math.atan2(x.y, x.x) * 180 / math.pi,
|
||||
geometry,
|
||||
);
|
||||
}
|
||||
|
||||
const PreviewGeometry._(
|
||||
this.center,
|
||||
this.size,
|
||||
this.rotation,
|
||||
this._execution,
|
||||
) : distortion = const ClipDistortion();
|
||||
final ExecutionVisualGeometry? _execution;
|
||||
final Offset center;
|
||||
final Size size;
|
||||
final double rotation;
|
||||
final ClipDistortion distortion;
|
||||
Offset rotate(Offset p) {
|
||||
final a = rotation * math.pi / 180;
|
||||
return Offset(
|
||||
p.dx * math.cos(a) - p.dy * math.sin(a),
|
||||
p.dx * math.sin(a) + p.dy * math.cos(a),
|
||||
);
|
||||
}
|
||||
|
||||
List<Offset> get corners => _execution != null
|
||||
? [for (final p in _execution.corners) Offset(p.x, p.y)]
|
||||
: [
|
||||
for (var i = 0; i < 4; i++)
|
||||
center +
|
||||
rotate(
|
||||
Offset(
|
||||
(i == 0 || i == 3 ? -.5 : .5) * size.width +
|
||||
distortion.values[i * 2] * size.width,
|
||||
(i < 2 ? -.5 : .5) * size.height +
|
||||
distortion.values[i * 2 + 1] * size.height,
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
Rect get bounds {
|
||||
final points = corners;
|
||||
return Rect.fromLTRB(
|
||||
points.map((p) => p.dx).reduce(math.min),
|
||||
points.map((p) => p.dy).reduce(math.min),
|
||||
points.map((p) => p.dx).reduce(math.max),
|
||||
points.map((p) => p.dy).reduce(math.max),
|
||||
);
|
||||
}
|
||||
|
||||
/// Handles follow the video's local corners through rotation.
|
||||
List<Offset> get selectionCorners => corners;
|
||||
|
||||
Size get distortionSize {
|
||||
final s = _execution?.distortionSize;
|
||||
return s == null ? size : Size(s.x, s.y);
|
||||
}
|
||||
|
||||
Offset distortionDelta(Offset delta) {
|
||||
final p = _execution?.distortionDelta(ExecutionPoint(delta.dx, delta.dy));
|
||||
if (p != null) return Offset(p.x, p.y);
|
||||
final a = -rotation * math.pi / 180;
|
||||
return Offset(
|
||||
(delta.dx * math.cos(a) - delta.dy * math.sin(a)) / size.width,
|
||||
(delta.dx * math.sin(a) + delta.dy * math.cos(a)) / size.height,
|
||||
);
|
||||
}
|
||||
|
||||
bool contains(Offset p) {
|
||||
final points = corners;
|
||||
final first = points[1] - points[0], second = points[2] - points[1];
|
||||
final sign = (first.dx * second.dy - first.dy * second.dx).sign;
|
||||
if (sign == 0) return false;
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final edge = points[(i + 1) % 4] - points[i], d = p - points[i];
|
||||
if (sign * (edge.dx * d.dy - edge.dy * d.dx) < -1e-9) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Offset localDelta(Offset delta) {
|
||||
final mapped = _execution?.localDelta(ExecutionPoint(delta.dx, delta.dy));
|
||||
return mapped == null ? delta : Offset(mapped.x, mapped.y);
|
||||
}
|
||||
|
||||
PreviewGeometry changed(ClipTransform from, ClipTransform to, Size canvas) {
|
||||
final execution = _execution;
|
||||
if (execution != null) {
|
||||
return PreviewGeometry.fromExecution(
|
||||
execution.changed(
|
||||
distortion: to.distortion,
|
||||
x: to.x - from.x,
|
||||
y: to.y - from.y,
|
||||
scaleX: to.scale / from.scale,
|
||||
scaleY: to.scaleY / from.scaleY,
|
||||
rotation: to.rotation - from.rotation,
|
||||
),
|
||||
);
|
||||
}
|
||||
return PreviewGeometry(
|
||||
center:
|
||||
center +
|
||||
Offset(
|
||||
(to.x - from.x) * canvas.width,
|
||||
(to.y - from.y) * canvas.height,
|
||||
),
|
||||
size: Size(
|
||||
size.width * to.scale / from.scale,
|
||||
size.height * to.scaleY / from.scaleY,
|
||||
),
|
||||
distortion: to.distortion,
|
||||
rotation: rotation + to.rotation - from.rotation,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PreviewVisual {
|
||||
const PreviewVisual({
|
||||
required this.layerId,
|
||||
required this.elementId,
|
||||
required this.geometry,
|
||||
required this.transform,
|
||||
required this.lane,
|
||||
});
|
||||
final String layerId;
|
||||
final ElementId elementId;
|
||||
final PreviewGeometry geometry;
|
||||
final ClipTransform transform;
|
||||
final int lane;
|
||||
}
|
||||
|
||||
class CanvasSnap {
|
||||
const CanvasSnap._(
|
||||
this.delta,
|
||||
this.verticalGuides,
|
||||
this.horizontalGuides,
|
||||
this._x,
|
||||
this._y,
|
||||
this._canvas,
|
||||
);
|
||||
final Offset delta;
|
||||
final List<double> verticalGuides;
|
||||
final List<double> horizontalGuides;
|
||||
final _SnapMatch? _x;
|
||||
final _SnapMatch? _y;
|
||||
final Size _canvas;
|
||||
|
||||
factory CanvasSnap.guides(PreviewGeometry geometry, Size canvas) {
|
||||
final b = geometry.bounds;
|
||||
return CanvasSnap._(
|
||||
Offset.zero,
|
||||
_alignedGuides([b.left, b.center.dx, b.right], canvas.width, 0),
|
||||
_alignedGuides([b.top, b.center.dy, b.bottom], canvas.height, 0),
|
||||
null,
|
||||
null,
|
||||
canvas,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum _SnapAnchor { start, center, end }
|
||||
|
||||
class _SnapMatch {
|
||||
const _SnapMatch(this.anchor, this.target);
|
||||
final _SnapAnchor anchor;
|
||||
final _SnapAnchor target;
|
||||
// Only break equal-distance ties; proximity still wins when acquiring a lock.
|
||||
int get priority => anchor == target ? (anchor == .center ? 0 : 1) : 2;
|
||||
}
|
||||
|
||||
/// Evaluate unsnapped pointer geometry, never the last corrected position.
|
||||
/// Keep the previous anchor/target pair until it exceeds the release threshold.
|
||||
/// Display guides are all exact alignments AFTER correction, not snap candidates.
|
||||
CanvasSnap snapToCanvas(
|
||||
PreviewGeometry geometry,
|
||||
Size canvas,
|
||||
double threshold, {
|
||||
CanvasSnap? previous,
|
||||
double? releaseThreshold,
|
||||
}) {
|
||||
final release = releaseThreshold ?? threshold * 5 / 3;
|
||||
if (!threshold.isFinite ||
|
||||
threshold <= 0 ||
|
||||
!release.isFinite ||
|
||||
release < threshold) {
|
||||
throw ArgumentError(
|
||||
'Snap thresholds must be finite, positive, and release >= entry',
|
||||
);
|
||||
}
|
||||
if (previous?._canvas != canvas) previous = null;
|
||||
final b = geometry.bounds;
|
||||
final xs = [b.left, b.center.dx, b.right];
|
||||
final ys = [b.top, b.center.dy, b.bottom];
|
||||
final x = _snapAxis(xs, canvas.width, threshold, release, previous?._x);
|
||||
final y = _snapAxis(ys, canvas.height, threshold, release, previous?._y);
|
||||
return CanvasSnap._(
|
||||
Offset(x.$1, y.$1),
|
||||
_alignedGuides(xs, canvas.width, x.$1),
|
||||
_alignedGuides(ys, canvas.height, y.$1),
|
||||
x.$2,
|
||||
y.$2,
|
||||
canvas,
|
||||
);
|
||||
}
|
||||
|
||||
(double, _SnapMatch?) _snapAxis(
|
||||
List<double> anchors,
|
||||
double extent,
|
||||
double entry,
|
||||
double release,
|
||||
_SnapMatch? previous,
|
||||
) {
|
||||
final targets = [0.0, extent / 2, extent];
|
||||
double correction(_SnapMatch match) =>
|
||||
targets[match.target.index] - anchors[match.anchor.index];
|
||||
if (previous != null) {
|
||||
final delta = correction(previous);
|
||||
if (delta.abs() <= release) return (delta, previous);
|
||||
}
|
||||
_SnapMatch? best;
|
||||
var delta = 0.0;
|
||||
for (final target in _SnapAnchor.values) {
|
||||
for (final anchor in _SnapAnchor.values) {
|
||||
final candidate = _SnapMatch(anchor, target);
|
||||
final next = correction(candidate);
|
||||
if (next.abs() > entry) continue;
|
||||
if (best == null ||
|
||||
next.abs() < delta.abs() - 1e-9 ||
|
||||
((next.abs() - delta.abs()).abs() <= 1e-9 &&
|
||||
candidate.priority < best.priority)) {
|
||||
best = candidate;
|
||||
delta = next;
|
||||
}
|
||||
}
|
||||
}
|
||||
return (delta, best);
|
||||
}
|
||||
|
||||
List<double> _alignedGuides(
|
||||
List<double> anchors,
|
||||
double extent,
|
||||
double delta,
|
||||
) => List.unmodifiable([
|
||||
for (final target in [0.0, extent / 2, extent])
|
||||
if (anchors.any((anchor) => (anchor + delta - target).abs() <= 1e-6))
|
||||
target,
|
||||
]);
|
||||
|
||||
/// Scale about the opposite corner. Solve in the transformed edge basis so
|
||||
/// unlocked resizing also works through rotated and nonuniformly scaled groups.
|
||||
ClipTransform scaleFromCorner(
|
||||
PreviewVisual visual,
|
||||
int corner,
|
||||
Offset pointer,
|
||||
Size canvas, {
|
||||
bool locked = true,
|
||||
}) {
|
||||
final points = visual.geometry.selectionCorners;
|
||||
final fixed = points[(corner + 2) % 4];
|
||||
final diagonal = points[corner] - fixed;
|
||||
final moved = pointer - fixed;
|
||||
final factor =
|
||||
((moved.dx * diagonal.dx + moved.dy * diagonal.dy) /
|
||||
diagonal.distanceSquared)
|
||||
.clamp(
|
||||
math.max(
|
||||
.01 / visual.transform.scale,
|
||||
.01 / visual.transform.scaleY,
|
||||
),
|
||||
math.min(
|
||||
100 / visual.transform.scale,
|
||||
100 / visual.transform.scaleY,
|
||||
),
|
||||
)
|
||||
.toDouble();
|
||||
var factorX = factor;
|
||||
var factorY = factor;
|
||||
if (!locked) {
|
||||
final localDiagonal = visual.geometry.distortionDelta(diagonal);
|
||||
final localMoved = visual.geometry.distortionDelta(moved);
|
||||
if (localDiagonal.dx.abs() < 1e-12 || localDiagonal.dy.abs() < 1e-12) {
|
||||
return visual.transform;
|
||||
}
|
||||
factorX = (localMoved.dx / localDiagonal.dx).clamp(
|
||||
.01 / visual.transform.scale,
|
||||
100 / visual.transform.scale,
|
||||
);
|
||||
factorY = (localMoved.dy / localDiagonal.dy).clamp(
|
||||
.01 / visual.transform.scaleY,
|
||||
100 / visual.transform.scaleY,
|
||||
);
|
||||
}
|
||||
final scaled = visual.transform.copyWith(
|
||||
scale: visual.transform.scale * factorX,
|
||||
scaleY: visual.transform.scaleY * factorY,
|
||||
);
|
||||
final delta = visual.geometry.localDelta(
|
||||
fixed -
|
||||
visual.geometry
|
||||
.changed(visual.transform, scaled, canvas)
|
||||
.corners[(corner + 2) % 4],
|
||||
);
|
||||
return scaled.copyWith(
|
||||
x: visual.transform.x + delta.dx / canvas.width,
|
||||
y: visual.transform.y + delta.dy / canvas.height,
|
||||
);
|
||||
}
|
||||
|
||||
/// Resize snapping changes scale, never translates the fixed opposite corner.
|
||||
(ClipTransform, CanvasSnap) snapScaleToCanvas(
|
||||
PreviewVisual visual,
|
||||
int corner,
|
||||
Offset pointer,
|
||||
Size canvas,
|
||||
double threshold, {
|
||||
required bool locked,
|
||||
CanvasSnap? previous,
|
||||
}) {
|
||||
if (!locked) {
|
||||
final snap = snapToCanvas(
|
||||
PreviewGeometry(center: pointer, size: Size.zero),
|
||||
canvas,
|
||||
threshold,
|
||||
previous: previous,
|
||||
);
|
||||
return (
|
||||
scaleFromCorner(
|
||||
visual,
|
||||
corner,
|
||||
pointer + snap.delta,
|
||||
canvas,
|
||||
locked: false,
|
||||
),
|
||||
snap,
|
||||
);
|
||||
}
|
||||
final raw = scaleFromCorner(visual, corner, pointer, canvas);
|
||||
final factor = raw.scale / visual.transform.scale;
|
||||
final points = visual.geometry.corners;
|
||||
final fixed = points[(corner + 2) % 4];
|
||||
final bounds = visual.geometry.bounds;
|
||||
var bestDistance = double.infinity;
|
||||
var bestFactor = factor;
|
||||
_SnapMatch? bestX;
|
||||
_SnapMatch? bestY;
|
||||
var retained = false;
|
||||
// Bounds are affine in a positive uniform scale about the fixed corner.
|
||||
// Ignore stationary anchors, which must not mask a moving edge's snap.
|
||||
for (final horizontal in [true, false]) {
|
||||
final origin = horizontal ? fixed.dx : fixed.dy;
|
||||
final anchors = horizontal
|
||||
? [bounds.left, bounds.center.dx, bounds.right]
|
||||
: [bounds.top, bounds.center.dy, bounds.bottom];
|
||||
final extent = horizontal ? canvas.width : canvas.height;
|
||||
final targets = [0.0, extent / 2, extent];
|
||||
final old = previous?._canvas == canvas
|
||||
? (horizontal ? previous?._x : previous?._y)
|
||||
: null;
|
||||
for (final anchor in _SnapAnchor.values) {
|
||||
final slope = anchors[anchor.index] - origin;
|
||||
if (slope.abs() < 1e-9) continue;
|
||||
for (final target in _SnapAnchor.values) {
|
||||
final keep = old?.anchor == anchor && old?.target == target;
|
||||
final distance = (targets[target.index] - origin - slope * factor)
|
||||
.abs();
|
||||
final candidate = (targets[target.index] - origin) / slope;
|
||||
if (distance > threshold * (keep ? 5 / 3 : 1) ||
|
||||
candidate * visual.transform.scale < .01 ||
|
||||
candidate * visual.transform.scale > 100 ||
|
||||
candidate * visual.transform.scaleY < .01 ||
|
||||
candidate * visual.transform.scaleY > 100) {
|
||||
continue;
|
||||
}
|
||||
if ((keep && !retained) ||
|
||||
(keep == retained && distance < bestDistance)) {
|
||||
retained = keep;
|
||||
bestDistance = distance;
|
||||
bestFactor = candidate;
|
||||
bestX = horizontal ? _SnapMatch(anchor, target) : null;
|
||||
bestY = horizontal ? null : _SnapMatch(anchor, target);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
final value = scaleFromCorner(
|
||||
visual,
|
||||
corner,
|
||||
fixed + (points[corner] - fixed) * bestFactor,
|
||||
canvas,
|
||||
);
|
||||
final guides = CanvasSnap.guides(
|
||||
visual.geometry.changed(visual.transform, value, canvas),
|
||||
canvas,
|
||||
);
|
||||
return (
|
||||
value,
|
||||
CanvasSnap._(
|
||||
Offset.zero,
|
||||
guides.verticalGuides,
|
||||
guides.horizontalGuides,
|
||||
bestX,
|
||||
bestY,
|
||||
canvas,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
import 'dart:async';
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/foundation.dart' show listEquals;
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import 'preview_controller.dart';
|
||||
import 'selection_decoration.dart';
|
||||
import 'preview_geometry.dart';
|
||||
import 'preview_transform_session.dart';
|
||||
|
||||
class PreviewInteractionOverlay extends StatefulWidget {
|
||||
const PreviewInteractionOverlay({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.canvasRect,
|
||||
this.onError,
|
||||
});
|
||||
final PreviewController controller;
|
||||
final Rect canvasRect;
|
||||
final void Function(Object error)? onError;
|
||||
@override
|
||||
State<PreviewInteractionOverlay> createState() =>
|
||||
_PreviewInteractionOverlayState();
|
||||
}
|
||||
|
||||
enum _Operation { move, scale, rotate, distort }
|
||||
|
||||
class _Drag {
|
||||
_Drag(
|
||||
this.edit,
|
||||
this.visual,
|
||||
this.operation,
|
||||
this.down,
|
||||
this.corner,
|
||||
this.inputOffset,
|
||||
) : value = visual.transform;
|
||||
final PreviewTransformEdit edit;
|
||||
final PreviewVisual visual;
|
||||
final _Operation operation;
|
||||
final Offset down;
|
||||
final int corner;
|
||||
final Offset inputOffset;
|
||||
ClipTransform value;
|
||||
CanvasSnap? snap;
|
||||
Offset? pointer;
|
||||
}
|
||||
|
||||
class _PreviewInteractionOverlayState extends State<PreviewInteractionOverlay> {
|
||||
final _focus = FocusNode();
|
||||
late final _label = SelectionLabel(onChanged: _rendered);
|
||||
MouseCursor _cursor = SystemMouseCursors.basic;
|
||||
_Drag? _drag;
|
||||
Offset? _down;
|
||||
_Drag? _pointerDrag;
|
||||
final _edits = <PreviewTransformEdit>{};
|
||||
Size get _canvas =>
|
||||
Size(widget.controller.canvas.width, widget.controller.canvas.height);
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Scene synchronization can change geometry without moving the playhead
|
||||
// or changing selection. Observe it directly even when the host filters
|
||||
// those notifications to keep the surrounding canvas stable.
|
||||
widget.controller.positionChanges.addListener(_rendered);
|
||||
widget.controller.transforms.presentation.addListener(_rendered);
|
||||
}
|
||||
|
||||
void _rendered() {
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
|
||||
double get _scale => widget.canvasRect.width / _canvas.width;
|
||||
// Use 1% of the displayed short side, capped at six logical pixels.
|
||||
double get _snapThreshold =>
|
||||
math.min(6.0, widget.canvasRect.shortestSide * .01) / _scale;
|
||||
Offset _output(Offset p) => (p - widget.canvasRect.topLeft) / _scale;
|
||||
Offset _screen(Offset p) => widget.canvasRect.topLeft + p * _scale;
|
||||
PreviewVisual? get _selected {
|
||||
final ids = widget.controller.selectedVisualIds;
|
||||
if (ids.isEmpty) return null;
|
||||
return widget.controller.visualsForSelection(ids).lastOrNull;
|
||||
}
|
||||
|
||||
PreviewVisual? _hit(Offset point) => widget.canvasRect.contains(point)
|
||||
? widget.controller.visuals.reversed
|
||||
.where((v) => _displayGeometry(v).contains(_output(point)))
|
||||
.firstOrNull
|
||||
: null;
|
||||
PreviewGeometry _displayGeometry(PreviewVisual visual) =>
|
||||
visual.geometry.changed(
|
||||
visual.transform,
|
||||
widget.controller.transforms.displayedValueFor(visual.elementId) ??
|
||||
visual.transform,
|
||||
_canvas,
|
||||
);
|
||||
void _start(DragStartDetails details) {
|
||||
_pointerDrag = null;
|
||||
if (_drag != null) return;
|
||||
final point = _down ?? details.localPosition;
|
||||
var visual = _selected;
|
||||
var operation = _Operation.move;
|
||||
var corner = -1;
|
||||
var inputOffset = Offset.zero;
|
||||
if (visual != null) {
|
||||
final displayed = _displayGeometry(visual);
|
||||
final corners = displayed.selectionCorners.map(_screen).toList();
|
||||
corner = selectionResizeCorner(corners, point);
|
||||
if (corner >= 0) {
|
||||
operation =
|
||||
widget.controller.distortionEditingElement == visual.elementId
|
||||
? _Operation.distort
|
||||
: _Operation.scale;
|
||||
inputOffset =
|
||||
visual.geometry.selectionCorners[corner] -
|
||||
displayed.selectionCorners[corner];
|
||||
} else if (widget.controller.distortionEditingElement == null &&
|
||||
selectionRotationCorner(corners, point) >= 0) {
|
||||
operation = _Operation.rotate;
|
||||
inputOffset = visual.geometry.center - displayed.center;
|
||||
} else {
|
||||
visual = _hit(point);
|
||||
}
|
||||
} else {
|
||||
visual = _hit(point);
|
||||
}
|
||||
if (visual == null || _scale <= 0) return;
|
||||
final edit = widget.controller.transforms.begin(visual);
|
||||
if (edit == null) return;
|
||||
_edits.add(edit);
|
||||
// Hit the completed frame, but retain queued authored edits as the gesture
|
||||
// baseline. A fixed offset prevents a pending frame from jumping a handle.
|
||||
final drag = _Drag(
|
||||
edit,
|
||||
visual,
|
||||
operation,
|
||||
_output(point) + inputOffset,
|
||||
corner,
|
||||
inputOffset,
|
||||
);
|
||||
_pointerDrag = drag;
|
||||
setState(() => _drag = drag);
|
||||
// Recognition can consume the only move event of a fast mouse drag.
|
||||
_updateAt(details.localPosition);
|
||||
unawaited(
|
||||
edit.done.then((_) {
|
||||
final owned = _edits.remove(edit);
|
||||
if (!mounted || !owned) return;
|
||||
if (identical(drag, _drag)) {
|
||||
_pointerDrag = null;
|
||||
setState(() => _drag = null);
|
||||
}
|
||||
if (edit.error != null) {
|
||||
widget.onError?.call(edit.error!);
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
void _update(DragUpdateDetails details) {
|
||||
if (identical(_pointerDrag, _drag)) _updateAt(details.localPosition);
|
||||
}
|
||||
|
||||
void _updateAt(Offset position) {
|
||||
final drag = _drag;
|
||||
if (drag == null || drag.edit.cancelled) return;
|
||||
drag.pointer = position;
|
||||
final pointer = _output(position) + drag.inputOffset;
|
||||
final original = drag.visual.transform;
|
||||
ClipTransform next;
|
||||
CanvasSnap? snap;
|
||||
switch (drag.operation) {
|
||||
case _Operation.move:
|
||||
final delta = drag.visual.geometry.localDelta(pointer - drag.down);
|
||||
next = original.copyWith(
|
||||
x: original.x + delta.dx / _canvas.width,
|
||||
y: original.y + delta.dy / _canvas.height,
|
||||
);
|
||||
if (!HardwareKeyboard.instance.isAltPressed) {
|
||||
snap = snapToCanvas(
|
||||
drag.visual.geometry.changed(original, next, _canvas),
|
||||
_canvas,
|
||||
_snapThreshold,
|
||||
previous: drag.snap,
|
||||
);
|
||||
final correction = drag.visual.geometry.localDelta(snap.delta);
|
||||
next = next.copyWith(
|
||||
x: next.x + correction.dx / _canvas.width,
|
||||
y: next.y + correction.dy / _canvas.height,
|
||||
);
|
||||
}
|
||||
case _Operation.scale:
|
||||
if (HardwareKeyboard.instance.isAltPressed) {
|
||||
next = scaleFromCorner(
|
||||
drag.visual,
|
||||
drag.corner,
|
||||
pointer,
|
||||
_canvas,
|
||||
locked: widget.controller.aspectRatioLocked,
|
||||
);
|
||||
} else {
|
||||
(next, snap) = snapScaleToCanvas(
|
||||
drag.visual,
|
||||
drag.corner,
|
||||
pointer,
|
||||
_canvas,
|
||||
_snapThreshold,
|
||||
locked: widget.controller.aspectRatioLocked,
|
||||
previous: drag.snap,
|
||||
);
|
||||
}
|
||||
case _Operation.distort:
|
||||
final delta = drag.visual.geometry.distortionDelta(pointer - drag.down);
|
||||
final offsets = original.distortion.corners;
|
||||
final p = offsets[drag.corner];
|
||||
var pose = original.distortion.withCorner(
|
||||
drag.corner,
|
||||
p.$1 + delta.dx,
|
||||
p.$2 + delta.dy,
|
||||
);
|
||||
if (widget.controller.distortionPerspective) {
|
||||
final linked = drag.corner ^ 1;
|
||||
final q = offsets[linked];
|
||||
pose = pose.withCorner(linked, q.$1 - delta.dx, q.$2 + delta.dy);
|
||||
}
|
||||
next = original.copyWith(
|
||||
distortion: pose.constrained(from: original.distortion),
|
||||
);
|
||||
case _Operation.rotate:
|
||||
final center = drag.visual.geometry.center;
|
||||
final from = drag.visual.geometry.localDelta(drag.down - center);
|
||||
final to = drag.visual.geometry.localDelta(pointer - center);
|
||||
final delta = math.atan2(to.dy, to.dx) - math.atan2(from.dy, from.dx);
|
||||
var angle = original.rotation + delta * 180 / math.pi;
|
||||
if (HardwareKeyboard.instance.isShiftPressed) {
|
||||
angle = (angle / 15).round() * 15.0;
|
||||
}
|
||||
next = original.copyWith(rotation: normalizeRotationDegrees(angle));
|
||||
}
|
||||
setState(() {
|
||||
drag.value = next;
|
||||
drag.snap = snap;
|
||||
});
|
||||
drag.edit.update(drag.value);
|
||||
}
|
||||
|
||||
void _end() {
|
||||
final drag = _pointerDrag;
|
||||
_pointerDrag = null;
|
||||
if (drag == null) return;
|
||||
unawaited(drag.edit.end());
|
||||
setState(() => _drag = null);
|
||||
}
|
||||
|
||||
void _cancel() {
|
||||
final drag = _drag;
|
||||
_pointerDrag = null;
|
||||
drag?.edit.cancel();
|
||||
if (mounted) setState(() => _drag = null);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant PreviewInteractionOverlay oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.controller != widget.controller) {
|
||||
oldWidget.controller.positionChanges.removeListener(_rendered);
|
||||
oldWidget.controller.transforms.presentation.removeListener(_rendered);
|
||||
widget.controller.positionChanges.addListener(_rendered);
|
||||
widget.controller.transforms.presentation.addListener(_rendered);
|
||||
oldWidget.controller.cancelTransform();
|
||||
}
|
||||
if (oldWidget.controller != widget.controller ||
|
||||
oldWidget.canvasRect != widget.canvasRect) {
|
||||
for (final edit in _edits.toList()) {
|
||||
edit.cancel();
|
||||
}
|
||||
_edits.clear();
|
||||
_cancel();
|
||||
} else if (_drag?.edit.cancelled ?? false) {
|
||||
_cancel();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_label.dispose();
|
||||
widget.controller.positionChanges.removeListener(_rendered);
|
||||
widget.controller.transforms.presentation.removeListener(_rendered);
|
||||
for (final edit in _edits) {
|
||||
scheduleMicrotask(edit.cancel);
|
||||
}
|
||||
_edits.clear();
|
||||
_focus.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final drag = _drag;
|
||||
final visual = drag?.visual ?? _selected;
|
||||
final geometry = visual == null ? null : _displayGeometry(visual);
|
||||
return Focus(
|
||||
focusNode: _focus,
|
||||
onKeyEvent: (_, event) {
|
||||
if (event.logicalKey == LogicalKeyboardKey.altLeft ||
|
||||
event.logicalKey == LogicalKeyboardKey.altRight) {
|
||||
if (_drag?.pointer case final pointer?) _updateAt(pointer);
|
||||
}
|
||||
if (event is KeyDownEvent &&
|
||||
event.logicalKey == LogicalKeyboardKey.escape) {
|
||||
if (_drag != null) {
|
||||
_cancel();
|
||||
} else if (widget.controller.distortionEditingElement != null) {
|
||||
widget.controller.setDistortionEditing(null);
|
||||
} else {
|
||||
widget.controller.selectVisual(null);
|
||||
}
|
||||
return KeyEventResult.handled;
|
||||
}
|
||||
return KeyEventResult.ignored;
|
||||
},
|
||||
child: MouseRegion(
|
||||
onHover: (event) {
|
||||
final corners = geometry?.selectionCorners.map(_screen).toList();
|
||||
final cursor = corners == null
|
||||
? SystemMouseCursors.basic
|
||||
: widget.controller.distortionEditingElement != null
|
||||
? selectionResizeCorner(corners, event.localPosition) >= 0
|
||||
? SystemMouseCursors.precise
|
||||
: SystemMouseCursors.move
|
||||
: selectionCursor(corners, event.localPosition);
|
||||
if (_cursor != cursor) setState(() => _cursor = cursor);
|
||||
},
|
||||
onExit: (_) => setState(() => _cursor = SystemMouseCursors.basic),
|
||||
cursor: drag != null ? SystemMouseCursors.grabbing : _cursor,
|
||||
child: Listener(
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPointerDown: (_) => unawaited(
|
||||
widget.controller.pauseForCanvasInteraction().catchError(
|
||||
(Object _) {},
|
||||
),
|
||||
),
|
||||
child: GestureDetector(
|
||||
key: const Key('preview-interaction'),
|
||||
behavior: HitTestBehavior.opaque,
|
||||
onPanDown: (d) {
|
||||
_down = d.localPosition;
|
||||
_focus.requestFocus();
|
||||
},
|
||||
onTapUp: (d) => widget.controller.selectVisual(
|
||||
_hit(d.localPosition)?.elementId,
|
||||
),
|
||||
onPanStart: _start,
|
||||
onPanUpdate: _update,
|
||||
onPanEnd: (_) => _end(),
|
||||
onPanCancel: () {
|
||||
if (_pointerDrag != null) _cancel();
|
||||
},
|
||||
child: CustomPaint(
|
||||
painter: _SelectionPainter(
|
||||
label: _label,
|
||||
rect: widget.canvasRect,
|
||||
scale: _scale,
|
||||
devicePixelRatio: MediaQuery.devicePixelRatioOf(context),
|
||||
geometry: geometry,
|
||||
snap:
|
||||
drag?.snap != null &&
|
||||
geometry != null &&
|
||||
!HardwareKeyboard.instance.isAltPressed
|
||||
? CanvasSnap.guides(geometry, _canvas)
|
||||
: null,
|
||||
rotating: drag?.operation == _Operation.rotate,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SelectionPainter extends CustomPainter {
|
||||
_SelectionPainter({
|
||||
required this.label,
|
||||
required this.rect,
|
||||
required this.scale,
|
||||
required this.devicePixelRatio,
|
||||
required this.geometry,
|
||||
required this.snap,
|
||||
required this.rotating,
|
||||
}) : labelRevision = label.revision;
|
||||
final int labelRevision;
|
||||
final Rect rect;
|
||||
final SelectionLabel label;
|
||||
final double scale;
|
||||
final double devicePixelRatio;
|
||||
final PreviewGeometry? geometry;
|
||||
final CanvasSnap? snap;
|
||||
final bool rotating;
|
||||
@override
|
||||
void paint(Canvas canvas, Size size) {
|
||||
canvas.save();
|
||||
canvas.clipRect(Offset.zero & size);
|
||||
_paint(canvas);
|
||||
canvas.restore();
|
||||
}
|
||||
|
||||
void _paintGuides(Canvas canvas) {
|
||||
final guide = Paint()
|
||||
..color = const Color(0xFFFF55C8)
|
||||
..strokeWidth = 1;
|
||||
for (final x in snap?.verticalGuides ?? const <double>[]) {
|
||||
final screenX = rect.left + x * scale;
|
||||
canvas.drawLine(
|
||||
Offset(screenX, rect.top),
|
||||
Offset(screenX, rect.bottom),
|
||||
guide,
|
||||
);
|
||||
}
|
||||
for (final y in snap?.horizontalGuides ?? const <double>[]) {
|
||||
final screenY = rect.top + y * scale;
|
||||
canvas.drawLine(
|
||||
Offset(rect.left, screenY),
|
||||
Offset(rect.right, screenY),
|
||||
guide,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
void _paint(Canvas canvas) {
|
||||
final g = geometry;
|
||||
if (g == null) return;
|
||||
Offset screen(Offset p) => rect.topLeft + p * scale;
|
||||
final points = g.selectionCorners.map(screen).toList();
|
||||
paintSelectionDecoration(
|
||||
canvas,
|
||||
points,
|
||||
dimensions: g.size,
|
||||
devicePixelRatio: devicePixelRatio,
|
||||
rotation: rotating ? g.rotation : null,
|
||||
labelLayout: label,
|
||||
);
|
||||
_paintGuides(canvas);
|
||||
}
|
||||
|
||||
@override
|
||||
bool shouldRepaint(covariant _SelectionPainter oldDelegate) {
|
||||
if (geometry == null && oldDelegate.geometry == null) return false;
|
||||
return rect != oldDelegate.rect ||
|
||||
labelRevision != oldDelegate.labelRevision ||
|
||||
scale != oldDelegate.scale ||
|
||||
devicePixelRatio != oldDelegate.devicePixelRatio ||
|
||||
rotating != oldDelegate.rotating ||
|
||||
geometry?.size != oldDelegate.geometry?.size ||
|
||||
geometry?.rotation != oldDelegate.geometry?.rotation ||
|
||||
!listEquals(
|
||||
geometry?.selectionCorners,
|
||||
oldDelegate.geometry?.selectionCorners,
|
||||
) ||
|
||||
!listEquals(snap?.verticalGuides, oldDelegate.snap?.verticalGuides) ||
|
||||
!listEquals(snap?.horizontalGuides, oldDelegate.snap?.horizontalGuides);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
part of 'preview_controller.dart';
|
||||
|
||||
/// Uses the same retained GPU frame and deferred publication as mask editing.
|
||||
extension PreviewObscureEditing on PreviewController {
|
||||
bool get obscureDragging => _obscureBase != null;
|
||||
ElementId? get obscureEditingElement =>
|
||||
_editingElement(PreviewCanvasEditMode.obscure);
|
||||
int get obscureEditGeneration => _obscureGeneration;
|
||||
void setObscureEditing(ElementId? id, {Object? owner}) =>
|
||||
_setCanvasEditing(PreviewCanvasEditMode.obscure, id, owner: owner);
|
||||
|
||||
void releaseObscureEditing(Object owner) =>
|
||||
_releaseCanvasEditing(PreviewCanvasEditMode.obscure, owner);
|
||||
|
||||
ClipObscureAnimation? obscureAnimation(ElementId id) {
|
||||
final stack = maskStackFor(id);
|
||||
if (stack == null) return null;
|
||||
final animation = ClipObscureAnimation(stack.record, stack.localTick);
|
||||
return animation.exists ? animation : null;
|
||||
}
|
||||
|
||||
ClipMask? obscureFor(ElementId id) =>
|
||||
id == obscureEditingElement && _pendingObscure != null
|
||||
? _pendingObscure
|
||||
: obscureAnimation(id)?.value;
|
||||
Map<String, double> _obscureValuesFor(ElementId id) => {
|
||||
...?obscureAnimation(id)?.values,
|
||||
if (id == obscureEditingElement && _pendingObscure != null)
|
||||
for (final f in ClipObscureAnimation.channels.expand((c) => c))
|
||||
'obscure.$f': _pendingObscure!.values[f]!,
|
||||
};
|
||||
Future<bool> beginObscureEdit() async {
|
||||
final id = obscureEditingElement;
|
||||
if (id == null ||
|
||||
!canPlay ||
|
||||
_view == null ||
|
||||
obscureAnimation(id)?.containsPlayhead != true ||
|
||||
!_nativeVisuals.any((v) => v.elementId == id)) {
|
||||
return false;
|
||||
}
|
||||
if (transforms.hasPending || _keyframePreviewing) cancelTransform();
|
||||
final generation = ++_obscureGeneration;
|
||||
_obscureBase = _view!.version.kernelVersion;
|
||||
_obscureTick = positionTick;
|
||||
_pendingObscure = obscureAnimation(id)!.value;
|
||||
final bool ready;
|
||||
try {
|
||||
ready = await transforms.ensureContext();
|
||||
} catch (_) {
|
||||
if (generation == _obscureGeneration) cancelObscureEdit();
|
||||
rethrow;
|
||||
}
|
||||
if (!ready || _closed || generation != _obscureGeneration) {
|
||||
if (generation == _obscureGeneration) cancelObscureEdit();
|
||||
return false;
|
||||
}
|
||||
_renderObscure();
|
||||
return true;
|
||||
}
|
||||
|
||||
void _renderObscure() {
|
||||
final id = obscureEditingElement;
|
||||
if (id == null || _transformHandle == null) return;
|
||||
final visual = visualForProperties(id);
|
||||
if (visual != null) _updateTransform(id, visual.transform, () {});
|
||||
}
|
||||
|
||||
void updateObscure(ClipMask next) {
|
||||
if (_obscureBase == null ||
|
||||
!next.isValid ||
|
||||
next.width > 3 ||
|
||||
next.height > 3) {
|
||||
return;
|
||||
}
|
||||
_pendingObscure = next;
|
||||
_renderObscure();
|
||||
_notify();
|
||||
}
|
||||
|
||||
void endObscureEdit() {
|
||||
final id = obscureEditingElement, next = _pendingObscure;
|
||||
try {
|
||||
if (id != null &&
|
||||
next != null &&
|
||||
identical(_obscureBase, _view?.version.kernelVersion) &&
|
||||
_obscureTick == positionTick) {
|
||||
final curves = obscureAnimation(id)!.edit(next);
|
||||
if (curves.isNotEmpty) {
|
||||
void edit() =>
|
||||
timeline.publishParameters(activeSequence()!, id, curves);
|
||||
if (_nativeTransforming) {
|
||||
_publishInteractiveParameters(edit);
|
||||
} else {
|
||||
edit();
|
||||
}
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
cancelObscureEdit();
|
||||
}
|
||||
}
|
||||
|
||||
void cancelObscureEdit() {
|
||||
_obscureGeneration++;
|
||||
_obscureBase = null;
|
||||
_obscureTick = null;
|
||||
_pendingObscure = null;
|
||||
_renderObscure();
|
||||
_notify();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
import 'package:cutdex_native_flutter/contracts.dart';
|
||||
|
||||
/// Viewing assumptions; authored project settings take precedence.
|
||||
final class PreviewPolicy {
|
||||
const PreviewPolicy({
|
||||
this.unknownVideoColorSpace =
|
||||
RenderColorPolicy.defaultUnknownVideoColorSpace,
|
||||
this.sourceHeadroom = RenderColorPolicy.defaultSourceHeadroom,
|
||||
this.targetHeadroom = RenderColorPolicy.defaultTargetHeadroom,
|
||||
this.skimmingMode = SkimmingMode.audible,
|
||||
});
|
||||
final RenderColorSpace? unknownVideoColorSpace;
|
||||
final double sourceHeadroom;
|
||||
final double targetHeadroom;
|
||||
|
||||
/// Selects silent or audible preview while dragging the playhead.
|
||||
final SkimmingMode skimmingMode;
|
||||
RenderColorPolicy get colorPolicy => RenderColorPolicy(
|
||||
unknownVideoColorSpace: unknownVideoColorSpace,
|
||||
sourceHeadroom: sourceHeadroom,
|
||||
targetHeadroom: targetHeadroom,
|
||||
);
|
||||
|
||||
RenderToneMapping get toneMapping =>
|
||||
colorPolicy.toneMappingFor(supportsToneMapping: true);
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'preview_geometry.dart';
|
||||
|
||||
/// A paused-frame editing context, independent of pointer and history lifetimes.
|
||||
/// Preparation runs once; rendering follows latest values, never a FIFO of edits.
|
||||
class PreviewTransformSession extends ChangeNotifier {
|
||||
PreviewTransformSession({
|
||||
required this.canBegin,
|
||||
required this.select,
|
||||
required this.prepareNative,
|
||||
required this.updateNative,
|
||||
required this.commit,
|
||||
required this.cancelNative,
|
||||
required this.failed,
|
||||
required this.changed,
|
||||
});
|
||||
final bool Function() canBegin;
|
||||
final void Function(ElementId) select;
|
||||
final Future<bool> Function() prepareNative;
|
||||
final void Function(ElementId, ClipTransform, VoidCallback onRendered)
|
||||
updateNative;
|
||||
final void Function(ElementId, ClipTransform) commit;
|
||||
final void Function() cancelNative;
|
||||
final void Function(Object) failed;
|
||||
final void Function() changed;
|
||||
final _values = <ElementId, ClipTransform>{};
|
||||
final _displayed = <ElementId, ClipTransform>{};
|
||||
final presentation = ValueNotifier<int>(0);
|
||||
final _committed = <ElementId, ClipTransform>{};
|
||||
PreviewTransformEdit? _active;
|
||||
Future<bool>? _preparing;
|
||||
bool _ready = false;
|
||||
int _epoch = 0;
|
||||
|
||||
ClipTransform? valueFor(ElementId id) => _values[id];
|
||||
|
||||
/// Last native render submitted to its display layer, not a display timestamp.
|
||||
ClipTransform? displayedValueFor(ElementId id) => _displayed[id];
|
||||
|
||||
void _changed() {
|
||||
changed();
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool get hasPending => _active != null;
|
||||
bool get hasContext => _preparing != null;
|
||||
|
||||
/// Render externally prepared parameter values without opening another edit.
|
||||
/// The caller owns publication; native rendering keeps only the latest values.
|
||||
void previewValues(Map<ElementId, ClipTransform> values) {
|
||||
for (final entry in values.entries) {
|
||||
if (!entry.value.isValid) {
|
||||
throw ArgumentError('Invalid preview transform');
|
||||
}
|
||||
}
|
||||
var changed = false;
|
||||
for (final entry in values.entries) {
|
||||
if (_values[entry.key] == entry.value) continue;
|
||||
_values[entry.key] = entry.value;
|
||||
_publish(entry.key, entry.value);
|
||||
changed = true;
|
||||
}
|
||||
if (changed) _changed();
|
||||
}
|
||||
|
||||
Future<void> get settled async {
|
||||
await _preparing;
|
||||
}
|
||||
|
||||
/// Selection alone can acquire the paused frame without opening history.
|
||||
Future<bool> ensureContext() {
|
||||
if (!canBegin()) return Future.value(false);
|
||||
return _preparing ??= _prepare(_epoch);
|
||||
}
|
||||
|
||||
PreviewTransformEdit? begin(PreviewVisual visual) {
|
||||
if (!canBegin() || _active != null) return null;
|
||||
final edit = PreviewTransformEdit._(this, visual);
|
||||
_displayed.putIfAbsent(visual.elementId, () => visual.transform);
|
||||
_active = edit;
|
||||
select(visual.elementId);
|
||||
_preparing ??= _prepare(_epoch);
|
||||
edit._prepared = _preparing!.then((ready) => ready && !edit.cancelled);
|
||||
_changed();
|
||||
return edit;
|
||||
}
|
||||
|
||||
Future<bool> _prepare(int epoch) async {
|
||||
try {
|
||||
final ready = await prepareNative();
|
||||
if (epoch != _epoch) return false;
|
||||
if (!ready) {
|
||||
cancelAll();
|
||||
return false;
|
||||
}
|
||||
_ready = true;
|
||||
// Gestures may have ended while preparing. Only their latest combined
|
||||
// state matters to rendering; history has already recorded each release.
|
||||
for (final entry in _values.entries.toList()) {
|
||||
_publish(entry.key, entry.value);
|
||||
}
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (epoch == _epoch) {
|
||||
cancelAll();
|
||||
failed(error);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
List<PreviewVisual> project(List<PreviewVisual> visuals, Size canvas) => [
|
||||
for (final visual in visuals)
|
||||
if (_values[visual.elementId] case final value?)
|
||||
PreviewVisual(
|
||||
layerId: visual.layerId,
|
||||
elementId: visual.elementId,
|
||||
lane: visual.lane,
|
||||
transform: value,
|
||||
geometry: visual.geometry.changed(visual.transform, value, canvas),
|
||||
)
|
||||
else
|
||||
visual,
|
||||
];
|
||||
|
||||
void _update(PreviewTransformEdit edit, ClipTransform value) {
|
||||
if (!identical(_active, edit) || edit.released) return;
|
||||
if (!value.isValid) {
|
||||
throw ArgumentError('Invalid canvas transform');
|
||||
}
|
||||
edit._value = value;
|
||||
_values[edit.initial.elementId] = value;
|
||||
_publish(edit.initial.elementId, value);
|
||||
// High-frequency values only notify consumers of the transform itself.
|
||||
// Selection geometry listens to acknowledged renders separately.
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void _publish(ElementId id, ClipTransform value) {
|
||||
if (!_ready) return;
|
||||
try {
|
||||
final epoch = _epoch;
|
||||
updateNative(id, value, () {
|
||||
if (epoch != _epoch || identical(_displayed[id], value)) return;
|
||||
_displayed[id] = value;
|
||||
presentation.value++;
|
||||
});
|
||||
} catch (error) {
|
||||
cancelAll();
|
||||
failed(error);
|
||||
}
|
||||
}
|
||||
|
||||
void _end(PreviewTransformEdit edit) {
|
||||
if (!identical(_active, edit)) return;
|
||||
try {
|
||||
commit(edit.initial.elementId, edit.value);
|
||||
_committed[edit.initial.elementId] = edit.value;
|
||||
_values[edit.initial.elementId] = edit.value;
|
||||
_active = null;
|
||||
edit._finish();
|
||||
_changed();
|
||||
} catch (error) {
|
||||
edit._error = error;
|
||||
_cancel(edit);
|
||||
failed(error);
|
||||
}
|
||||
}
|
||||
|
||||
void _cancel(PreviewTransformEdit edit) {
|
||||
if (!identical(_active, edit)) return;
|
||||
_active = null;
|
||||
edit._cancelled = true;
|
||||
edit._finish();
|
||||
final id = edit.initial.elementId;
|
||||
final restored = _committed[id] ?? edit.initial.transform;
|
||||
_values[id] = restored;
|
||||
if (_committed.isEmpty) {
|
||||
cancelAll();
|
||||
} else {
|
||||
_publish(id, restored);
|
||||
_changed();
|
||||
}
|
||||
}
|
||||
|
||||
/// Invalidates this frame context, not the already committed timeline history.
|
||||
void cancelAll() {
|
||||
_epoch++;
|
||||
_active?._cancelled = true;
|
||||
_active?._finish();
|
||||
_active = null;
|
||||
_preparing = null;
|
||||
_ready = false;
|
||||
_values.clear();
|
||||
_displayed.clear();
|
||||
_committed.clear();
|
||||
cancelNative();
|
||||
_changed();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_epoch++;
|
||||
presentation.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
class PreviewTransformEdit {
|
||||
PreviewTransformEdit._(this._session, this.initial)
|
||||
: _value = initial.transform;
|
||||
final PreviewTransformSession _session;
|
||||
final PreviewVisual initial;
|
||||
ClipTransform _value;
|
||||
ClipTransform get value => _value;
|
||||
late final Future<bool> _prepared;
|
||||
final _done = Completer<void>();
|
||||
bool _cancelled = false;
|
||||
Object? _error;
|
||||
Future<bool> get prepared => _prepared;
|
||||
Future<void> get done => _done.future;
|
||||
bool get released => _done.isCompleted;
|
||||
bool get cancelled => _cancelled;
|
||||
Object? get error => _error;
|
||||
void update(ClipTransform value) => _session._update(this, value);
|
||||
Future<void> end() {
|
||||
_session._end(this);
|
||||
return done;
|
||||
}
|
||||
|
||||
void cancel() => _session._cancel(this);
|
||||
void _finish() {
|
||||
if (!released) _done.complete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,234 @@
|
||||
import 'dart:math' as math;
|
||||
import 'dart:ui' show Vertices;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
const selectionBlue = Color(0xFF0099FF);
|
||||
|
||||
/// One label layout owned and released by the overlay's widget state.
|
||||
class SelectionLabel {
|
||||
SelectionLabel({this.onChanged}) {
|
||||
PaintingBinding.instance.systemFonts.addListener(_fontsChanged);
|
||||
}
|
||||
final VoidCallback? onChanged;
|
||||
String? _label;
|
||||
TextPainter? _painter;
|
||||
int _revision = 0;
|
||||
int get revision => _revision;
|
||||
|
||||
void _fontsChanged() {
|
||||
_revision++;
|
||||
_painter?.dispose();
|
||||
_painter = null;
|
||||
_label = null;
|
||||
onChanged?.call();
|
||||
}
|
||||
|
||||
TextPainter layout(String label) {
|
||||
if (_label == label && _painter != null) return _painter!;
|
||||
_painter?.dispose();
|
||||
_label = label;
|
||||
return _painter = TextPainter(
|
||||
text: TextSpan(
|
||||
text: label,
|
||||
style: const TextStyle(color: Colors.white, fontSize: 12),
|
||||
),
|
||||
textDirection: TextDirection.ltr,
|
||||
)..layout();
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
PaintingBinding.instance.systemFonts.removeListener(_fontsChanged);
|
||||
_painter?.dispose();
|
||||
_painter = null;
|
||||
_label = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Corner squares resize; the exterior sector around each corner rotates.
|
||||
int selectionResizeCorner(List<Offset> corners, Offset pointer) =>
|
||||
corners.indexWhere((p) => (p - pointer).distance <= 9);
|
||||
|
||||
int selectionRotationCorner(List<Offset> corners, Offset pointer) {
|
||||
final path = Path()..addPolygon(corners, true);
|
||||
if (path.contains(pointer)) return -1;
|
||||
return corners.indexWhere((p) => (p - pointer).distance <= 26);
|
||||
}
|
||||
|
||||
MouseCursor selectionCursor(List<Offset> corners, Offset pointer) {
|
||||
final corner = selectionResizeCorner(corners, pointer);
|
||||
if (corner >= 0) {
|
||||
final diagonal = corners[corner] - corners[(corner + 2) % 4];
|
||||
final sector =
|
||||
(math.atan2(diagonal.dy, diagonal.dx) / (math.pi / 4)).round() % 4;
|
||||
return switch (sector) {
|
||||
0 => SystemMouseCursors.resizeLeftRight,
|
||||
1 => SystemMouseCursors.resizeUpLeftDownRight,
|
||||
2 => SystemMouseCursors.resizeUpDown,
|
||||
_ => SystemMouseCursors.resizeUpRightDownLeft,
|
||||
};
|
||||
}
|
||||
if (selectionRotationCorner(corners, pointer) >= 0) {
|
||||
return SystemMouseCursors.grab;
|
||||
}
|
||||
return SystemMouseCursors.basic;
|
||||
}
|
||||
|
||||
void paintSelectionDecoration(
|
||||
Canvas canvas,
|
||||
List<Offset> corners, {
|
||||
required Size dimensions,
|
||||
required double devicePixelRatio,
|
||||
double? rotation,
|
||||
SelectionLabel? labelLayout,
|
||||
}) {
|
||||
final physicalStrokeWidth = math.max(1, (1.5 * devicePixelRatio).round());
|
||||
final outline = Paint()
|
||||
..color = selectionBlue
|
||||
..isAntiAlias = true
|
||||
..style = PaintingStyle.stroke
|
||||
..strokeWidth = physicalStrokeWidth / devicePixelRatio;
|
||||
final angle = math.atan2(
|
||||
(corners[1] - corners[0]).dy,
|
||||
(corners[1] - corners[0]).dx,
|
||||
);
|
||||
final axisAligned =
|
||||
(angle - (angle / (math.pi / 2)).round() * math.pi / 2).abs() < 1e-9;
|
||||
// Align stroke boundaries to physical pixels only for axis-aligned bounds.
|
||||
// Rotated edges retain their exact subpixel coordinates for antialiasing.
|
||||
double align(double coordinate) =>
|
||||
((coordinate * devicePixelRatio - physicalStrokeWidth / 2).round() +
|
||||
physicalStrokeWidth / 2) /
|
||||
devicePixelRatio;
|
||||
final paintedCorners = axisAligned
|
||||
? [for (final p in corners) Offset(align(p.dx), align(p.dy))]
|
||||
: corners;
|
||||
if (axisAligned) {
|
||||
canvas.drawPath(Path()..addPolygon(paintedCorners, true), outline);
|
||||
} else {
|
||||
_paintSmoothOutline(canvas, corners, outline, devicePixelRatio);
|
||||
}
|
||||
final handleFill = Paint()..color = Colors.white;
|
||||
for (final p in corners) {
|
||||
canvas.save();
|
||||
final Rect box;
|
||||
if (axisAligned) {
|
||||
box = Rect.fromLTRB(
|
||||
align(p.dx - 4),
|
||||
align(p.dy - 4),
|
||||
align(p.dx + 4),
|
||||
align(p.dy + 4),
|
||||
);
|
||||
} else {
|
||||
canvas.translate(p.dx, p.dy);
|
||||
canvas.rotate(angle);
|
||||
box = const Rect.fromLTWH(-4, -4, 8, 8);
|
||||
}
|
||||
canvas.drawRect(box, handleFill);
|
||||
if (axisAligned) {
|
||||
canvas.drawRect(box, outline);
|
||||
} else {
|
||||
_paintSmoothOutline(
|
||||
canvas,
|
||||
[box.topLeft, box.topRight, box.bottomRight, box.bottomLeft],
|
||||
outline,
|
||||
devicePixelRatio,
|
||||
);
|
||||
}
|
||||
canvas.restore();
|
||||
}
|
||||
final label = rotation == null
|
||||
? '${dimensions.width.round()} × ${dimensions.height.round()}'
|
||||
: '${rotation.toStringAsFixed(1)}°';
|
||||
final layout = labelLayout ?? SelectionLabel();
|
||||
final text = layout.layout(label);
|
||||
final quarterTurns = ((angle + math.pi / 4) / (math.pi / 2)).floor();
|
||||
final labelEdge = (2 - quarterTurns) % 4;
|
||||
final edgeCenter = (corners[labelEdge] + corners[(labelEdge + 1) % 4]) / 2;
|
||||
final oppositeCenter =
|
||||
(corners[(labelEdge + 2) % 4] + corners[(labelEdge + 3) % 4]) / 2;
|
||||
var outward = edgeCenter - oppositeCenter;
|
||||
outward = outward / math.max(outward.distance, .001);
|
||||
final center = edgeCenter + outward * (14 + text.height / 2);
|
||||
canvas.save();
|
||||
canvas.translate(center.dx, center.dy);
|
||||
canvas.rotate(angle - quarterTurns * math.pi / 2);
|
||||
final rect = Rect.fromCenter(
|
||||
center: Offset.zero,
|
||||
width: text.width + 12,
|
||||
height: text.height + 6,
|
||||
);
|
||||
canvas.drawRRect(
|
||||
RRect.fromRectAndRadius(rect, const Radius.circular(3)),
|
||||
Paint()..color = selectionBlue,
|
||||
);
|
||||
text.paint(canvas, rect.topLeft + const Offset(6, 3));
|
||||
canvas.restore();
|
||||
if (labelLayout == null) layout.dispose();
|
||||
}
|
||||
|
||||
/// Explicit opacity ramps smooth shallow diagonals.
|
||||
void _paintSmoothOutline(
|
||||
Canvas canvas,
|
||||
List<Offset> corners,
|
||||
Paint outline,
|
||||
double devicePixelRatio,
|
||||
) {
|
||||
final halfWidth = outline.strokeWidth / 2;
|
||||
final feather = math.min(outline.strokeWidth, 1.5 / devicePixelRatio);
|
||||
final outer = halfWidth + feather / 2;
|
||||
final core = halfWidth - feather / 2;
|
||||
final center = (corners[0] + corners[2]) / 2;
|
||||
final normals = <Offset>[];
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final edge = corners[(i + 1) % 4] - corners[i];
|
||||
if (edge.distance <= outer * 2) {
|
||||
canvas.drawPath(Path()..addPolygon(corners, true), outline);
|
||||
return;
|
||||
}
|
||||
var normal = Offset(edge.dy, -edge.dx) / edge.distance;
|
||||
final outward = (corners[i] + corners[(i + 1) % 4]) / 2 - center;
|
||||
if (normal.dx * outward.dx + normal.dy * outward.dy < 0) {
|
||||
normal = -normal;
|
||||
}
|
||||
normals.add(normal);
|
||||
}
|
||||
final miters = <Offset>[];
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final a = normals[(i + 3) % 4];
|
||||
final b = normals[i];
|
||||
miters.add((a + b) / math.max(1 + a.dx * b.dx + a.dy * b.dy, .001));
|
||||
}
|
||||
final positions = <Offset>[];
|
||||
final colors = <Color>[];
|
||||
final transparent = outline.color.withValues(alpha: 0);
|
||||
for (final (distance, color) in [
|
||||
(outer, transparent),
|
||||
(core, outline.color),
|
||||
(-core, outline.color),
|
||||
(-outer, transparent),
|
||||
]) {
|
||||
for (var i = 0; i < 4; i++) {
|
||||
positions.add(corners[i] + miters[i] * distance);
|
||||
colors.add(color);
|
||||
}
|
||||
}
|
||||
final indices = <int>[];
|
||||
for (var ring = 0; ring < 3; ring++) {
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final a = ring * 4 + i;
|
||||
final b = ring * 4 + (i + 1) % 4;
|
||||
final c = a + 4;
|
||||
final d = b + 4;
|
||||
indices.addAll([a, b, c, b, d, c]);
|
||||
}
|
||||
}
|
||||
final vertices = Vertices(
|
||||
VertexMode.triangles,
|
||||
positions,
|
||||
colors: colors,
|
||||
indices: indices,
|
||||
);
|
||||
canvas.drawVertices(vertices, BlendMode.dst, Paint());
|
||||
vertices.dispose();
|
||||
}
|
||||
@@ -0,0 +1,599 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:cutdex_core/editor/commands.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
|
||||
import 'cleanup.dart';
|
||||
import 'preview_policy.dart';
|
||||
|
||||
/// The host retains media access until the supplied action finishes.
|
||||
typedef PreviewMediaLoader = Future<T> Function<T>(
|
||||
Future<T> Function(MediaReference media) action,
|
||||
);
|
||||
|
||||
/// Owns an independent source session and holds file access until it is closed.
|
||||
class SourcePreviewController extends ChangeNotifier {
|
||||
SourcePreviewController({
|
||||
required this.loadMedia,
|
||||
required this.frameDuration,
|
||||
required this.rememberPosition,
|
||||
int positionTick = 0,
|
||||
this.policy = const PreviewPolicy(),
|
||||
CutdexRuntime? runtime,
|
||||
// Keep the public constructor argument separate from private storage.
|
||||
// ignore: prefer_initializing_formals
|
||||
}) : _positionTick = positionTick,
|
||||
runtime = runtime ?? CutdexRuntime();
|
||||
|
||||
final PreviewMediaLoader loadMedia;
|
||||
final PreviewPolicy policy;
|
||||
final RationalTime frameDuration;
|
||||
final void Function(int) rememberPosition;
|
||||
final CutdexRuntime runtime;
|
||||
RuntimeSession? _session;
|
||||
RuntimeSession? get session => _session;
|
||||
Uint8List? _image;
|
||||
Uint8List? get image => _image;
|
||||
double _aspectRatio = 16 / 9;
|
||||
double get aspectRatio => _aspectRatio;
|
||||
int _positionTick;
|
||||
int get positionTick => _positionTick;
|
||||
int _durationTick = 0;
|
||||
int get durationTick => _durationTick;
|
||||
bool _busy = true;
|
||||
bool get busy => _busy;
|
||||
bool _playing = false;
|
||||
bool get playing => _playing;
|
||||
bool _audioOnly = false;
|
||||
bool get audioOnly => _audioOnly;
|
||||
Object? _error;
|
||||
Object? get error => _error;
|
||||
bool _closed = false;
|
||||
StreamSubscription<RuntimeSnapshot>? _events;
|
||||
final _release = Completer<void>();
|
||||
Future<void>? _lifetime;
|
||||
bool get canPlay => !_closed && !busy && _error == null && session != null;
|
||||
|
||||
Future<void>? _opening;
|
||||
Future<void>? _closing;
|
||||
Future<void> initialize(Future<void> beforeOpen) {
|
||||
if (_closed) return Future.error(StateError('Source preview is closed'));
|
||||
if (_opening case final pending?) return pending;
|
||||
final completion = Completer<void>();
|
||||
_opening = completion.future;
|
||||
_initialize(beforeOpen)
|
||||
.then(completion.complete, onError: completion.completeError);
|
||||
return completion.future;
|
||||
}
|
||||
|
||||
Future<void> _initialize(Future<void> beforeOpen) async {
|
||||
final ready = Completer<void>();
|
||||
_lifetime = () async {
|
||||
try {
|
||||
await beforeOpen;
|
||||
if (_closed) return;
|
||||
await loadMedia((media) async {
|
||||
try {
|
||||
if (_closed) return;
|
||||
if (media.isImage) {
|
||||
final image = await _loadStillImage(media);
|
||||
if (_closed) return;
|
||||
_aspectRatio = image.aspectRatio;
|
||||
_image = image.data;
|
||||
} else {
|
||||
final info = await runtime.probe(media);
|
||||
if (_closed) return;
|
||||
if (info.isProtected ||
|
||||
(info.videoTrackCount == 0 && info.audioTrackCount == 0)) {
|
||||
throw const RuntimeException(
|
||||
code: 'unpreviewableMedia',
|
||||
message: 'Media has no previewable audio or video tracks',
|
||||
);
|
||||
}
|
||||
final size =
|
||||
info.videoDisplaySizes.firstOrNull ?? RenderSize(1920, 1080);
|
||||
_audioOnly = info.videoTrackCount == 0;
|
||||
_aspectRatio = size.width / size.height;
|
||||
_durationTick =
|
||||
(info.duration.seconds * TimelineClock.ticksPerSecond)
|
||||
.floor();
|
||||
_positionTick = positionTick.clamp(0, durationTick);
|
||||
final created = await runtime.createSession();
|
||||
_session = created;
|
||||
if (_closed) return;
|
||||
_events = created.events.listen(
|
||||
(snapshot) {
|
||||
if (_closed) return;
|
||||
if (!_scrubbing &&
|
||||
_scrubEnd == null &&
|
||||
_interactiveSeeks == 0) {
|
||||
_positionTick =
|
||||
(snapshot.position.seconds *
|
||||
TimelineClock.ticksPerSecond)
|
||||
.round()
|
||||
.clamp(0, durationTick);
|
||||
}
|
||||
_playing = snapshot.state == PlaybackState.playing;
|
||||
if (snapshot.state == PlaybackState.failed) {
|
||||
_error = RuntimeException(
|
||||
code: 'playbackFailed',
|
||||
message: snapshot.message ?? 'Source preview failed',
|
||||
);
|
||||
}
|
||||
rememberPosition(positionTick);
|
||||
notifyListeners();
|
||||
},
|
||||
onError: (Object failure) {
|
||||
if (!_closed) {
|
||||
_error = failure;
|
||||
notifyListeners();
|
||||
}
|
||||
},
|
||||
);
|
||||
final start = positionTick;
|
||||
await created.load(
|
||||
sourcePreviewPlan(media, info, frameDuration, policy: policy),
|
||||
);
|
||||
if (_closed) return;
|
||||
await created.seek(
|
||||
MediaTime(start, TimelineClock.ticksPerSecond),
|
||||
);
|
||||
_positionTick = start;
|
||||
}
|
||||
if (_closed) return;
|
||||
_busy = false;
|
||||
notifyListeners();
|
||||
ready.complete();
|
||||
await _release.future;
|
||||
} finally {
|
||||
await completeCleanup([
|
||||
() async => _playback,
|
||||
() async => _scrubStart,
|
||||
() async => _scrubEnd,
|
||||
() async => _events?.cancel(),
|
||||
() async => session?.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
} catch (failure) {
|
||||
if (_closed) rethrow;
|
||||
if (!_closed) {
|
||||
_busy = false;
|
||||
_error = failure;
|
||||
notifyListeners();
|
||||
}
|
||||
} finally {
|
||||
if (!ready.isCompleted) ready.complete();
|
||||
}
|
||||
}();
|
||||
await ready.future;
|
||||
}
|
||||
|
||||
Future<({Uint8List data, double aspectRatio})> _loadStillImage(
|
||||
MediaReference media,
|
||||
) async {
|
||||
try {
|
||||
final thumbnail = await runtime.thumbnail(
|
||||
ThumbnailRequest(media: media, maximumWidth: 2048, maximumHeight: 2048),
|
||||
);
|
||||
final codec = await ui.instantiateImageCodec(thumbnail.data);
|
||||
try {
|
||||
final frame = await codec.getNextFrame();
|
||||
try {
|
||||
return (
|
||||
data: thumbnail.data,
|
||||
aspectRatio: frame.image.width / frame.image.height,
|
||||
);
|
||||
} finally {
|
||||
frame.image.dispose();
|
||||
}
|
||||
} finally {
|
||||
codec.dispose();
|
||||
}
|
||||
} catch (_) {
|
||||
if (kIsWeb || media.uri.scheme != 'file') rethrow;
|
||||
final bytes = await File.fromUri(media.uri).readAsBytes();
|
||||
final buffer = await ui.ImmutableBuffer.fromUint8List(bytes);
|
||||
try {
|
||||
final descriptor = await ui.ImageDescriptor.encoded(buffer);
|
||||
try {
|
||||
final scale = descriptor.width > descriptor.height
|
||||
? (2048 / descriptor.width).clamp(0.0, 1.0)
|
||||
: (2048 / descriptor.height).clamp(0.0, 1.0);
|
||||
final codec = await descriptor.instantiateCodec(
|
||||
targetWidth: (descriptor.width * scale).round().clamp(1, 2048),
|
||||
targetHeight: (descriptor.height * scale).round().clamp(1, 2048),
|
||||
);
|
||||
try {
|
||||
final frame = await codec.getNextFrame();
|
||||
try {
|
||||
final encoded = await frame.image.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
if (encoded == null) throw StateError('Could not encode image');
|
||||
return (
|
||||
data: encoded.buffer.asUint8List(),
|
||||
aspectRatio: descriptor.width / descriptor.height,
|
||||
);
|
||||
} finally {
|
||||
frame.image.dispose();
|
||||
}
|
||||
} finally {
|
||||
codec.dispose();
|
||||
}
|
||||
} finally {
|
||||
descriptor.dispose();
|
||||
}
|
||||
} finally {
|
||||
buffer.dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A host preparation failure changes state through this boundary.
|
||||
void reportFailure(Object failure, [StackTrace? stack]) {
|
||||
if (_closed) return;
|
||||
reportDiagnostic(
|
||||
runtime.diagnostics,
|
||||
DiagnosticEvent(
|
||||
component: 'preview',
|
||||
operation: 'sourceFailure',
|
||||
error: failure,
|
||||
stackTrace: stack,
|
||||
context: {'nativeSessionId': session?.id},
|
||||
),
|
||||
);
|
||||
_error = failure;
|
||||
_busy = false;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
bool _scrubbing = false;
|
||||
Future<void>? _scrubStart;
|
||||
Future<void>? _scrubEnd;
|
||||
|
||||
/// Uses the runtime's replaceable skim target, shared with timeline scrubbing.
|
||||
void beginScrubbing() {
|
||||
if (!canPlay || _scrubbing) return;
|
||||
_interactiveSeek = null;
|
||||
_scrubbing = true;
|
||||
final native = session!;
|
||||
final pendingEnd = _scrubEnd;
|
||||
_scrubStart = () async {
|
||||
await pendingEnd;
|
||||
await _playback;
|
||||
if (_closed) return;
|
||||
await native.beginSkimming(mode: policy.skimmingMode);
|
||||
}().catchError(_scrubFailed);
|
||||
}
|
||||
|
||||
void updateScrubbing(int tick) {
|
||||
if (!_scrubbing || _closed) return;
|
||||
final frameTick = TimelineClock.standard.toTicks(frameDuration);
|
||||
final last = durationTick > 0
|
||||
? ((durationTick - 1) ~/ frameTick) * frameTick
|
||||
: 0;
|
||||
_positionTick = tick.clamp(0, last);
|
||||
final native = session!;
|
||||
final start = _scrubStart;
|
||||
final time = MediaTime(_positionTick, TimelineClock.ticksPerSecond);
|
||||
unawaited(
|
||||
() async {
|
||||
await start;
|
||||
if (_closed || _error != null) return;
|
||||
await native.skim(time);
|
||||
}().catchError(_scrubFailed),
|
||||
);
|
||||
rememberPosition(_positionTick);
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
void endScrubbing() {
|
||||
if (!_scrubbing) return;
|
||||
_scrubbing = false;
|
||||
final native = session!;
|
||||
final start = _scrubStart;
|
||||
_scrubStart = null;
|
||||
final time = MediaTime(_positionTick, TimelineClock.ticksPerSecond);
|
||||
final ending = () async {
|
||||
await start;
|
||||
if (_closed || _error != null) return;
|
||||
await native.endSkimming(time);
|
||||
}().catchError(_scrubFailed);
|
||||
_scrubEnd = ending;
|
||||
unawaited(
|
||||
ending.whenComplete(() {
|
||||
if (identical(_scrubEnd, ending)) _scrubEnd = null;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
void _scrubFailed(Object error) {
|
||||
if (_closed || error is RuntimeException && error.code == 'cancelled') {
|
||||
return;
|
||||
}
|
||||
reportFailure(error);
|
||||
}
|
||||
|
||||
Future<void>? _playback;
|
||||
_InteractiveSourceSeek? _interactiveSeek;
|
||||
int _interactiveSeeks = 0;
|
||||
|
||||
/// UI navigation keeps one native seek and one replaceable next target.
|
||||
/// The returned future settles when this burst's final target has rendered.
|
||||
Future<void> seekInteractive(int requested) {
|
||||
if (!canPlay) {
|
||||
return Future.error(
|
||||
const CommandRejected('sourceNotReady', 'Source preview is not ready'),
|
||||
);
|
||||
}
|
||||
final frame = TimelineClock.standard.toTicks(frameDuration);
|
||||
final last = durationTick > 0 ? ((durationTick - 1) ~/ frame) * frame : 0;
|
||||
final tick = requested.clamp(0, last);
|
||||
if (_scrubbing) endScrubbing();
|
||||
var batch = _interactiveSeek;
|
||||
if (batch == null) {
|
||||
batch = _InteractiveSourceSeek();
|
||||
_interactiveSeek = batch;
|
||||
_interactiveSeeks++;
|
||||
final previous = _playback ?? Future<void>.value();
|
||||
final scrubEnd = _scrubEnd;
|
||||
final owned = batch;
|
||||
final pending = previous
|
||||
.then((_) async {
|
||||
try {
|
||||
await scrubEnd;
|
||||
while (owned.tick != null) {
|
||||
final target = owned.tick!;
|
||||
owned.tick = null;
|
||||
if (_closed || _error != null) {
|
||||
throw StateError('Source closed or failed during navigation');
|
||||
}
|
||||
await session!.seek(
|
||||
MediaTime(target, TimelineClock.ticksPerSecond),
|
||||
);
|
||||
if (_closed) {
|
||||
throw StateError('Source closed during navigation');
|
||||
}
|
||||
if (owned.tick == null &&
|
||||
_interactiveSeeks == 1 &&
|
||||
!_scrubbing &&
|
||||
_scrubEnd == null) {
|
||||
_positionTick = target;
|
||||
rememberPosition(target);
|
||||
}
|
||||
}
|
||||
} catch (failure) {
|
||||
if (!_closed) _error = failure;
|
||||
rethrow;
|
||||
}
|
||||
})
|
||||
.whenComplete(() {
|
||||
_interactiveSeeks--;
|
||||
if (identical(_interactiveSeek, owned)) _interactiveSeek = null;
|
||||
if (!_closed) notifyListeners();
|
||||
});
|
||||
owned.done = _trackPlayback(pending);
|
||||
}
|
||||
batch.tick = tick;
|
||||
_positionTick = tick;
|
||||
rememberPosition(tick);
|
||||
notifyListeners();
|
||||
return batch.done;
|
||||
}
|
||||
|
||||
Future<void> togglePlayback() {
|
||||
if (_interactiveSeek != null) {
|
||||
return control(
|
||||
playing ? SourcePreviewAction.pause : SourcePreviewAction.play,
|
||||
);
|
||||
}
|
||||
if (_playback case final pending?) return pending;
|
||||
if (!canPlay || _closed) return Future.value();
|
||||
final completion = Completer<void>();
|
||||
_playback = completion.future;
|
||||
_togglePlayback().then(
|
||||
(_) {
|
||||
_playback = null;
|
||||
completion.complete();
|
||||
},
|
||||
onError: (Object error, StackTrace stack) {
|
||||
_playback = null;
|
||||
completion.completeError(error, stack);
|
||||
},
|
||||
);
|
||||
return completion.future;
|
||||
}
|
||||
|
||||
Future<void> _togglePlayback() async {
|
||||
if (!canPlay || _closed) return;
|
||||
_busy = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
if (playing) {
|
||||
await session!.pause();
|
||||
} else {
|
||||
if (positionTick >= durationTick) await session!.seek(MediaTime(0, 1));
|
||||
if (!_closed) await session!.play();
|
||||
}
|
||||
} catch (failure) {
|
||||
if (!_closed) _error = failure;
|
||||
} finally {
|
||||
_busy = false;
|
||||
if (!_closed) notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Explicit controls reuse this player and are drained before media access releases.
|
||||
Future<void> control(SourcePreviewAction action, {CommandTime? at}) {
|
||||
// An exact command fences the interactive burst. Later UI targets enqueue
|
||||
// after it instead of changing targets that precede the command.
|
||||
_interactiveSeek = null;
|
||||
final previous = _playback ?? Future<void>.value();
|
||||
final pending = previous.then((_) async {
|
||||
if (_closed || !canPlay) {
|
||||
throw const CommandRejected(
|
||||
'sourceNotReady',
|
||||
'Source preview is not ready',
|
||||
);
|
||||
}
|
||||
if (action == SourcePreviewAction.seek && at == null ||
|
||||
action != SourcePreviewAction.seek && at != null ||
|
||||
!{
|
||||
SourcePreviewAction.play,
|
||||
SourcePreviewAction.pause,
|
||||
SourcePreviewAction.seek,
|
||||
}.contains(action)) {
|
||||
throw const CommandRejected(
|
||||
'invalidArguments',
|
||||
'Invalid source control',
|
||||
);
|
||||
}
|
||||
final tick = at == null
|
||||
? null
|
||||
: TimelineClock.standard.toTicks(
|
||||
RationalTime(at.numerator, at.denominator),
|
||||
);
|
||||
if (tick != null && tick > durationTick) {
|
||||
throw const CommandRejected(
|
||||
'invalidTime',
|
||||
'Seek exceeds source duration',
|
||||
);
|
||||
}
|
||||
_busy = true;
|
||||
notifyListeners();
|
||||
try {
|
||||
switch (action) {
|
||||
case SourcePreviewAction.play:
|
||||
if (positionTick >= durationTick) {
|
||||
await session!.seek(MediaTime(0, 1));
|
||||
}
|
||||
if (!_closed) await session!.play();
|
||||
case SourcePreviewAction.pause:
|
||||
await session!.pause();
|
||||
_playing = false;
|
||||
case SourcePreviewAction.seek:
|
||||
await session!.seek(MediaTime(at!.numerator, at.denominator));
|
||||
if (!_closed) {
|
||||
_positionTick = tick!;
|
||||
rememberPosition(tick);
|
||||
}
|
||||
default:
|
||||
throw StateError('Unreachable source action');
|
||||
}
|
||||
} catch (failure) {
|
||||
if (!_closed) _error = failure;
|
||||
rethrow;
|
||||
} finally {
|
||||
_busy = false;
|
||||
if (!_closed) notifyListeners();
|
||||
}
|
||||
if (_closed) throw StateError('Source closed during control');
|
||||
});
|
||||
return _trackPlayback(pending);
|
||||
}
|
||||
|
||||
Future<void> _trackPlayback(Future<void> pending) {
|
||||
_playback = pending;
|
||||
unawaited(
|
||||
pending.then<void>(
|
||||
(_) {
|
||||
if (identical(_playback, pending)) _playback = null;
|
||||
},
|
||||
onError: (Object _, StackTrace _) {
|
||||
if (identical(_playback, pending)) _playback = null;
|
||||
},
|
||||
),
|
||||
);
|
||||
return pending;
|
||||
}
|
||||
|
||||
Future<void> close() {
|
||||
if (_closing case final pending?) return pending;
|
||||
final completion = Completer<void>();
|
||||
_closing = completion.future;
|
||||
_closed = true;
|
||||
completeCleanup([
|
||||
() => rememberPosition(positionTick),
|
||||
_release.complete,
|
||||
() async => _lifetime,
|
||||
]).then(completion.complete, onError: completion.completeError);
|
||||
return completion.future;
|
||||
}
|
||||
}
|
||||
|
||||
class _InteractiveSourceSeek {
|
||||
int? tick;
|
||||
late final Future<void> done;
|
||||
}
|
||||
|
||||
ExecutionPlan sourcePreviewPlan(
|
||||
MediaReference media,
|
||||
MediaInfo info,
|
||||
RationalTime frame, {
|
||||
PreviewPolicy policy = const PreviewPolicy(),
|
||||
}) {
|
||||
final range = MediaRange(start: MediaTime(0, 1), duration: info.duration);
|
||||
final audio = info.audioTracks.firstOrNull;
|
||||
MediaRange? audioRange;
|
||||
if (audio != null) {
|
||||
final assetEnd = RationalTime(
|
||||
info.duration.numerator,
|
||||
info.duration.denominator,
|
||||
);
|
||||
final start = RationalTime(audio.start.numerator, audio.start.denominator);
|
||||
final end =
|
||||
start +
|
||||
RationalTime(audio.duration.numerator, audio.duration.denominator);
|
||||
final clippedStart = start.isNegative ? RationalTime.zero : start;
|
||||
final clippedEnd = end.compareTo(assetEnd) > 0 ? assetEnd : end;
|
||||
if (clippedEnd.compareTo(clippedStart) > 0) {
|
||||
final duration = clippedEnd - clippedStart;
|
||||
audioRange = MediaRange(
|
||||
start: MediaTime(clippedStart.numerator, clippedStart.denominator),
|
||||
duration: MediaTime(duration.numerator, duration.denominator),
|
||||
);
|
||||
}
|
||||
}
|
||||
return ExecutionPlan(
|
||||
duration: info.duration,
|
||||
toneMapping:
|
||||
{
|
||||
RenderColorSpace.rec2020HLG,
|
||||
RenderColorSpace.rec2020PQ,
|
||||
RenderColorSpace.linearRec2020,
|
||||
}.contains(info.videoColorSpaces.firstOrNull)
|
||||
? policy.toneMapping
|
||||
: const RenderToneMapping.none(),
|
||||
renderSize: info.videoDisplaySizes.firstOrNull ?? RenderSize(1920, 1080),
|
||||
frameDuration: MediaTime(frame.numerator, frame.denominator),
|
||||
media: [media],
|
||||
visualLayers: [
|
||||
if (info.videoTrackCount > 0)
|
||||
VisualLayer(
|
||||
id: 'source-video',
|
||||
mediaId: media.id,
|
||||
sourceRange: range,
|
||||
timelineRange: range,
|
||||
inputColorSpace:
|
||||
info.videoColorSpaces.firstOrNull ??
|
||||
(info.videoColorSpaces.isNotEmpty
|
||||
? policy.unknownVideoColorSpace
|
||||
: null),
|
||||
),
|
||||
],
|
||||
audioLayers: [
|
||||
if (audioRange != null)
|
||||
AudioLayer(
|
||||
id: 'source-audio',
|
||||
mediaId: media.id,
|
||||
sourceRange: audioRange,
|
||||
timelineRange: audioRange,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
name: cutdex_preview
|
||||
description: Native preview lifecycle, playback and Flutter canvas interactions.
|
||||
version: 0.1.0
|
||||
publish_to: none
|
||||
resolution: workspace
|
||||
environment:
|
||||
sdk: ^3.13.2
|
||||
dependencies:
|
||||
cutdex_native_flutter:
|
||||
path: ../../.dependencies/cutdex_core/native_flutter
|
||||
cutdex_core:
|
||||
path: ../../.dependencies/cutdex_core
|
||||
flutter:
|
||||
sdk: flutter
|
||||
cutdex_timeline_ui:
|
||||
path: ../cutdex_timeline_ui
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
sdk: flutter
|
||||
flutter_lints: ^6.0.0
|
||||
@@ -0,0 +1,590 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/project.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/engine.dart';
|
||||
import 'package:cutdex_core/timeline/layout.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
|
||||
for (final scenario in [
|
||||
'initialize',
|
||||
'concurrent initialize',
|
||||
'close during create',
|
||||
'clear active sequence',
|
||||
'single timeline seek',
|
||||
'rapid timeline seeks',
|
||||
'cancelled timeline seek',
|
||||
'superseded seek cancellations',
|
||||
'cancelled plan update',
|
||||
'recover plan update',
|
||||
'edit during recovery',
|
||||
'recovery fails',
|
||||
'recovery remains required',
|
||||
'native failure message',
|
||||
'native failure snapshots preserve command error',
|
||||
'playhead drag skims and settles',
|
||||
'cancelled drag release',
|
||||
'clear active sequence during drag',
|
||||
'cancelled skim during sequence clear',
|
||||
'close during play',
|
||||
]) {
|
||||
test(scenario, () async {
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
const events = MethodChannel('cutdex_runtime/sessions/preview-sdk');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final calls = <MethodCall>[];
|
||||
final creating = Completer<void>();
|
||||
final nativePlay = Completer<void>();
|
||||
final nativeSeek = Completer<void>();
|
||||
final nativeRecovery = Completer<void>();
|
||||
var seekCalls = 0;
|
||||
var cancelNextSeek = false;
|
||||
var failNextSeek = false;
|
||||
var cancelNextEndSkimming = false;
|
||||
var cancelNextPatch = false;
|
||||
var recoveryRequired = false;
|
||||
var nativeRevision = 0;
|
||||
var advanceCancelledSeek = false;
|
||||
var cancelledSeekCount = 0;
|
||||
void Function(int)? advanceSeek;
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls.add(call);
|
||||
if (scenario == 'close during create' &&
|
||||
call.method == 'createSession') {
|
||||
await creating.future;
|
||||
}
|
||||
if (scenario == 'close during play' && call.method == 'play') {
|
||||
await nativePlay.future;
|
||||
}
|
||||
if (scenario == 'rapid timeline seeks' &&
|
||||
call.method == 'seek' &&
|
||||
++seekCalls == 1) {
|
||||
await nativeSeek.future;
|
||||
}
|
||||
if (call.method == 'seek' && failNextSeek) {
|
||||
failNextSeek = false;
|
||||
throw PlatformException(
|
||||
code: 'failed',
|
||||
message: 'Native video decoder returned no frame',
|
||||
details: {
|
||||
'domain': 'render',
|
||||
'code': 'failed',
|
||||
'platformDetails': {
|
||||
'nativeDomain': 'CutdexMedia.CutdexMediaError',
|
||||
'nativeCode': 3,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
if (call.method == 'seek' && cancelNextSeek) {
|
||||
cancelNextSeek = false;
|
||||
throw PlatformException(
|
||||
code: 'cancelled',
|
||||
message: 'Seek superseded',
|
||||
);
|
||||
}
|
||||
if (call.method == 'seek' && advanceCancelledSeek) {
|
||||
cancelledSeekCount++;
|
||||
if (cancelledSeekCount <= 3) {
|
||||
scheduleMicrotask(
|
||||
() => advanceSeek?.call((cancelledSeekCount + 1) * 100),
|
||||
);
|
||||
throw PlatformException(
|
||||
code: 'cancelled',
|
||||
message: 'Seek superseded',
|
||||
);
|
||||
}
|
||||
}
|
||||
if (call.method == 'endSkimming' && cancelNextEndSkimming) {
|
||||
cancelNextEndSkimming = false;
|
||||
throw PlatformException(
|
||||
code: 'cancelled',
|
||||
message: 'Skim superseded',
|
||||
);
|
||||
}
|
||||
if (call.method == 'recover') {
|
||||
if (scenario == 'edit during recovery') {
|
||||
await nativeRecovery.future;
|
||||
}
|
||||
if (scenario == 'recovery fails') {
|
||||
throw PlatformException(
|
||||
code: 'invalidState',
|
||||
message: 'Playback is still suspended',
|
||||
details: {'domain': 'playback'},
|
||||
);
|
||||
}
|
||||
recoveryRequired = scenario == 'recovery remains required';
|
||||
}
|
||||
if (recoveryRequired && {'load', 'applyPatch'}.contains(call.method)) {
|
||||
throw PlatformException(
|
||||
code: 'invalidState',
|
||||
message:
|
||||
'Recover playback before replacing its plan or configuration',
|
||||
details: {'domain': 'playback'},
|
||||
);
|
||||
}
|
||||
if (call.method == 'applyPatch' && cancelNextPatch) {
|
||||
cancelNextPatch = false;
|
||||
throw PlatformException(
|
||||
code: 'cancelled',
|
||||
message: 'Plan superseded',
|
||||
);
|
||||
}
|
||||
return switch (call.method) {
|
||||
'capabilities' => {
|
||||
'contractVersion': 1,
|
||||
'features': {'playback.preview': 'available'},
|
||||
},
|
||||
'createSession' => {'sessionId': 'preview-sdk'},
|
||||
'snapshot' => {
|
||||
'state': 'paused',
|
||||
'revision': '$nativeRevision',
|
||||
'position': {'numerator': '0', 'denominator': 1},
|
||||
'rate': 0.0,
|
||||
'lifecycle': {
|
||||
'suspensions': <String>[],
|
||||
'requiresRecovery': recoveryRequired,
|
||||
'requiresNativeRebuild': recoveryRequired,
|
||||
'version': '1',
|
||||
},
|
||||
},
|
||||
'load' => '${++nativeRevision}',
|
||||
'applyPatch' =>
|
||||
'${nativeRevision = int.parse((call.arguments as Map)['patch']['revision'] as String)}',
|
||||
_ => null,
|
||||
};
|
||||
});
|
||||
messenger.setMockMethodCallHandler(events, (call) async {
|
||||
if (call.method == 'listen') {
|
||||
scheduleMicrotask(
|
||||
() => messenger.handlePlatformMessage(
|
||||
events.name,
|
||||
const StandardMethodCodec().encodeSuccessEnvelope({
|
||||
'type': 'attached',
|
||||
}),
|
||||
(_) {},
|
||||
),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
addTearDown(() {
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
messenger.setMockMethodCallHandler(events, null);
|
||||
});
|
||||
final directory = await Directory.systemTemp.createTemp('sdk-preview-');
|
||||
final library = await ProjectFile.create(
|
||||
Directory('${directory.path}/test.cutdex'),
|
||||
name: 'Preview',
|
||||
);
|
||||
await library.saveAsset(
|
||||
AssetDocument(
|
||||
id: 'asset',
|
||||
name: 'test.png',
|
||||
storage: AssetStorage.external,
|
||||
location: 'file:///test.png',
|
||||
),
|
||||
);
|
||||
final sequence = SequenceId('one');
|
||||
SequenceId? selectedSequence = sequence;
|
||||
final clip = ElementId('clip');
|
||||
await library.saveTimeline(
|
||||
TimelineDocument(
|
||||
id: 'project',
|
||||
name: 'Preview',
|
||||
defaultSequenceId: sequence,
|
||||
payloads: [
|
||||
PayloadDocument(id: 'image', type: 'image', assetIds: ['asset']),
|
||||
],
|
||||
sequences: [
|
||||
TimelineKernel.importDto(
|
||||
TimelineDto(
|
||||
id: sequence,
|
||||
format: TimelineFormat.fps30,
|
||||
primaryStorylineId: StorylineId('primary'),
|
||||
storylines: [
|
||||
StorylineDto(id: StorylineId('primary'), elementIds: [clip]),
|
||||
],
|
||||
elements: [
|
||||
ElementDto(
|
||||
id: clip,
|
||||
structure: ElementStructure.content,
|
||||
duration: RationalTime.seconds(2),
|
||||
sourceRange: TimeRange(
|
||||
start: RationalTime.zero,
|
||||
duration: RationalTime.seconds(2),
|
||||
),
|
||||
payloadRef: PayloadRef('image'),
|
||||
),
|
||||
],
|
||||
),
|
||||
).exportDto(),
|
||||
],
|
||||
),
|
||||
);
|
||||
final editor = EditorSession(
|
||||
document: await library.loadTimeline('project'),
|
||||
persistence: await library.openTimelineSaveSession('project'),
|
||||
assetUris: {'asset': Uri.parse('file:///test.png')},
|
||||
);
|
||||
final view = TimelineViewController.editable(
|
||||
engine: editor.layout(sequence),
|
||||
geometry: TimelineViewportGeometry(primaryTop: 48, primaryHeight: 72),
|
||||
camera: TimelineCamera(baseTick: 0, pixelsPerTick: 1),
|
||||
createConnectionId: () => ConnectionId('new-connection'),
|
||||
createElementId: () => ElementId('new-element'),
|
||||
commitEdit: <T>(T Function() action) => editor.commit(sequence, action),
|
||||
);
|
||||
advanceSeek = view.seekTo;
|
||||
final preview = PreviewController(
|
||||
timeline: editor,
|
||||
runtime: CutdexRuntime(),
|
||||
activeSequence: () => selectedSequence,
|
||||
viewForSequence: (_) => view,
|
||||
);
|
||||
addTearDown(() async {
|
||||
await preview.close();
|
||||
view.dispose();
|
||||
await editor.close();
|
||||
await library.close();
|
||||
await directory.delete(recursive: true);
|
||||
});
|
||||
if (scenario == 'close during create') {
|
||||
final opening = preview.initialize();
|
||||
while (!calls.any((c) => c.method == 'createSession')) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
var closed = false;
|
||||
final closing = preview.close().then((_) => closed = true);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
final closedBeforeNative = closed;
|
||||
creating.complete();
|
||||
await opening;
|
||||
await closing;
|
||||
expect(
|
||||
closedBeforeNative,
|
||||
isFalse,
|
||||
reason: 'close must retain native ownership through startup',
|
||||
);
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
return;
|
||||
}
|
||||
if (scenario == 'concurrent initialize') {
|
||||
await Future.wait([preview.initialize(), preview.initialize()]);
|
||||
} else {
|
||||
await preview.initialize();
|
||||
}
|
||||
expect(preview.error, isNull);
|
||||
expect(calls.where((c) => c.method == 'createSession'), hasLength(1));
|
||||
expect(calls.where((c) => c.method == 'load'), hasLength(1));
|
||||
if (scenario == 'native failure snapshots preserve command error') {
|
||||
failNextSeek = true;
|
||||
view.seekTo(100);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
expect(preview.error.toString(), contains('render/failed'));
|
||||
final originalError = preview.error;
|
||||
var notifications = 0;
|
||||
preview.addListener(() => notifications++);
|
||||
for (var index = 0; index < 3; index++) {
|
||||
messenger.handlePlatformMessage(
|
||||
events.name,
|
||||
const StandardMethodCodec().encodeSuccessEnvelope({
|
||||
'state': 'failed',
|
||||
'revision': '1',
|
||||
'position': {'numerator': '0', 'denominator': 1},
|
||||
'rate': 0.0,
|
||||
'message': 'Native video decoder returned no frame',
|
||||
}),
|
||||
(_) {},
|
||||
);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
expect(preview.error, same(originalError));
|
||||
expect(notifications, 0);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'native failure message') {
|
||||
messenger.handlePlatformMessage(
|
||||
events.name,
|
||||
const StandardMethodCodec().encodeSuccessEnvelope({
|
||||
'state': 'failed',
|
||||
'revision': '1',
|
||||
'position': {'numerator': '0', 'denominator': 1},
|
||||
'rate': 0.0,
|
||||
'message': 'Decode failed: invalid data',
|
||||
}),
|
||||
(_) {},
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
expect(
|
||||
preview.error.toString(),
|
||||
contains('Decode failed: invalid data'),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'single timeline seek') {
|
||||
final before = calls.where((c) => c.method == 'seek').length;
|
||||
view.seekTo(100);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 160));
|
||||
final seeks = calls.where((c) => c.method == 'seek').toList();
|
||||
expect(seeks, hasLength(before + 1));
|
||||
expect((seeks.last.arguments as Map)['policy'], 'exact');
|
||||
expect((seeks.last.arguments as Map).containsKey('exact'), isFalse);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'rapid timeline seeks') {
|
||||
view.seekTo(100);
|
||||
while (seekCalls == 0) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
view.seekTo(200);
|
||||
view.seekTo(300);
|
||||
nativeSeek.complete();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
final seeks = calls.where((call) => call.method == 'seek').toList();
|
||||
expect(seeks, hasLength(2));
|
||||
expect((seeks.last.arguments as Map)['time'], {
|
||||
'numerator': '300',
|
||||
'denominator': TimelineClock.ticksPerSecond,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (scenario == 'cancelled timeline seek') {
|
||||
cancelNextSeek = true;
|
||||
final before = calls.where((call) => call.method == 'seek').length;
|
||||
view.seekTo(100);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
expect(preview.error, isNull);
|
||||
expect(
|
||||
calls.where((call) => call.method == 'seek'),
|
||||
hasLength(before + 2),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'superseded seek cancellations') {
|
||||
advanceCancelledSeek = true;
|
||||
view.seekTo(100);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 40));
|
||||
expect(preview.error, isNull);
|
||||
expect(cancelledSeekCount, 4);
|
||||
expect(view.playheadTick, 400);
|
||||
return;
|
||||
}
|
||||
if ({
|
||||
'recover plan update',
|
||||
'edit during recovery',
|
||||
'recovery fails',
|
||||
'recovery remains required',
|
||||
}.contains(scenario)) {
|
||||
// No failed snapshot: lifecycle events may leave playback paused and
|
||||
// command replies may arrive before the event channel catches up.
|
||||
recoveryRequired = true;
|
||||
editor.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: 25),
|
||||
);
|
||||
if (scenario == 'edit during recovery') {
|
||||
for (
|
||||
var attempt = 0;
|
||||
attempt < 100 && !calls.any((call) => call.method == 'recover');
|
||||
attempt++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
final before = calls.length;
|
||||
editor.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: 50),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
final pendingPlanCalls = calls
|
||||
.skip(before)
|
||||
.where((call) => {'load', 'applyPatch'}.contains(call.method))
|
||||
.length;
|
||||
nativeRecovery.complete();
|
||||
expect(pendingPlanCalls, 0);
|
||||
}
|
||||
await Future<void>.delayed(const Duration(milliseconds: 80));
|
||||
expect(calls.where((call) => call.method == 'recover'), hasLength(1));
|
||||
expect(preview.busy, isFalse);
|
||||
if (scenario == 'recover plan update' ||
|
||||
scenario == 'edit during recovery') {
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.ready, isTrue);
|
||||
final methods = calls.map((call) => call.method).toList();
|
||||
expect(
|
||||
methods.indexOf('recover'),
|
||||
greaterThan(methods.indexOf('applyPatch')),
|
||||
);
|
||||
expect(
|
||||
methods.lastIndexOf('applyPatch'),
|
||||
greaterThan(methods.indexOf('recover')),
|
||||
);
|
||||
} else {
|
||||
expect(preview.ready, isFalse);
|
||||
expect(
|
||||
preview.error.toString(),
|
||||
contains(
|
||||
scenario == 'recovery fails'
|
||||
? 'Playback is still suspended'
|
||||
: 'Playback recovery did not restore availability',
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (scenario == 'cancelled plan update') {
|
||||
cancelNextPatch = true;
|
||||
editor.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: 25),
|
||||
);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 40));
|
||||
expect(preview.error, isNull);
|
||||
expect(preview.ready, isTrue);
|
||||
expect(
|
||||
calls.where((call) => call.method == 'applyPatch'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(calls.where((call) => call.method == 'load'), hasLength(2));
|
||||
return;
|
||||
}
|
||||
if (scenario == 'playhead drag skims and settles') {
|
||||
view.beginScrubbing();
|
||||
view.seekTo(100);
|
||||
view.seekTo(200);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
view.endScrubbing();
|
||||
for (
|
||||
var attempt = 0;
|
||||
attempt < 100 && !calls.any((call) => call.method == 'endSkimming');
|
||||
attempt++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
expect(
|
||||
calls.where((call) => call.method == 'beginSkimming'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(
|
||||
(calls.singleWhere((call) => call.method == 'beginSkimming').arguments
|
||||
as Map)['mode'],
|
||||
'audible',
|
||||
);
|
||||
expect(calls.any((call) => call.method == 'skim'), isTrue);
|
||||
expect(
|
||||
calls.where((call) => call.method == 'endSkimming'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(calls.where((call) => call.method == 'seek'), isEmpty);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'cancelled drag release') {
|
||||
cancelNextEndSkimming = true;
|
||||
view.beginScrubbing();
|
||||
view.seekTo(100);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 10));
|
||||
view.endScrubbing();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 30));
|
||||
expect(preview.error, isNull);
|
||||
expect(
|
||||
calls.where((call) => call.method == 'endSkimming'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(calls.where((call) => call.method == 'seek'), isNotEmpty);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'clear active sequence during drag' ||
|
||||
scenario == 'cancelled skim during sequence clear') {
|
||||
view.beginScrubbing();
|
||||
view.seekTo(100);
|
||||
for (
|
||||
var attempt = 0;
|
||||
attempt < 100 && !calls.any((call) => call.method == 'skim');
|
||||
attempt++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
cancelNextEndSkimming =
|
||||
scenario == 'cancelled skim during sequence clear';
|
||||
selectedSequence = null;
|
||||
editor.notifyListeners();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
expect(
|
||||
calls.where((call) => call.method == 'endSkimming'),
|
||||
hasLength(1),
|
||||
);
|
||||
expect(preview.error, isNull);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'close during play') {
|
||||
final playing = preview.togglePlayback();
|
||||
while (!calls.any((c) => c.method == 'play')) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
final closing = preview.close();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
final closedDuringPlayback = calls.any((c) => c.method == 'close');
|
||||
nativePlay.complete();
|
||||
await Future.wait([playing, closing]);
|
||||
expect(closedDuringPlayback, isFalse);
|
||||
return;
|
||||
}
|
||||
if (scenario == 'clear active sequence') {
|
||||
selectedSequence = null;
|
||||
editor.notifyListeners();
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(preview.durationTick, 0);
|
||||
expect(preview.ready, isFalse);
|
||||
expect(preview.canPlay, isFalse);
|
||||
expect(preview.visuals, isEmpty);
|
||||
final seeks = calls.where((c) => c.method == 'seek').length;
|
||||
view.seekTo(100);
|
||||
await Future<void>.delayed(const Duration(milliseconds: 60));
|
||||
expect(calls.where((c) => c.method == 'seek'), hasLength(seeks));
|
||||
return;
|
||||
}
|
||||
editor.commands.setTransform(
|
||||
sequence: sequence,
|
||||
clip: clip,
|
||||
tick: 0,
|
||||
change: (value) => value.copyWith(x: 25),
|
||||
);
|
||||
for (
|
||||
var attempt = 0;
|
||||
attempt < 100 && !calls.any((c) => c.method == 'applyPatch');
|
||||
attempt++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
}
|
||||
expect(calls.where((c) => c.method == 'applyPatch'), hasLength(1));
|
||||
expect(calls.where((c) => c.method == 'createSession'), hasLength(1));
|
||||
expect(calls.where((c) => c.method == 'load'), hasLength(1));
|
||||
await preview.close();
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
expect(editor.acceptsEdits, isTrue);
|
||||
final previous = editor.version;
|
||||
editor.commands.setCanvas(const ProjectCanvas(800, 600));
|
||||
expect(editor.version, isNot(previous));
|
||||
// Closing preview neither disposes the host view nor its project session.
|
||||
view.seekTo(10);
|
||||
expect(view.playheadTick, 10);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
import 'package:cutdex_core/execution.dart';
|
||||
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('grouped geometry hit testing, alignment and corner drags use output coordinates', () {
|
||||
RenderAutomation scalar(String target, double value) =>
|
||||
RenderAutomation(target: target, defaultValue: value);
|
||||
const canvas = Size(200, 100);
|
||||
final evaluated = ExecutionEvaluator().visualAt(
|
||||
VisualLayer(
|
||||
id: 'clip',
|
||||
mediaId: 'media',
|
||||
sourceRange: MediaRange(
|
||||
start: MediaTime(0, 1),
|
||||
duration: MediaTime(10, 1),
|
||||
),
|
||||
timelineRange: MediaRange(
|
||||
start: MediaTime(0, 1),
|
||||
duration: MediaTime(10, 1),
|
||||
),
|
||||
groups: [
|
||||
RenderCompositingGroup(
|
||||
id: 'outer',
|
||||
automation: [scalar('scale.x', 2)],
|
||||
),
|
||||
RenderCompositingGroup(
|
||||
id: 'inner',
|
||||
automation: [scalar('rotation', 37)],
|
||||
),
|
||||
],
|
||||
),
|
||||
seconds: 0,
|
||||
source: RenderSize(20, 10),
|
||||
canvas: RenderSize(200, 100),
|
||||
);
|
||||
final visual = PreviewVisual(
|
||||
layerId: 'clip',
|
||||
elementId: ElementId('clip'),
|
||||
lane: 0,
|
||||
transform: const ClipTransform(),
|
||||
geometry: PreviewGeometry.fromExecution(evaluated),
|
||||
);
|
||||
final geometry = visual.geometry;
|
||||
expect(geometry.contains(geometry.center), isTrue);
|
||||
expect(
|
||||
geometry.contains(geometry.bounds.topLeft + const Offset(.1, .1)),
|
||||
isFalse,
|
||||
);
|
||||
for (var corner = 0; corner < 4; corner++) {
|
||||
final points = geometry.corners;
|
||||
final fixed = points[(corner + 2) % 4];
|
||||
final target = fixed + (points[corner] - fixed) * 1.5;
|
||||
final value = scaleFromCorner(visual, corner, target, canvas);
|
||||
final after = geometry.changed(visual.transform, value, canvas);
|
||||
expect(
|
||||
(after.corners[(corner + 2) % 4] - fixed).distance,
|
||||
lessThan(1e-8),
|
||||
);
|
||||
expect((after.corners[corner] - target).distance, lessThan(1e-8));
|
||||
final edgeX =
|
||||
(points[1] - points[0]) * (corner == 0 || corner == 3 ? -1 : 1);
|
||||
final edgeY = (points[3] - points[0]) * (corner < 2 ? -1 : 1);
|
||||
final freeTarget = fixed + edgeX * 1.7 + edgeY * .8;
|
||||
final free = scaleFromCorner(
|
||||
visual,
|
||||
corner,
|
||||
freeTarget,
|
||||
canvas,
|
||||
locked: false,
|
||||
);
|
||||
final resized = geometry.changed(visual.transform, free, canvas);
|
||||
expect(free.scale, closeTo(1.7, 1e-9));
|
||||
expect(free.scaleY, closeTo(.8, 1e-9));
|
||||
expect((resized.corners[corner] - freeTarget).distance, lessThan(1e-8));
|
||||
expect(
|
||||
(resized.corners[(corner + 2) % 4] - fixed).distance,
|
||||
lessThan(1e-8),
|
||||
);
|
||||
}
|
||||
final aligned = alignToCanvas(visual, canvas, CanvasAlignment.left);
|
||||
expect(
|
||||
geometry.changed(visual.transform, aligned, canvas).bounds.left,
|
||||
closeTo(0, 1e-9),
|
||||
);
|
||||
});
|
||||
test('corner snapping preserves opposite anchor and scale lock', () {
|
||||
const canvas = Size(1000, 600);
|
||||
final visual = PreviewVisual(
|
||||
layerId: 'clip',
|
||||
elementId: ElementId('clip'),
|
||||
lane: 0,
|
||||
transform: const ClipTransform(),
|
||||
geometry: const PreviewGeometry(
|
||||
center: Offset(500, 300),
|
||||
size: Size(300, 200),
|
||||
),
|
||||
);
|
||||
final fixed = visual.geometry.corners[0];
|
||||
final target = fixed + const Offset(647, 431.3333333333333);
|
||||
final (locked, snap) = snapScaleToCanvas(
|
||||
visual,
|
||||
2,
|
||||
target,
|
||||
canvas,
|
||||
6,
|
||||
locked: true,
|
||||
);
|
||||
final after = visual.geometry.changed(visual.transform, locked, canvas);
|
||||
expect(after.bounds.right, closeTo(1000, 1e-9));
|
||||
expect(locked.scale, closeTo(locked.scaleY, 1e-9));
|
||||
expect((after.corners[0] - fixed).distance, lessThan(1e-9));
|
||||
expect(snap.verticalGuides, contains(1000));
|
||||
final (free, _) = snapScaleToCanvas(
|
||||
visual,
|
||||
2,
|
||||
const Offset(997, 597),
|
||||
canvas,
|
||||
6,
|
||||
locked: false,
|
||||
);
|
||||
final freeGeometry = visual.geometry.changed(
|
||||
visual.transform,
|
||||
free,
|
||||
canvas,
|
||||
);
|
||||
expect(freeGeometry.bounds.bottomRight, const Offset(1000, 600));
|
||||
expect(freeGeometry.corners[0], fixed);
|
||||
expect(free.scale, isNot(closeTo(free.scaleY, 1e-6)));
|
||||
});
|
||||
test(
|
||||
'independent scale survives corner drags and all rotated alignments',
|
||||
() {
|
||||
const canvas = Size(1920, 1080);
|
||||
final visual = PreviewVisual(
|
||||
layerId: 'video',
|
||||
elementId: ElementId('clip'),
|
||||
lane: 0,
|
||||
transform: const ClipTransform(scale: 2, scaleY: .5, rotation: 37),
|
||||
geometry: const PreviewGeometry(
|
||||
center: Offset(700, 400),
|
||||
size: Size(800, 150),
|
||||
rotation: 37,
|
||||
),
|
||||
);
|
||||
final points = visual.geometry.selectionCorners;
|
||||
final value = scaleFromCorner(
|
||||
visual,
|
||||
0,
|
||||
points[2] + (points[0] - points[2]) * 2,
|
||||
canvas,
|
||||
);
|
||||
expect(value.scale, closeTo(4, 1e-9));
|
||||
expect(value.scaleY, closeTo(1, 1e-9));
|
||||
final changed = visual.geometry.changed(visual.transform, value, canvas);
|
||||
expect(changed.size.aspectRatio, closeTo(800 / 150, 1e-9));
|
||||
for (final alignment in CanvasAlignment.values) {
|
||||
final aligned = alignToCanvas(visual, canvas, alignment);
|
||||
final bounds = visual.geometry
|
||||
.changed(visual.transform, aligned, canvas)
|
||||
.bounds;
|
||||
final coordinate = switch (alignment) {
|
||||
CanvasAlignment.left => bounds.left,
|
||||
CanvasAlignment.horizontalCenter =>
|
||||
bounds.center.dx - canvas.width / 2,
|
||||
CanvasAlignment.right => bounds.right - canvas.width,
|
||||
CanvasAlignment.top => bounds.top,
|
||||
CanvasAlignment.verticalCenter =>
|
||||
bounds.center.dy - canvas.height / 2,
|
||||
CanvasAlignment.bottom => bounds.bottom - canvas.height,
|
||||
};
|
||||
expect(coordinate, closeTo(0, 1e-9));
|
||||
expect(aligned.scaleY, .5);
|
||||
expect(aligned.rotation, 37);
|
||||
}
|
||||
expect(const ClipTransform(scaleY: 0).isValid, isFalse);
|
||||
expect(const ClipTransform(scaleY: double.nan).isValid, isFalse);
|
||||
},
|
||||
);
|
||||
test('all four video corners scale around their opposite after rotation', () {
|
||||
const canvas = Size(1920, 1080);
|
||||
for (final angle in [0.0, 37.0, 90.0, -133.0]) {
|
||||
final visual = PreviewVisual(
|
||||
layerId: 'video',
|
||||
elementId: ElementId('clip'),
|
||||
lane: 0,
|
||||
transform: ClipTransform(rotation: angle),
|
||||
geometry: PreviewGeometry(
|
||||
center: const Offset(960, 540),
|
||||
size: const Size(600, 400),
|
||||
rotation: angle,
|
||||
),
|
||||
);
|
||||
for (var corner = 0; corner < 4; corner++) {
|
||||
final points = visual.geometry.corners;
|
||||
final fixed = points[(corner + 2) % 4];
|
||||
final pointer = fixed + (points[corner] - fixed) * 1.5;
|
||||
final value = scaleFromCorner(visual, corner, pointer, canvas);
|
||||
final after = visual.geometry.changed(visual.transform, value, canvas);
|
||||
expect(value.scale, closeTo(1.5, 1e-9));
|
||||
final resized = after.corners;
|
||||
expect((resized[(corner + 2) % 4] - fixed).distance, lessThan(1e-8));
|
||||
expect((resized[corner] - pointer).distance, lessThan(1e-8));
|
||||
expect(value.rotation, angle);
|
||||
expect(after.size.aspectRatio, visual.geometry.size.aspectRatio);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test(
|
||||
'all six canvas guides snap within tolerance and reject distant points',
|
||||
() {
|
||||
const canvas = Size(1000, 600);
|
||||
for (final x in [103.0, 503.0, 903.0]) {
|
||||
final snap = snapToCanvas(
|
||||
PreviewGeometry(center: Offset(x, 250), size: const Size(200, 100)),
|
||||
canvas,
|
||||
6,
|
||||
);
|
||||
expect(snap.verticalGuides, [
|
||||
x == 103
|
||||
? 0
|
||||
: x == 503
|
||||
? 500
|
||||
: 1000,
|
||||
]);
|
||||
expect(snap.delta.dx, -3);
|
||||
}
|
||||
for (final y in [53.0, 303.0, 553.0]) {
|
||||
final snap = snapToCanvas(
|
||||
PreviewGeometry(center: Offset(340, y), size: const Size(200, 100)),
|
||||
canvas,
|
||||
6,
|
||||
);
|
||||
expect(snap.horizontalGuides, [
|
||||
y == 53
|
||||
? 0
|
||||
: y == 303
|
||||
? 300
|
||||
: 600,
|
||||
]);
|
||||
expect(snap.delta.dy, -3);
|
||||
}
|
||||
final far = snapToCanvas(
|
||||
const PreviewGeometry(center: Offset(340, 220), size: Size(200, 100)),
|
||||
canvas,
|
||||
6,
|
||||
);
|
||||
expect(far.verticalGuides, isEmpty);
|
||||
expect(far.horizontalGuides, isEmpty);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'a full canvas shows all six alignments without choosing just one guide',
|
||||
() {
|
||||
final snap = snapToCanvas(
|
||||
const PreviewGeometry(center: Offset(503, 298), size: Size(1000, 600)),
|
||||
const Size(1000, 600),
|
||||
6,
|
||||
);
|
||||
expect(snap.delta, const Offset(-3, 2));
|
||||
expect(snap.verticalGuides, [0, 500, 1000]);
|
||||
expect(snap.horizontalGuides, [0, 300, 600]);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'nearby candidates do not steal the locked anchor within release distance',
|
||||
() {
|
||||
const canvas = Size(1000, 600);
|
||||
// An almost full-width video has three competing matches near the middle.
|
||||
PreviewGeometry at(double x) =>
|
||||
PreviewGeometry(center: Offset(x, 220), size: const Size(992, 100));
|
||||
var snap = snapToCanvas(at(496), canvas, 6); // Left edge at zero.
|
||||
expect(snap.verticalGuides, [0]);
|
||||
for (final x in [499.0, 503.0, 500.0, 505.9, 499.0]) {
|
||||
snap = snapToCanvas(at(x), canvas, 6, previous: snap);
|
||||
expect(x + snap.delta.dx, closeTo(496, 1e-9));
|
||||
expect(snap.verticalGuides, [0]);
|
||||
}
|
||||
// The old left-edge match exceeds 10px; the right-edge match can now win.
|
||||
snap = snapToCanvas(at(506.1), canvas, 6, previous: snap);
|
||||
expect(snap.delta.dx, closeTo(-2.1, 1e-9));
|
||||
expect(snap.verticalGuides, [1000]);
|
||||
},
|
||||
);
|
||||
|
||||
test('entry and release are separate, use raw pointer geometry, and work on both axes', () {
|
||||
const canvas = Size(1000, 600);
|
||||
PreviewGeometry at(double x, double y) =>
|
||||
PreviewGeometry(center: Offset(x, y), size: const Size(200, 100));
|
||||
var snap = snapToCanvas(at(506, 306), canvas, 6);
|
||||
expect(snap.delta, const Offset(-6, -6));
|
||||
snap = snapToCanvas(at(509, 311), canvas, 6, previous: snap);
|
||||
expect(snap.delta, const Offset(-9, 0));
|
||||
expect(snap.verticalGuides, [500]);
|
||||
expect(snap.horizontalGuides, isEmpty);
|
||||
snap = snapToCanvas(at(511, 309), canvas, 6, previous: snap);
|
||||
expect(snap.delta, Offset.zero);
|
||||
snap = snapToCanvas(at(509, 306), canvas, 6, previous: snap);
|
||||
expect(snap.delta, const Offset(0, -6)); // 9px cannot reacquire x.
|
||||
});
|
||||
|
||||
test('a fresh gesture does not inherit a previous edge lock and ties prefer center', () {
|
||||
const canvas = Size(1000, 600);
|
||||
const geometry = PreviewGeometry(
|
||||
center: Offset(502, 220),
|
||||
size: Size(992, 100),
|
||||
);
|
||||
final snap = snapToCanvas(geometry, canvas, 6);
|
||||
expect(snap.delta.dx, -2); // Center and right edge are equally close.
|
||||
expect(snap.verticalGuides, [500]);
|
||||
});
|
||||
|
||||
test(
|
||||
'screen-scaled thresholds preserve entry and release after canvas resize',
|
||||
() {
|
||||
for (final scale in [.25, .5, 1.0, 2.0]) {
|
||||
PreviewGeometry at(double screenDelta) => PreviewGeometry(
|
||||
center: Offset(500 + screenDelta / scale, 220),
|
||||
size: const Size(200, 100),
|
||||
);
|
||||
var snap = snapToCanvas(at(5), const Size(1000, 600), 6 / scale);
|
||||
snap = snapToCanvas(
|
||||
at(9),
|
||||
const Size(1000, 600),
|
||||
6 / scale,
|
||||
previous: snap,
|
||||
);
|
||||
expect(snap.delta.dx * scale, closeTo(-9, 1e-9));
|
||||
snap = snapToCanvas(
|
||||
at(11),
|
||||
const Size(1000, 600),
|
||||
6 / scale,
|
||||
previous: snap,
|
||||
);
|
||||
expect(snap.verticalGuides, isEmpty);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test('guides describe corrected bounds, including rotation, not nearby candidates', () {
|
||||
final snap = snapToCanvas(
|
||||
const PreviewGeometry(
|
||||
center: Offset(503, 303),
|
||||
size: Size(600, 1000),
|
||||
rotation: 90,
|
||||
),
|
||||
const Size(1000, 600),
|
||||
6,
|
||||
);
|
||||
expect(snap.verticalGuides, [0, 500, 1000]);
|
||||
expect(snap.horizontalGuides, [0, 300, 600]);
|
||||
final narrow = snapToCanvas(
|
||||
const PreviewGeometry(center: Offset(501, 220), size: Size(4, 100)),
|
||||
const Size(1000, 600),
|
||||
6,
|
||||
);
|
||||
expect(narrow.verticalGuides, [
|
||||
500,
|
||||
]); // Deduplicated, no almost-aligned extras.
|
||||
});
|
||||
|
||||
test(
|
||||
'rotated hit testing uses the video rectangle, not its bounding box',
|
||||
() {
|
||||
const geometry = PreviewGeometry(
|
||||
center: Offset(100, 100),
|
||||
size: Size(100, 40),
|
||||
rotation: 45,
|
||||
);
|
||||
expect(geometry.contains(const Offset(100, 100)), isTrue);
|
||||
expect(
|
||||
geometry.contains(geometry.bounds.topLeft + const Offset(1, 1)),
|
||||
isFalse,
|
||||
);
|
||||
expect(
|
||||
geometry.contains(
|
||||
geometry.center + geometry.rotate(const Offset(40, 15)),
|
||||
),
|
||||
isTrue,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import 'dart:async';
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_core/editor.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('late render completion cannot overwrite a replacement context or disposed session', () async {
|
||||
final b = _Backend()..delayRendering = true;
|
||||
final first = b.begin();
|
||||
await first.prepared;
|
||||
first.update(const ClipTransform(x: .1));
|
||||
final late = b.rendered.single;
|
||||
b.session.cancelAll();
|
||||
final next = b.begin();
|
||||
await next.prepared;
|
||||
next.update(const ClipTransform(x: .2));
|
||||
late();
|
||||
expect(b.session.displayedValueFor(ElementId('clip'))!.x, 0);
|
||||
b.rendered.last();
|
||||
expect(b.session.displayedValueFor(ElementId('clip'))!.x, .2);
|
||||
b.session.cancelAll();
|
||||
b.session.dispose();
|
||||
expect(b.rendered.last, returnsNormally);
|
||||
});
|
||||
|
||||
test('preparation happens once and renders latest state rather than released history', () async {
|
||||
final b = _Backend()..gate = Completer<void>();
|
||||
for (final x in [.1, .2, .3]) {
|
||||
final edit = b.begin();
|
||||
edit.update(ClipTransform(x: x));
|
||||
await edit.end();
|
||||
}
|
||||
expect(b.commits, [.1, .2, .3]);
|
||||
expect(b.preparations, 1);
|
||||
expect(b.updates, isEmpty);
|
||||
b.gate!.complete();
|
||||
await b.session.settled;
|
||||
expect(b.updates, [.3]);
|
||||
expect(b.session.hasPending, isFalse);
|
||||
expect(b.session.hasContext, isTrue);
|
||||
b.session.cancelAll();
|
||||
});
|
||||
|
||||
test(
|
||||
'next drag renders immediately without closing or re-preparing the frame',
|
||||
() async {
|
||||
final b = _Backend();
|
||||
final first = b.begin();
|
||||
await first.prepared;
|
||||
first.update(const ClipTransform(x: .1));
|
||||
await first.end();
|
||||
final second = b.begin();
|
||||
second.update(const ClipTransform(x: .2));
|
||||
expect(b.updates, [.1, .2]);
|
||||
expect(b.preparations, 1);
|
||||
expect(b.cancellations, 0);
|
||||
second.cancel();
|
||||
expect(b.updates.last, .1);
|
||||
expect(b.commits, [.1]);
|
||||
expect(b.cancellations, 0);
|
||||
b.session.cancelAll();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'completed edit callbacks cannot update or cancel a new pointer',
|
||||
() async {
|
||||
final b = _Backend();
|
||||
final first = b.begin();
|
||||
first.update(const ClipTransform(x: .1));
|
||||
final done = first.end();
|
||||
expect(first.end(), same(done));
|
||||
final second = b.begin();
|
||||
second.update(const ClipTransform(x: .2));
|
||||
first.cancel();
|
||||
first.update(const ClipTransform(x: 9));
|
||||
expect(second.cancelled, isFalse);
|
||||
expect(b.visual().transform.x, .2);
|
||||
await second.end();
|
||||
await b.session.settled;
|
||||
expect(b.commits, [.1, .2]);
|
||||
b.session.cancelAll();
|
||||
},
|
||||
);
|
||||
|
||||
test('cancelling preparation rejects its late result without touching replacement', () async {
|
||||
final b = _Backend()..gate = Completer<void>();
|
||||
final first = b.begin();
|
||||
first.cancel();
|
||||
final second = b.begin();
|
||||
second.update(const ClipTransform(x: .2));
|
||||
b.gate!.complete();
|
||||
expect(await first.prepared, isFalse);
|
||||
expect(await second.prepared, isTrue);
|
||||
expect(b.updates, [.2]);
|
||||
expect(b.commits, isEmpty);
|
||||
b.session.cancelAll();
|
||||
});
|
||||
|
||||
test('preparation failure reports preview error but never rolls back authored history', () async {
|
||||
final b = _Backend()
|
||||
..gate = Completer<void>()
|
||||
..failPrepare = true;
|
||||
final first = b.begin();
|
||||
first.update(const ClipTransform(x: .1));
|
||||
await first.end();
|
||||
b.gate!.complete();
|
||||
expect(await first.prepared, isFalse);
|
||||
expect(b.errors.single, isA<StateError>());
|
||||
expect(b.commits, [.1]);
|
||||
b.failPrepare = false;
|
||||
final retry = b.begin();
|
||||
expect(await retry.prepared, isTrue);
|
||||
retry.cancel();
|
||||
});
|
||||
|
||||
test('changes to another layer retain earlier layer overrides', () async {
|
||||
final b = _Backend()..gate = Completer<void>();
|
||||
final first = b.begin();
|
||||
first.update(const ClipTransform(x: .1));
|
||||
await first.end();
|
||||
final second = b.session.begin(b.visual('other'))!;
|
||||
second.update(const ClipTransform(x: .2));
|
||||
b.gate!.complete();
|
||||
await second.prepared;
|
||||
expect(b.layers, {'clip': .1, 'other': .2});
|
||||
second.cancel();
|
||||
expect(b.layers, {'clip': .1, 'other': 0.0});
|
||||
b.session.cancelAll();
|
||||
});
|
||||
|
||||
test('invalid input does not enter projected geometry', () async {
|
||||
final b = _Backend();
|
||||
final edit = b.begin();
|
||||
for (final value in [
|
||||
const ClipTransform(x: double.nan),
|
||||
const ClipTransform(scale: 0),
|
||||
]) {
|
||||
expect(() => edit.update(value), throwsArgumentError);
|
||||
expect(b.visual().transform.x, 0);
|
||||
}
|
||||
edit.cancel();
|
||||
await edit.prepared;
|
||||
});
|
||||
}
|
||||
|
||||
class _Backend {
|
||||
bool delayRendering = false;
|
||||
final rendered = <void Function()>[];
|
||||
Completer<void>? gate;
|
||||
bool failPrepare = false;
|
||||
int preparations = 0;
|
||||
int cancellations = 0;
|
||||
final commits = <double>[];
|
||||
final updates = <double>[];
|
||||
final layers = <String, double>{};
|
||||
final errors = <Object>[];
|
||||
late final session = PreviewTransformSession(
|
||||
canBegin: () => true,
|
||||
select: (_) {},
|
||||
prepareNative: () async {
|
||||
preparations++;
|
||||
await gate?.future;
|
||||
if (failPrepare) throw StateError('prepare failed');
|
||||
return true;
|
||||
},
|
||||
updateNative: (id, value, onRendered) {
|
||||
updates.add(value.x);
|
||||
layers[id.value] = value.x;
|
||||
rendered.add(onRendered);
|
||||
if (!delayRendering) onRendered();
|
||||
},
|
||||
commit: (_, value) => commits.add(value.x),
|
||||
cancelNative: () {
|
||||
cancellations++;
|
||||
},
|
||||
failed: errors.add,
|
||||
changed: () {},
|
||||
);
|
||||
PreviewVisual visual([String id = 'clip']) => session.project([
|
||||
PreviewVisual(
|
||||
layerId: id,
|
||||
elementId: ElementId(id),
|
||||
lane: 0,
|
||||
transform: const ClipTransform(),
|
||||
geometry: const PreviewGeometry(
|
||||
center: Offset(500, 300),
|
||||
size: Size(300, 200),
|
||||
),
|
||||
),
|
||||
], const Size(1000, 600)).single;
|
||||
PreviewTransformEdit begin() => session.begin(visual())!;
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:cutdex_preview/src/selection_decoration.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
test('font changes invalidate and release the cached label', () async {
|
||||
var changes = 0;
|
||||
final label = SelectionLabel(onChanged: () => changes++);
|
||||
final first = label.layout('100 × 200');
|
||||
await TestWidgetsFlutterBinding.ensureInitialized().handleSystemMessage({
|
||||
'type': 'fontsChange',
|
||||
});
|
||||
expect(changes, 1);
|
||||
expect(first.debugDisposed, isTrue);
|
||||
expect(label.layout('100 × 200'), isNot(same(first)));
|
||||
label.dispose();
|
||||
await TestWidgetsFlutterBinding.ensureInitialized().handleSystemMessage({
|
||||
'type': 'fontsChange',
|
||||
});
|
||||
expect(changes, 1);
|
||||
});
|
||||
|
||||
test('label layout is reused and replaced paragraphs are released', () {
|
||||
final label = SelectionLabel();
|
||||
final first = label.layout('100 × 200');
|
||||
expect(label.layout('100 × 200'), same(first));
|
||||
final second = label.layout('200 × 300');
|
||||
expect(second, isNot(same(first)));
|
||||
expect(first.debugDisposed, isTrue);
|
||||
label.dispose();
|
||||
expect(second.debugDisposed, isTrue);
|
||||
});
|
||||
|
||||
for (final angle in [0.0, math.pi / 4, math.pi / 2]) {
|
||||
test('corner sectors follow rotated bounds at $angle', () {
|
||||
const center = Offset(200, 200);
|
||||
Offset rotate(Offset p) =>
|
||||
center +
|
||||
Offset(
|
||||
p.dx * math.cos(angle) - p.dy * math.sin(angle),
|
||||
p.dx * math.sin(angle) + p.dy * math.cos(angle),
|
||||
);
|
||||
final corners = [
|
||||
const Offset(-75, -50),
|
||||
const Offset(75, -50),
|
||||
const Offset(75, 50),
|
||||
const Offset(-75, 50),
|
||||
].map(rotate).toList();
|
||||
for (var i = 0; i < 4; i++) {
|
||||
final direction = corners[i] - center;
|
||||
final outward = corners[i] + direction / direction.distance * 16;
|
||||
final inward = corners[i] - direction / direction.distance * 16;
|
||||
expect(selectionResizeCorner(corners, corners[i]), i);
|
||||
expect(selectionResizeCorner(corners, outward), -1);
|
||||
expect(selectionRotationCorner(corners, outward), i);
|
||||
expect(selectionRotationCorner(corners, inward), -1);
|
||||
expect(selectionCursor(corners, outward), SystemMouseCursors.grab);
|
||||
}
|
||||
expect(selectionRotationCorner(corners, center), -1);
|
||||
expect(selectionRotationCorner(corners, const Offset(500, 500)), -1);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,601 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:cutdex_core/editor/commands.dart';
|
||||
|
||||
import 'package:cutdex_preview/cutdex_preview.dart';
|
||||
import 'package:cutdex_native_flutter/cutdex_native_flutter.dart';
|
||||
import 'package:cutdex_core/timeline/model.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
TestWidgetsFlutterBinding.ensureInitialized();
|
||||
const channel = MethodChannel('cutdex_runtime');
|
||||
const events = MethodChannel('cutdex_runtime/sessions/source-test');
|
||||
final messenger =
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger;
|
||||
final calls = <MethodCall>[];
|
||||
final asset = (id: 'source', location: 'file:///source.mov');
|
||||
final info = MediaInfo(
|
||||
duration: MediaTime(10, 1),
|
||||
videoTrackCount: 1,
|
||||
videoTrackIds: [1],
|
||||
audioTrackCount: 1,
|
||||
audioTrackIds: [1],
|
||||
isProtected: false,
|
||||
videoDisplaySizes: [RenderSize(1080, 1920)],
|
||||
audioTracks: [
|
||||
MediaTrackTiming(start: MediaTime(1, 1), duration: MediaTime(8, 1)),
|
||||
],
|
||||
);
|
||||
Completer<void>? blockedProbe;
|
||||
Completer<void>? blockedPlay;
|
||||
Completer<void>? blockedSkim;
|
||||
Completer<void>? blockedSeek;
|
||||
setUp(() {
|
||||
calls.clear();
|
||||
blockedProbe = null;
|
||||
blockedPlay = null;
|
||||
blockedSkim = null;
|
||||
blockedSeek = null;
|
||||
messenger.setMockMethodCallHandler(events, (call) async {
|
||||
if (call.method == 'listen') {
|
||||
scheduleMicrotask(
|
||||
() => messenger.handlePlatformMessage(
|
||||
events.name,
|
||||
const StandardMethodCodec().encodeSuccessEnvelope({
|
||||
'type': 'attached',
|
||||
}),
|
||||
(_) {},
|
||||
),
|
||||
);
|
||||
}
|
||||
return null;
|
||||
});
|
||||
messenger.setMockMethodCallHandler(channel, (call) async {
|
||||
calls.add(call);
|
||||
switch (call.method) {
|
||||
case 'seek':
|
||||
await blockedSeek?.future;
|
||||
return null;
|
||||
case 'skim':
|
||||
await blockedSkim?.future;
|
||||
return null;
|
||||
case 'probe':
|
||||
await blockedProbe?.future;
|
||||
return {
|
||||
'duration': info.duration.toMap(),
|
||||
'videoTrackCount': 1,
|
||||
'videoTrackIds': [1],
|
||||
'audioTrackCount': 1,
|
||||
'audioTrackIds': [1],
|
||||
'isProtected': false,
|
||||
'videoDisplaySizes': [
|
||||
{'width': 1080.0, 'height': 1920.0},
|
||||
],
|
||||
'audioTracks': [
|
||||
{
|
||||
'start': MediaTime(1, 1).toMap(),
|
||||
'duration': MediaTime(8, 1).toMap(),
|
||||
},
|
||||
],
|
||||
};
|
||||
case 'play':
|
||||
await blockedPlay?.future;
|
||||
return null;
|
||||
case 'createSession':
|
||||
return {'sessionId': 'source-test'};
|
||||
case 'load':
|
||||
return '1';
|
||||
case 'thumbnail':
|
||||
throw PlatformException(code: 'unsupported');
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
});
|
||||
});
|
||||
tearDown(() {
|
||||
messenger.setMockMethodCallHandler(channel, null);
|
||||
messenger.setMockMethodCallHandler(events, null);
|
||||
});
|
||||
|
||||
SourcePreviewController source() => SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) =>
|
||||
action(MediaReference(id: asset.id, uri: Uri.parse(asset.location))),
|
||||
);
|
||||
Future<void> waitForSeek() async {
|
||||
for (var i = 0; i < 100; i++) {
|
||||
if (calls.any((c) => c.method == 'seek')) return;
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
fail('Native seek did not start');
|
||||
}
|
||||
|
||||
List<double> seekTimes() => [
|
||||
for (final call in calls.where((c) => c.method == 'seek'))
|
||||
MediaTime.fromMap((call.arguments as Map)['time']).seconds,
|
||||
];
|
||||
|
||||
test(
|
||||
'interactive source navigation merges 100 targets before pause',
|
||||
() async {
|
||||
final controller = source();
|
||||
await controller.initialize(Future.value());
|
||||
calls.clear();
|
||||
final block = blockedSeek = Completer<void>();
|
||||
final first = controller.seekInteractive(TimelineClock.ticksPerSecond);
|
||||
await waitForSeek();
|
||||
final requests = <Future<void>>[first];
|
||||
for (var i = 1; i <= 100; i++) {
|
||||
requests.add(
|
||||
controller.seekInteractive(
|
||||
TimelineClock.ticksPerSecond +
|
||||
i * TimelineClock.ticksPerSecond ~/ 30,
|
||||
),
|
||||
);
|
||||
}
|
||||
final pause = controller.control(SourcePreviewAction.pause);
|
||||
expect(seekTimes(), [1]);
|
||||
expect(controller.positionTick, TimelineClock.ticksPerSecond * 13 ~/ 3);
|
||||
expect(calls.where((c) => c.method == 'pause'), isEmpty);
|
||||
block.complete();
|
||||
blockedSeek = null;
|
||||
await Future.wait([...requests, pause]);
|
||||
expect(seekTimes(), [1, closeTo(13 / 3, 1e-6)]);
|
||||
expect(calls.last.method, 'pause');
|
||||
expect(controller.error, isNull);
|
||||
await controller.close();
|
||||
controller.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test('exact source commands fence replaceable UI navigation', () async {
|
||||
final controller = source();
|
||||
await controller.initialize(Future.value());
|
||||
calls.clear();
|
||||
final block = blockedSeek = Completer<void>();
|
||||
final first = controller.seekInteractive(TimelineClock.ticksPerSecond);
|
||||
await waitForSeek();
|
||||
final latest = controller.seekInteractive(2 * TimelineClock.ticksPerSecond);
|
||||
final exact = controller.control(
|
||||
SourcePreviewAction.seek,
|
||||
at: CommandTime(3, 1),
|
||||
);
|
||||
final after = controller.seekInteractive(4 * TimelineClock.ticksPerSecond);
|
||||
final afterLatest = controller.seekInteractive(
|
||||
5 * TimelineClock.ticksPerSecond,
|
||||
);
|
||||
block.complete();
|
||||
blockedSeek = null;
|
||||
await Future.wait([first, latest, exact, after, afterLatest]);
|
||||
expect(seekTimes(), [1, 2, 3, 5]);
|
||||
expect(controller.positionTick, 5 * TimelineClock.ticksPerSecond);
|
||||
await controller.close();
|
||||
controller.dispose();
|
||||
});
|
||||
|
||||
test(
|
||||
'closing drains interactive navigation before releasing source',
|
||||
() async {
|
||||
final controller = source();
|
||||
await controller.initialize(Future.value());
|
||||
calls.clear();
|
||||
final block = blockedSeek = Completer<void>();
|
||||
final seeking = controller.seekInteractive(TimelineClock.ticksPerSecond);
|
||||
await waitForSeek();
|
||||
final seekFailure = expectLater(seeking, throwsStateError);
|
||||
final closing = controller.close();
|
||||
final closeFailure = expectLater(closing, throwsStateError);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
expect(calls.where((c) => c.method == 'close'), isEmpty);
|
||||
block.complete();
|
||||
blockedSeek = null;
|
||||
await Future.wait([seekFailure, closeFailure]);
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
controller.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test('navigation and scrubbing settle in either handoff direction', () async {
|
||||
final controller = source();
|
||||
await controller.initialize(Future.value());
|
||||
calls.clear();
|
||||
final block = blockedSeek = Completer<void>();
|
||||
final navigating = controller.seekInteractive(TimelineClock.ticksPerSecond);
|
||||
await waitForSeek();
|
||||
controller.beginScrubbing();
|
||||
controller.updateScrubbing(2 * TimelineClock.ticksPerSecond);
|
||||
block.complete();
|
||||
blockedSeek = null;
|
||||
await navigating;
|
||||
expect(controller.positionTick, 2 * TimelineClock.ticksPerSecond);
|
||||
// Navigation ends the scrub at its final target before the new exact frame.
|
||||
await controller.seekInteractive(3 * TimelineClock.ticksPerSecond);
|
||||
expect(controller.positionTick, 3 * TimelineClock.ticksPerSecond);
|
||||
final end = calls.singleWhere((c) => c.method == 'endSkimming');
|
||||
expect(MediaTime.fromMap((end.arguments as Map)['time']).seconds, 2);
|
||||
expect(calls.last.method, 'seek');
|
||||
expect(seekTimes(), [1, 3]);
|
||||
expect(controller.error, isNull);
|
||||
await controller.close();
|
||||
controller.dispose();
|
||||
});
|
||||
|
||||
test('local image preview survives native thumbnail failure', () async {
|
||||
final directory = await Directory.systemTemp.createTemp('source-image-');
|
||||
final file = File('${directory.path}/image.png');
|
||||
await file.writeAsBytes(
|
||||
base64Decode(
|
||||
'iVBORw0KGgoAAAANSUhEUgAAAAIAAAACCAIAAAD91JpzAAAAEElEQVR4nGP4z8AARAwQCgAf7gP9i18U1AAAAABJRU5ErkJggg==',
|
||||
),
|
||||
);
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) =>
|
||||
action(MediaReference(id: 'image', uri: file.uri, isImage: true)),
|
||||
);
|
||||
try {
|
||||
await controller.initialize(Future.value());
|
||||
expect(calls.where((call) => call.method == 'thumbnail'), hasLength(1));
|
||||
expect(controller.error, isNull);
|
||||
expect(controller.busy, isFalse);
|
||||
expect(controller.image, isNotNull);
|
||||
expect(controller.aspectRatio, 1);
|
||||
expect(controller.session, isNull);
|
||||
} finally {
|
||||
await controller.close();
|
||||
controller.dispose();
|
||||
await directory.delete(recursive: true);
|
||||
}
|
||||
});
|
||||
|
||||
for (final mode in SkimmingMode.values) {
|
||||
test(
|
||||
'${mode.name} source scrubbing previews latest target and settles once',
|
||||
() async {
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
policy: PreviewPolicy(skimmingMode: mode),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) => action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
),
|
||||
);
|
||||
await controller.initialize(Future.value());
|
||||
calls.clear();
|
||||
blockedSkim = Completer<void>();
|
||||
controller.beginScrubbing();
|
||||
controller.updateScrubbing(TimelineClock.ticksPerSecond);
|
||||
for (var i = 0; i < 100 && !calls.any((c) => c.method == 'skim'); i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
expect(calls.where((c) => c.method == 'skim'), hasLength(1));
|
||||
controller.updateScrubbing(2 * TimelineClock.ticksPerSecond);
|
||||
controller.updateScrubbing(3 * TimelineClock.ticksPerSecond);
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
blockedSkim!.complete();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
final skims = calls.where((c) => c.method == 'skim').toList();
|
||||
expect(skims, hasLength(2));
|
||||
expect(
|
||||
MediaTime.fromMap((skims.last.arguments as Map)['time']).seconds,
|
||||
3,
|
||||
);
|
||||
controller.endScrubbing();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
expect(calls.where((c) => c.method == 'beginSkimming'), hasLength(1));
|
||||
final begin = calls.singleWhere((c) => c.method == 'beginSkimming');
|
||||
expect((begin.arguments as Map)['mode'], mode.name);
|
||||
expect((begin.arguments as Map).containsKey('audible'), isFalse);
|
||||
final end = calls.singleWhere((c) => c.method == 'endSkimming');
|
||||
expect(MediaTime.fromMap((end.arguments as Map)['time']).seconds, 3);
|
||||
expect(calls.where((c) => c.method == 'seek'), isEmpty);
|
||||
expect(controller.error, isNull);
|
||||
await controller.close();
|
||||
controller.dispose();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test(
|
||||
'explicit source controls pause before playback events and drain on close',
|
||||
() async {
|
||||
var retained = false;
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) async {
|
||||
retained = true;
|
||||
try {
|
||||
return await action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
);
|
||||
} finally {
|
||||
retained = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
await controller.initialize(Future.value());
|
||||
await controller.control(SourcePreviewAction.play);
|
||||
await controller.control(SourcePreviewAction.pause);
|
||||
expect(calls.where((c) => c.method == 'pause'), hasLength(1));
|
||||
await controller.control(SourcePreviewAction.seek, at: CommandTime(3, 2));
|
||||
expect(controller.positionTick, 3 * TimelineClock.ticksPerSecond ~/ 2);
|
||||
await expectLater(
|
||||
controller.control(SourcePreviewAction.seek, at: CommandTime(11, 1)),
|
||||
throwsA(isA<CommandRejected>()),
|
||||
);
|
||||
blockedPlay = Completer<void>();
|
||||
final playing = controller.control(SourcePreviewAction.play);
|
||||
final expected = expectLater(playing, throwsStateError);
|
||||
for (
|
||||
var i = 0;
|
||||
i < 100 && calls.where((c) => c.method == 'play').length < 2;
|
||||
i++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 2));
|
||||
}
|
||||
final closing = controller.close();
|
||||
final closed = closing.catchError((Object e) {
|
||||
expect(e, isA<StateError>());
|
||||
});
|
||||
expect(retained, true);
|
||||
blockedPlay!.complete();
|
||||
await expected;
|
||||
await closed;
|
||||
expect(retained, false);
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
controller.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'source opens paused at saved position and retains access until close',
|
||||
() async {
|
||||
var retained = false;
|
||||
var remembered = 0;
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 25),
|
||||
positionTick: 2 * TimelineClock.ticksPerSecond,
|
||||
rememberPosition: (tick) => remembered = tick,
|
||||
loadMedia: <T>(action) async {
|
||||
retained = true;
|
||||
try {
|
||||
return await action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
);
|
||||
} finally {
|
||||
retained = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
await controller.initialize(Future.value());
|
||||
expect(retained, isTrue);
|
||||
expect(controller.aspectRatio, 1080 / 1920);
|
||||
expect(controller.durationTick, 10 * TimelineClock.ticksPerSecond);
|
||||
expect(calls.where((c) => c.method == 'play'), isEmpty);
|
||||
final seek = calls.singleWhere((c) => c.method == 'seek');
|
||||
expect(MediaTime.fromMap((seek.arguments as Map)['time']).seconds, 2);
|
||||
await controller.togglePlayback();
|
||||
expect(calls.where((c) => c.method == 'play'), hasLength(1));
|
||||
await controller.close();
|
||||
expect(retained, isFalse);
|
||||
expect(remembered, 2 * TimelineClock.ticksPerSecond);
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
controller.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'switching away during probe never creates or plays a stale session',
|
||||
() async {
|
||||
blockedProbe = Completer<void>();
|
||||
var released = false;
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) async {
|
||||
try {
|
||||
return await action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
);
|
||||
} finally {
|
||||
released = true;
|
||||
}
|
||||
},
|
||||
);
|
||||
final opening = controller.initialize(Future.value());
|
||||
for (var i = 0; i < 100 && !calls.any((c) => c.method == 'probe'); i++) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 1));
|
||||
}
|
||||
expect(calls.any((c) => c.method == 'probe'), isTrue);
|
||||
final closing = controller.close();
|
||||
blockedProbe!.complete();
|
||||
await opening;
|
||||
await closing;
|
||||
expect(released, isTrue);
|
||||
expect(
|
||||
calls.where((c) => c.method == 'createSession' || c.method == 'play'),
|
||||
isEmpty,
|
||||
);
|
||||
controller.dispose();
|
||||
},
|
||||
);
|
||||
|
||||
test('concurrent source startup retains only one loader', () async {
|
||||
blockedProbe = Completer<void>();
|
||||
var loads = 0;
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) async {
|
||||
loads++;
|
||||
return action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
);
|
||||
},
|
||||
);
|
||||
final first = controller.initialize(Future.value());
|
||||
final second = controller.initialize(Future.value());
|
||||
while (loads == 0) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
final closing = controller.close();
|
||||
blockedProbe!.complete();
|
||||
await Future.wait([first, second, closing]);
|
||||
controller.dispose();
|
||||
expect(loads, 1);
|
||||
});
|
||||
|
||||
test('host position callback failure cannot leak source access', () async {
|
||||
var retained = false;
|
||||
final failure = StateError('host callback failed');
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) => throw failure,
|
||||
loadMedia: <T>(action) async {
|
||||
retained = true;
|
||||
try {
|
||||
return await action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
);
|
||||
} finally {
|
||||
retained = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
await controller.initialize(Future.value());
|
||||
await expectLater(controller.close(), throwsA(same(failure)));
|
||||
expect(retained, isFalse);
|
||||
expect(calls.where((c) => c.method == 'close'), hasLength(1));
|
||||
controller.dispose();
|
||||
});
|
||||
|
||||
test(
|
||||
'close retains source access until in-flight playback finishes',
|
||||
() async {
|
||||
blockedPlay = Completer<void>();
|
||||
var retained = false;
|
||||
final controller = SourcePreviewController(
|
||||
frameDuration: RationalTime(1, 30),
|
||||
rememberPosition: (_) {},
|
||||
loadMedia: <T>(action) async {
|
||||
retained = true;
|
||||
try {
|
||||
return await action(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
);
|
||||
} finally {
|
||||
retained = false;
|
||||
}
|
||||
},
|
||||
);
|
||||
await controller.initialize(Future.value());
|
||||
final playing = controller.togglePlayback();
|
||||
while (!calls.any((c) => c.method == 'play')) {
|
||||
await Future<void>.delayed(Duration.zero);
|
||||
}
|
||||
final closing = controller.close();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 5));
|
||||
final retainedDuringPlayback = retained;
|
||||
final closedDuringPlayback = calls.any((c) => c.method == 'close');
|
||||
blockedPlay!.complete();
|
||||
await Future.wait([playing, closing]);
|
||||
controller.dispose();
|
||||
expect(retainedDuringPlayback, isTrue);
|
||||
expect(closedDuringPlayback, isFalse);
|
||||
expect(retained, isFalse);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'audio sample endpoints stay exact without rounding beyond the track',
|
||||
() {
|
||||
final audio = MediaInfo(
|
||||
duration: MediaTime(10, 1),
|
||||
videoTrackCount: 0,
|
||||
videoTrackIds: [],
|
||||
audioTrackCount: 1,
|
||||
audioTrackIds: [1],
|
||||
isProtected: false,
|
||||
audioTracks: [
|
||||
MediaTrackTiming(
|
||||
start: MediaTime(0, 1),
|
||||
duration: MediaTime(479999, 48000),
|
||||
),
|
||||
],
|
||||
);
|
||||
final plan = sourcePreviewPlan(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
audio,
|
||||
RationalTime(1, 30),
|
||||
);
|
||||
expect(plan.audioLayers.single.sourceRange.duration.numerator, 479999);
|
||||
expect(plan.audioLayers.single.sourceRange.duration.denominator, 48000);
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'reported unknown source color uses the timeline Rec.709 viewing fallback',
|
||||
() {
|
||||
final unknown = MediaInfo(
|
||||
duration: info.duration,
|
||||
videoTrackCount: 1,
|
||||
videoTrackIds: [1],
|
||||
audioTrackCount: 0,
|
||||
audioTrackIds: [],
|
||||
isProtected: false,
|
||||
audioTracks: [],
|
||||
videoColorSpaces: [null],
|
||||
);
|
||||
final plan = sourcePreviewPlan(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
unknown,
|
||||
RationalTime(1, 30),
|
||||
);
|
||||
expect(plan.visualLayers.single.inputColorSpace, RenderColorSpace.rec709);
|
||||
expect(plan.toneMapping, const RenderToneMapping.none());
|
||||
},
|
||||
);
|
||||
|
||||
test('HDR source preview explicitly maps to SDR', () {
|
||||
final hdr = MediaInfo(
|
||||
duration: info.duration,
|
||||
videoTrackCount: 1,
|
||||
videoTrackIds: [1],
|
||||
audioTrackCount: 0,
|
||||
audioTrackIds: [],
|
||||
isProtected: false,
|
||||
audioTracks: [],
|
||||
videoColorSpaces: [RenderColorSpace.rec2020HLG],
|
||||
);
|
||||
final plan = sourcePreviewPlan(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
hdr,
|
||||
RationalTime(1, 30),
|
||||
);
|
||||
expect(plan.toneMapping.sourceHeadroom, 4);
|
||||
expect(
|
||||
plan.visualLayers.single.inputColorSpace,
|
||||
RenderColorSpace.rec2020HLG,
|
||||
);
|
||||
});
|
||||
|
||||
test('source plan preserves native aspect and delayed audio alignment', () {
|
||||
final plan = sourcePreviewPlan(
|
||||
MediaReference(id: asset.id, uri: Uri.parse(asset.location)),
|
||||
info,
|
||||
RationalTime(1, 25),
|
||||
);
|
||||
expect(plan.renderSize.width, 1080);
|
||||
expect(plan.renderSize.height, 1920);
|
||||
expect(plan.audioLayers.single.sourceRange.start.seconds, 1);
|
||||
expect(plan.audioLayers.single.timelineRange.start.seconds, 1);
|
||||
expect(plan.audioLayers.single.timelineRange.duration.seconds, 8);
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user