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

This commit was merged in pull request #14.
This commit is contained in:
lingjhf committed 2026-10-11 19:59:40 +00:00
1 parent abc1868550
commit 06f1c26681
452 files changed
+43806 -2329

No files matched your search

+41
View File
@@ -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,
),
],
);
}
+20
View File
@@ -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);
});
}
+31
View File
@@ -0,0 +1,31 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
# Libraries should not include pubspec.lock, per https://dart.dev/guides/libraries/private-files#pubspeclock.
/pubspec.lock
**/doc/api/
.dart_tool/
.flutter-plugins-dependencies
/build/
/coverage/
+10
View File
@@ -0,0 +1,10 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "058e0af2c2b57e369d905a03ac9748b0ebf543c6"
channel: "stable"
project_type: package
+284
View File
@@ -0,0 +1,284 @@
# Timeline UI Architecture
[简体中文](ARCHITECTURE.zh-CN.md)
## Authority boundary
`TimelineScrollbars` is a Camera adapter, not a `ScrollController` or document
owner. Bounds are cached by Layout version, opened storyline and geometry.
Refreshing them reads O(P + S) partition/stack aggregates plus Kernel's storyline
span query; it never enumerates bodies. Camera-only updates use O(1) scrollbar
work. A drag freezes its range and grab offset, and is invalidated by external
camera changes, root/geometry changes, controller replacement or viewport resize.
The dependency and authority flow is one-way:
```text
TimelineView -> TimelineViewController -> TimelineViewportEngine
-> LayoutVersion
-> TimelineVersion
```
- Kernel owns time, topology, edit validity, transactions, and history.
- Layout owns physical lanes, avoidance, drop resolution, and geometry.
- UI owns camera state, paint appearance, focus, and pointer lifecycle.
- UI never writes DTOs, derives lanes, or repairs a rejected edit.
`TimelineViewController` is a presentation controller, not a second timeline
state machine. Read-only views retain the supplied Layout root. Editable views
bind to `TimelineLayoutEngine` with a published definition component root, so
the engine retains the canonical projection across undo/redo. UI never keeps a
parallel projection history. All publication uses Layout's prepared edit APIs.
## Viewport camera lifecycle
The host session saves and restores each timeline's presentation state before
publishing that session to the view. `TimelineViewport` supplies the measured
dimensions and cached content bounds. `timeline_camera_layout.dart` resolves
an immutable camera result from those bounds and the previous camera; it has
no widget, persistence or notification side effects. Initialization, restored
views, resize, focus, pan and zoom share this calculation.
`configureViewport` marks changed bounds for preparation. During layout,
`prepareViewport` applies the resolved camera silently before the ruler,
scrollbars and content paint. Only a fresh, uninitialized empty view receives
the twenty-second default scale; restored and cached views retain their scale.
Zero-sized layouts defer initialization. Unchanged bounds skip preparation.
After layout, `reconcileViewport` publishes any pending change without moving
the already prepared camera again. Repeating preparation or reconciliation is
idempotent. The scheduled callback belongs to the captured controller and must
still match the mounted viewport; it cannot update a replacement controller.
Camera-only reconciliation does not invalidate inspected editing values or add
document history. Camera constraint calculation is constant work and has no ticker.
## Connected-clip selection drag
`TimelineInteractionRegion` adapts pointer, focus and Escape events. It records
the initial grab before Flutter's pan threshold, while `TimelineViewportDragAnchor`
resolves every update with the current camera. Input rounds to the nearest
runtime tick; frame/sample snapping is not implemented yet.
- Same-side avoidance uses `TimelineLayoutPreview.connectedSelection` and
`LayoutRigidConnectionMove.previewResolved`.
- Crossing sides uses `LayoutConnectedSideMove`, including time translation.
- Entering the Primary band uses `LayoutPrimaryDropEdit` with a version-bound
`LayoutPrimaryDropTarget`. Pointer front/back halves choose before/after
(midpoint chooses after); outside the span clamps to begin/end. No split/gap IDs
or time-insertion commands are available on this drag/drop path.
UI supplies movement roots ordered by start time (same-time roots within a
stack retain semantic order). Roots are inserted back-to-back without a
container or inter-root gaps, preserving the grabbed member's pointer offset.
Selected descendants are carried, not inserted a second time. One private
Kernel transaction publishes the whole group. Overlap coverage uses the frontmost
serial body, matching paint order, and still selects only a member boundary.
Same-time roots on different sides have no implied serial order and remain
rejected in UI; the Layout API accepts a caller-supplied explicit order.
- Each valid frame renders the prepared canonical Layout version, hiding the
active body's landing projection. Its themed pointer ghost and connection
line remain visible; the line uses the prepared connection and the ghost edge.
Primary insertion has no connection line and outlines each serial landing with
the shared transparent, rounded reservation border, including incoming connected
clips. Leaving Primary removes those incoming reservations. Occupancy still drives avoidance and
exact commit. No separate UI collision solver or lane state exists.
- A release with unchanged camera/coordinates commits that exact prepared root.
A changed release is re-resolved first. Invalid drops retain the original
placement, omit ghosts and create no history.
- Escape, pointer cancellation, focus loss, app deactivation, controller
replacement and disposal discard private previews. External coordinated
history invalidates a stale drag; an unmatched Kernel root fails closed.
- Call `synchronize()` after host-side edits to notify the view. Editable
`applyLayout`/`replaceLayout` accept only the engine's published root.
`LayoutMovementPlan` normalizes same-definition Primary, connected and mixed
selections into direct roots, independent accompanying roots, carried descendants
and a body-to-root map. `LayoutMovementBounds` supplies the shared zero-origin
constraint for both pointer projection and connected edit APIs. UI chooses the
explicit insertion order and rejects expanded components and ambiguous ordering;
it does not traverse connection ancestry or calculate a second movement limit.
Instance-context editing remains unsupported by this gesture path.
## Explicit selection commands
Explicit `cutSelectionAtPlayhead`/`deleteSelection` use version-bound
`LayoutBladeEdit.selectionAtTime`/`LayoutCascadeDeleteEdit.selection`. Selection
planning consumes Kernel local times, ownership intervals and anchor queries;
no lane, media mapping or ownership rule is implemented in UI. The controller
supplies fresh IDs for blade and publishes exactly one prepared result.
Blade adds right halves to selection; delete clears it. Unsupported mixed
selections (transition items, expanded components, foreign/stale handles or
instance contexts) reject as a whole. Non-intersecting selected clips are not
cut; endpoint-only cuts and empty selections create no history. A right half
requires an exact Primary anchor at the cut; the existing Kernel rule that the
left connection point remain inside the left half still applies. Invalid source,
transition or anchor constraints reject atomically, without repair or extension.
The controller's element-ID factory is never passed to the drag session.
## Keyframe Editing
Hosts enable `TimelineInteractionRegion.keyframes` alongside
`TimelineView.showKeyframes`. A marker click selects its merged channels and
seeks to its exact time. Horizontal dragging uses `LayoutKeyframeMove` for
frame snapping, clip limits, source mapping and collision validation. Vertical
pointer movement does not alter the key or clip. Values and interpolation are
preserved. Dragging clamps to the intersection of the moved channels' neighboring
key ranges, retaining at least one project frame of spacing. A range with no
available frame leaves the key in place. Direct edits outside these bounds are
rejected; dragging against a neighbor remains a valid preview.
The same private preview drives the marker and, through
`TimelineViewController.keyframePreviewVersion`, the host's video renderer.
The playhead remains fixed during dragging. The host samples temporary values
at that time and renders them through its interactive frame context, coalescing
pending renders to the latest values. Only published edits update the playback
plan; pointer updates must not replace the playback session.
Release publishes one history entry; Escape, pointer cancellation, focus loss
and external history discard it. Delete applies to selected key channels, not
the enclosing clip. Held or repeated source visits remain selectable for seeking
but reject independent moves rather than changing other occurrences implicitly.
## Edge Trimming
`TimelineInteractionRegion` passes the theme's inner edge hit band to `beginDrag`.
The closest edge wins on narrow clips (midpoint: trailing). Content, gaps and
collapsed containers expose grips; instance-context/expanded components and
transition items do not. A multi-selection edge edits only the hit clip.
Move and trim are mutually exclusive private sessions under the same controller
lifecycle. `isDragging` covers either; `isTrimming` and `trimEdge` distinguish trim.
Each pointer/Camera update resolves a duration from the immutable grab anchor and
base duration, at runtime-tick precision, then calls `LayoutIntervalEdit.previewTrim`.
This pure-Dart entry point constrains source availability and chooses the Kernel
leading/trailing or container-view trim. Serial trim ripples the suffix; connected
left trim keeps its right edge. When its start passes the original anchor, Layout
resolves a valid storyline anchor and reattaches before shortening in the same
private transaction. Kernel validates source, retime, transition and connection
constraints. Invalid outgoing anchors reject atomically; children are not deleted.
Layout handles changed intervals and avoidance. The painter displays only this
canonical preview and its connection lines, without a move ghost or projection.
Unchanged release commits exactly that prepared version. Invalid/no-motion release
creates no history. Camera navigation, edge scrolling, cancellation, focus loss
and external root invalidation share the move lifecycle. Frame/sample snapping,
roll/slip/slide gestures and transition resizing are not part of this basic trim.
Grip width/hit band and outline colors come from `TimelineThemeData`; put the
extension above both the input region and painter when customizing edge behavior.
## Primary-to-connected drag
`beginDrag` / `updateDrag` / `finishDrag` allow Primary reordering with connected
descendants, but ordinary dragging into or out of Primary requires each moved
root to have no outgoing connections. Container contents do not count as outer
connections. Both transfer commands enforce this using Kernel's direct anchor
index; UI cannot bypass the precondition. `LayoutPrimaryDetachEdit`
rejects the ownership conversion, not pointer movement: owners with connections
use the same free ghost and Primary reservation path as gaps. A valid Primary
drop moves that reservation; an off-axis release does not publish.
For an eligible unconnected source, `LayoutPrimaryDetachEdit`
composes Kernel link and placement primitives into one unpublished result. A→B→C
becomes A→C when B is detached; its old span is not replaced by a gap. Anchoring uses the
post-ripple rope, including any adjacent transition adjustment. Connection IDs
come from the host's `createConnectionId` factory and are reused during a gesture.
The detached body receives pointer priority; passively translated suffix bodies
do not. Their canonical time index is updated before collision discovery. The same
prepared Kernel/Layout bundle supplies preview and drop. Returning to Primary
rebuilds the boundary reorder from the original version while carrying forward
the generated/extended gap in the same transaction. The source's own boundaries
are no-ops only when there is no pending gap edit. Cancel and invalid drop
leave history unchanged. Tail dragging clamps the accepted start to the current
tail T. Only when the clip's start reaches T does the same terminal gap extend
by the moved clip's duration. Moving within the gap, even with the clip's end
beyond T, does not extend it.
Layout retains the last raw/accepted start and gap extent in its preview; later
pointer deltas advance from that accepted start. Repeated frames cannot consume
the newly extended tail. Gap end is monotonic during connected dragging, including
backward movement. Existing terminal gaps retain their IDs across gestures.
Otherwise IDs come from the host element-ID factory. A sole Primary clip can
use T=0. For connected multi-selections, the rightmost movement root's start
triggers and clamps at T; every root receives the same translation. The gap
extends by max(root end) - max(root start), covering the group's remaining
time envelope without waiting for its leftmost root. Committing publishes the gap and
connections together; cancel publishes neither. Moving a connected clip away
does not delete its committed gap. Other missing-anchor cases remain rejected. Pointer
ghosts and connection lines remain visible; connected landing bodies remain hidden.
Both membership directions share canonical projection and passive-ripple targeting.
Primary drop invokes only Kernel `splice` or `unlink` by index, never blade. Explicit
arbitrary-time insertion remains separate. Display-only Primary ghosts never enter
the Layout solver; pointer offsets remain independent of hidden snapped landings.
## Rendering contract
### Drag edge scrolling
One vsync ticker runs only for an active single-pointer clip drag inside an edge
zone. Defaults: 48 logical pixels and maximum 600 logical pixels/second per axis;
zone width is capped at half the viewport dimension. For signed edge penetration
`p ∈ [-1,1]`, `v = vmax * p * |p|` and each frame applies
`ΔcameraPixels = v * min(Δseconds, 0.05)`. Corners combine axes. Zero extent/speed
disables scrolling. Idle, ruler, marquee and hand navigation never start it;
suspended frames do not produce catch-up jumps.
Each tick calls existing controller `panBy` once, re-resolving the retained grab
and pointer with the current Camera. No history or second placement implementation
is added. Ghosts and connection lines use the same preview; release commits that
latest prepared root. Cancel retains the scrolled Camera but not the edit. Camera
bounds remain those of manual pan; scrolling does not bypass semantic validation.
Leaving the edge/view, release, cancellation, focus/lifecycle loss, controller
replacement, external drag cancellation and a second touch stop the ticker.
Viewport resize cancels the old-coordinate gesture after layout; dispose releases
the ticker. Input work per frame is O(1), plus existing affected-region preview
and resident paint costs; no traversal of total N is introduced.
The input region uses one ScaleGestureRecognizer for clip drag, touch pinch and
native trackpad navigation, with explicit press-time routing for ruler seek and
hand navigation. Pointer cancellation/focus loss discard edit state. All combined
pan/zoom transforms call `controller.navigate` and then the existing Layout
Camera APIs; the time under the old focal point moves to the new focal point.
`TimelineRuler` paints a bounded number of adaptive elapsed-time ticks proportional
to viewport width. It never walks Kernel elements. Its playhead is presentation
state, has no undo history, and does not implement playback. The ruler is fixed
vertically while the clip surface can pan vertically.
The painter requests one transient `TimelineViewportFrame` during paint and
consumes it immediately. The frame references a reusable buffer and must not be
retained across another projection. One canvas surface paints all resident
items; element count does not affect the widget-tree size.
For `V` resident items:
```text
widget build = O(1)
camera update without active drag = O(1)
resident cache hit = O(1) projection + O(V) paint
resident cache miss = Layout viewport query + O(V) projection/paint
hit test = O(V), reverse paint order
active drag update = Layout target/semantic preview cost + viewport paint
```
Media thumbnails, waveforms, text, selections, and drag overlays must extend
this bulk rendering pipeline or use bounded viewport overlays. They must not
introduce one persistent widget per project element.
All painters and overlays consume `TimelineThemeData`. The widget layer
resolves the Flutter theme once per build and passes immutable visual tokens to
the painter; the resident-item loop performs no inherited-theme lookup.
Opaque Primary payload classification reuses the host's exact
`LayoutMediaClassifier`. Connected audio/visual classification is read from
Layout's solved placement class;
structural gap/container state is read from the exact Kernel version. UI never
parses `PayloadRef` or recursively inspects a container.
## Publication contract
- `applyLayout(result)` is for an adjacent, atomically published Layout update.
The viewport cache survives only when Layout proves it is geometry-neutral.
- `replaceLayout(version)` explicitly invalidates the cache for opening another
scene, non-adjacent history movement, or a global rebuild.
- Camera changes re-resolve an active drag, otherwise only notify painting.
Neither path creates Kernel history.
- A compound clip opens by supplying its independent Storyline/Layout scene to
the controller; it is not expanded inside the parent timeline surface.
@@ -0,0 +1,212 @@
# 时间线 UI 架构
[English](ARCHITECTURE.md)
## 权威边界
`TimelineScrollbars` 只是 Camera 适配器,不持有独立的 `ScrollController` 或文档。
范围按 Layout 版本、打开的故事线和几何配置缓存;更新时读取 O(P + S) 个分区/栈聚合,
另查询 Kernel 故事线 span,不遍历片段。仅 Camera 变化时,滚动条工作量为 O(1)。
拖动固定范围和抓取偏移;外部 Camera 变化、根/几何变化、替换 controller 或视口尺寸
变化都会使旧拖动失效。
依赖与权威数据流保持单向:
```text
TimelineView -> TimelineViewController -> TimelineViewportEngine
-> LayoutVersion
-> TimelineVersion
```
- Kernel 负责时间、拓扑、编辑合法性、事务和历史。
- Layout 负责物理 lane、避让、放置解析和几何。
- UI 负责 Camera 状态、绘制外观、焦点和指针生命周期。
- UI 不直接写 DTO、不自行推导 lane,也不修复被 Kernel 拒绝的编辑。
`TimelineViewController` 是表现层 controller,不是第二套时间线状态机。只读视图保留宿主
提供的 Layout root;可编辑视图绑定已经发布 definition component root 的
`TimelineLayoutEngine`,由引擎在撤销/重做时保留权威投影。UI 不另建投影历史,所有提交
都经过 Layout 已准备好的编辑入口。
## 视口相机生命周期
宿主会话在发布到界面前保存、恢复每条时间线的表现状态。`TimelineViewport` 提供实际
视口尺寸和缓存的内容边界。`timeline_camera_layout.dart` 根据这些不可变边界和原相机
计算新的相机结果,不访问 Widget、持久化或通知系统。初始化、恢复视图、窗口调整、
居中、平移和缩放共用这套计算。
`configureViewport` 将变化的边界标记为待准备。布局期间,`prepareViewport` 在标尺、
滚动条和内容绘制前静默应用结果。只有尚未初始化的新空时间线使用默认二十秒比例,
恢复或缓存的视图保留原比例。零尺寸布局推迟初始化,边界未变化时跳过准备。
布局结束后,`reconcileViewport` 只发布待通知的变化,不再次移动已经准备好的相机。
重复准备或发布不会产生额外变化。帧回调捕获其所属 controller,只有视口仍挂载且绑定
同一个 controller 时才发布,不能操作替换后的 controller。仅相机变化不使属性编辑值
失效,也不新增文档历史。相机边界计算为常数成本,不启动 ticker。
## 连接片段选区拖拽
`TimelineInteractionRegion` 转接指针、焦点和 Esc 事件。在 Flutter 判定拖拽阈值前记录
按下位置,之后通过 `TimelineViewportDragAnchor` 使用当前相机重新解析每次输入。
时间取最近的运行时 tick;本轮尚未接入帧/采样吸附。
- 同侧避让复用 `TimelineLayoutPreview.connectedSelection` 和
`LayoutRigidConnectionMove.previewResolved`。
- 跨上下侧复用 `LayoutConnectedSideMove`,时间平移和换侧一起处理。
- 进入主故事线使用 `LayoutPrimaryDropEdit` 和绑定版本的 `LayoutPrimaryDropTarget`。
鼠标前/后半区决定插在目标前/后,中点归后半区;超出首尾则钳制到首尾边界。
拖拽没有切割/gap ID 工厂,不调用按时间插入命令。
UI 按开始时间生成明确的移动根顺序,同一栈内同时间的根沿用语义顺序;各根紧接插入,
不创建容器或根之间的 gap,并保留被抓片段在指针下的偏移。选中的后代随父级携带,
不重复插入。整个组在一个私有 Kernel 事务内发布;重叠区按绘制顺序选择最前方串行片段,仍只解析成员边界。
不同侧、同一开始时间的根没有默认先后顺序,UI 仍拒绝隐式排列;Layout API 支持调用方明确指定顺序。
- 每个有效预览帧绘制已经准备好的权威 Layout 版本,但隐藏活动片段的落点投影。
跟随指针的浮动片段及连接线保持可见,连接线读取权威预览的连接关系并连到浮动片段边缘;
主故事线插入预览不画连接线,而是在各串行落点绘制统一的透明背景、圆角边框占位,
包括从连接区域拖入的片段;再次离开主轴时移除这些新落点占位。占位仍驱动避让和精确提交。
UI 不另建碰撞求解器或 lane 状态。
- 放置时若相机/坐标未变,直接提交该预览的同一版本根;有变化则先重新解析。无效位置
保留原占位,不绘制浮动预览,不产生历史。
- Esc、指针取消、焦点丢失、应用失活、替换 controller 和释放都会丢弃私有预览。外部协调
历史跳转会使旧拖拽失效;如果 Kernel 没有匹配的 Layout 根,则拒绝操作。
- 宿主在外部编辑后调用 `synchronize()` 通知视图。可编辑模式的 `applyLayout` 和
`replaceLayout` 仅接受引擎当前已发布的根。
`LayoutMovementPlan` 将同一 definition 内的主片段、连接片段及混合选区归一为直接移动根、
独立随动根、携带后代和片段到移动根的映射。`LayoutMovementBounds` 为指针投影和连接
编辑 API 提供共用的零点约束。UI 选择明确的插入顺序,拒绝展开组件及有歧义的排序,
不再遍历连接祖先或重复计算移动下限。当前手势路径仍不支持实例上下文编辑。
## 显式选区命令
显式 `cutSelectionAtPlayhead`/`deleteSelection` 使用绑定版本的
`LayoutBladeEdit.selectionAtTime`/`LayoutCascadeDeleteEdit.selection`。选区计划只读取
Kernel 局部时间、ownership 区间与锚点查询;UI 不实现 lane、媒体映射或归属规则。
Controller 为切割提供新 ID,一次发布一个准备好的结果。切割后右半段加入选区,删除后
清空选区。不支持的混合选区(转场项、展开组件、外部/失效 handle、实例上下文)整体拒绝。
不与播放头内部相交的选中片段不切割;端点切割和空选区不产生历史。右半段必须在切割点
找到精确的主片段锚点;Kernel 现有的“左半段连接点必须留在左半段内部”约束继续适用。
源范围、转场或锚点不合法则原子拒绝,不隐式修复或延长时间线。Controller 的片段 ID 工厂
不会传入拖拽会话。
## 关键帧编辑
宿主同时开启 `TimelineInteractionRegion.keyframes` 与 `TimelineView.showKeyframes`。
点击菱形选中其合并通道并定位播放头;水平拖动由 `LayoutKeyframeMove` 统一处理帧吸附、
片段范围、源时间映射与目标冲突,纵向移动不改变时间和值。拖动范围取所有被移动通道
相邻关键帧范围的交集,与邻帧至少保留一个项目帧间隔。没有可用帧位置时保持原位,
拖到相邻边界仍是有效预览;直接提交越界位置会被拒绝。值和插值方式保持不变。
菱形与宿主视频渲染共用私有预览,视频通过 `keyframePreviewVersion` 读取临时版本。
拖动期间播放头保持不动,宿主在该时刻采样临时参数,通过交互式帧上下文渲染;
待渲染请求合并为最新值。仅已发布的编辑更新播放计划,指针更新不替换播放会话。
松手提交一条历史;Esc、指针取消、失焦和外部历史切换丢弃预览。Delete 只作用于选中
关键帧,不删除片段。定格或重复源时间仍可选中定位,但拒绝独立移动。
## 边缘裁剪
`TimelineInteractionRegion` 将主题中的内侧边缘命中宽度传入 `beginDrag`。窄片段取最近
边缘,中点归右边缘。内容、gap 和未展开容器显示手柄;实例上下文、展开组件和转场项
不提供裁剪手柄。多选状态下拖一个边缘只裁剪命中的片段。
移动和裁剪是互斥的私有会话,共用 controller 生命周期;`isDragging` 包含两者,
`isTrimming` 和 `trimEdge` 用于区分裁剪。
每次指针/Camera 更新从不可变抓取点及原时长求出目标时长,精确到运行时 tick,随后通过
`LayoutIntervalEdit.previewTrim` 统一限制源范围并选择 Kernel 左/右裁剪或容器视图裁剪。
串行裁剪磁性移动后缀;连接片段左裁剪保持右边缘。新起点越过原锚点后,由 Layout 查询
合法的故事线锚点,在同一私有事务中先重新连接再裁剪。Kernel 校验源范围、变速、转场
和连接点约束;子连接 anchor 失效时整体拒绝,不删除子片段。Layout 负责区间变化与避让,Painter 只显示权威预览
及连接线,不添加移动浮影或落点投影。坐标未变时精确提交准备好的同一版本,无效或无
位移松手不创建历史。Camera、边缘滚动、取消、失焦、外部根失效共用移动的生命周期。
本次基础裁剪不包含帧/采样吸附、roll/slip/slide 手势或转场缩放。手柄宽度、命中宽度及
边框颜色统一来自 `TimelineThemeData`;自定义命中行为时,在输入区域和 Painter 上方
统一安装主题扩展。
## 主片段拖出成为连接片段
`beginDrag` / `updateDrag` / `finishDrag` 允许主轴内重排时携带连接后代,但普通拖入或拖出
主轴要求每个移动根都没有对外连接片段。容器内部内容不算外部连接。两个转移命令统一读取
Kernel 的直接锚点索引检查,UI 不能绕过此前置条件。
此限制只针对归属转换,不禁止指针移动:带连接片段的主片段与 gap 共用自由拖影和主轴
占位路径,合法主轴放置切换占位,离轴释放不提交。
`LayoutPrimaryDetachEdit` 把 Kernel 的 link 和 placement 原语组合成一个未发布结果。
从 A→B→C 拖出 B 后变成 A→C,不在 B 原位置补 gap。锚点根据闭合后的 rope 解析,包含相邻转场
调整。连接 ID 由宿主的 `createConnectionId` 工厂提供,同一手势中复用。
被拖出的片段获得主动拖拽优先级,随主线前移的后缀片段不会获得这一优先级;其权威时间索引在
碰撞查询前增量更新。预览与放置共用同一个已准备的 Kernel/Layout 根组合。拖回主线时,
从原始版本重建边界重排,同时在同一事务中保留手势已生成或扩展的 gap。
只有不存在待提交的 gap 编辑时,片段自身前后边界才为空操作。取消和无效放置不写历史。
尾部拖拽把实际开始位置限制在当前尾点 T;仅当片段起点到达 T 时,同一个尾部 gap 才增加
一段片段时长。在 gap 内部移动时,即使片段终点已超过 T,也不触发延长。
Layout 预览记录上次指针目标、实际开始位置和 gap 范围;后续使用指针增量继续移动,因此
重复刷新不会自动消耗扩展后的尾点。连接拖拽中 gap 只增长,回拖也不自动缩短。
已有尾部 gap 跨手势保持 ID;新 ID 来自宿主元素 ID 工厂。唯一主片段可以使用 T=0,
连接片段多选以最右侧移动根的起点触发并钳制到 T,所有根保持同一平移量。
gap 增量为「所有根的最晚终点 − 最晚起点」,覆盖整组选区伸出尾点的时间范围,
不再等待最左侧根到达尾点。提交时 gap 与连接一起发布,取消不发布;后续移走连接片段
不删除已提交的 gap。其他缺少锚点的情况仍拒绝。鼠标跟随片段与连接线可见,连接区域的落点投影不显示。
两种主线 membership 移动共用权威投影和被动 ripple 落点处理。主线拖拽只按索引调用 Kernel
`splice` 或 `unlink`,不调用 blade;显式任意时间插入仍是独立 API。仅用于显示的主片段 ghost
不进入 Layout solver,鼠标抓取偏移与吸附后的不可见落点分开处理。
## 渲染约束
### 拖拽边缘自动滚动
只有单鼠标/单指片段拖拽位于边缘区时,才运行一个显示帧 ticker。默认边缘宽 48 逻辑像素,
每轴最高 600 逻辑像素/秒;边缘宽度不超过该维度的一半。带符号深入比例为 `p ∈ [-1,1]` 时,
`v = vmax * p * |p|`,每帧 `ΔcameraPixels = v * min(Δseconds, 0.05)`;角落同时移动两轴。
宽度或速度设零可禁用。空闲、标尺、框选、抓手导航不启动 ticker;停顿不补算成大幅跳跃。
每帧只调用一次现有 controller `panBy`,使用最新 Camera 重新解析保留的抓取点和鼠标位置,
不新增历史或放置实现。鼠标跟随片段、连接线共用该预览,松手提交最新已准备根。取消保留
滚动后的 Camera,但不提交编辑。Camera 范围与手动平移一致,滚动不绕过语义合法性校验。
离开边缘/视口、松手、取消、失焦/失活、替换 controller、外部取消拖拽及第二根手指加入
都会停止 ticker。视口尺寸变化后取消旧坐标下的手势,dispose 释放 ticker。每帧输入计算
为 O(1),另加已有受影响区域预览和可见内容绘制成本,不遍历总元素 N。
输入区用一个 ScaleGestureRecognizer 处理片段拖拽、触屏双指和原生触控板导航,在按下时
明确区分标尺定位和抓手平移。指针取消/失焦会丢弃编辑状态。组合平移和缩放统一调用
`controller.navigate`,再调用 Layout 已有 Camera API,使旧焦点下的时间移动到新焦点。
`TimelineRuler` 仅绘制与 viewport 宽度成比例、有数量上界的自适应经过时间刻度,不遍历
Kernel 元素。播放位置属于表现层状态,不进入撤销历史,也不实现播放。标尺垂直固定,
片段区域可以垂直平移。
Painter 在绘制期间请求一个临时 `TimelineViewportFrame` 并立即消费。该 frame 引用可复用
buffer,不能跨下一次 projection 保留。一个 Canvas surface 绘制全部 resident 元素;
工程元素总数不会改变 Widget tree 大小。
对于 resident 元素数 `V`:
```text
Widget build = O(1)
没有活动拖拽时的 Camera 更新 = O(1)
resident cache 命中 = O(1) projection + O(V) 绘制
resident cache 未命中 = Layout viewport query + O(V) projection/绘制
hit test = O(V),按绘制顺序反向扫描
活动拖拽更新 = Layout 目标解析/语义预览成本 + viewport 绘制
```
媒体缩略图、波形、文字、选择状态和拖拽 overlay 必须扩展这条批量渲染管线,或使用数量
受 viewport 限制的 overlay;不能为工程中的每个元素创建持久 Widget。
所有 Painter 和 overlay 都消费 `TimelineThemeData`。Widget 层每次 build 只解析一次
Flutter 主题,并把不可变视觉 token 传给 Painter;resident 元素循环不查询继承主题。
不透明 Primary payload 的分类复用宿主的同一个 `LayoutMediaClassifier`。connected 音频/视觉分类读取
Layout 已求解的 placement class;结构 gap/container 状态读取精确 Kernel 版本。
UI 不解析 `PayloadRef`,也不递归遍历 container。
## 发布约束
- `applyLayout(result)` 只用于相邻、原子发布的 Layout 更新。只有 Layout 能证明几何未变化
时才保留 viewport cache。
- `replaceLayout(version)` 用于打开另一个场景、非相邻历史跳转或全局重建,并显式使 cache
失效。
- Camera 修改在拖拽中重新解析预览,其他时候只通知绘制;两者都不创建 Kernel 历史。
- 打开复合片段时向 controller 提供其独立 Storyline/Layout scene,不在父时间线 surface
内展开。
+58
View File
@@ -0,0 +1,58 @@
# Changelog
## Unreleased
- Stabilize filmstrip source samples within each tile-count level, expose each
tile's source-time span and painted resolution to thumbnail providers, and
request two offscreen tiles on each side after visible demand.
- Unify drag placement across Primary, connected clips and audio side changes.
Keep gaps and Primary clips with connections freely draggable but Primary-only
on drop; enabled state does not alter placement rules.
- Create and grow one persistent terminal gap at explicit tail crossings,
preserving multi-selection offsets, Primary return, cancellation and history.
Outline Primary reservations (including incoming connected clips), paint opaque
ghosts, and keep selection borders inside clips above neighboring fills.
- Paint clip names in themed 18px headers with 2px horizontal padding and no
separate background fill, including pointer ghosts. Use ID fallback, ellipsis and clip-anchored positioning without
changing Layout geometry or adding per-clip widgets.
- Constrain pointer trims with Kernel media limits instead of discarding an
overrun preview. Add mouse/touch original-speed and half-speed boundary tests;
demo video/audio declare finite ranges and titles explicitly allow extension.
- Connect selected connected-clip group dragging, carried descendants and serial
Primary insertion to canonical Layout edits. Render each active ghost and its
connection without a connected landing projection. Reject transition-overlap targets
without killing the gesture; stabilize example status height while dragging.
- Add themed mouse marquee selection against the current Layout frame, with
cancellation restoration and stale-root protection. Blank mouse drag selects;
Space/middle drag and touch/trackpad navigation retain pan behavior.
- Keep the dragged clip's connection line visible at its pointer ghost, using
the prepared attachment. Landing bodies remain hidden; Primary insertion has no line.
- Add themed horizontal/vertical Camera scrollbars, track paging and frozen
thumb-drag mapping. Read cached Layout aggregates instead of scanning clips.
- Add a themed elapsed-time ruler and seekable playhead, cursor-anchored wheel
zoom, Shift-wheel pan, middle/Space drag pan and touch/native trackpad
pinch. Toolbar and gestures share one Camera transform; navigation never
publishes edits, and a second touch cancels an active clip drag.
- Add single connected-clip dragging with canonical preview/drop, side crossing,
Primary insertion, coordinated undo/redo, themed ghost rendering with invisible landing occupancy,
camera-aware hit/grab mapping and lifecycle cancellation tests. Fix accepted
pointer cancellation being interpreted as a drop by Flutter's pan recognizer.
- Add a runnable macOS example with a Kernel-backed scene, theme switching,
viewport navigation, selection, hover, and a camera-coordinate widget test.
- Add the Flutter UI package, presentation-only viewport controller, and
single-painter resident timeline surface.
- Add one Flutter `ThemeExtension` shared by global and local timeline styles.
- Add themed bulk primitives for visual/audio clips, gaps, containers,
transitions, direct connection lines, hover and selection, plus
reverse-paint-order hit testing.
@@ -0,0 +1,44 @@
# 变更记录
## 未发布
- 统一主轴、连接片段及音频跨侧拖拽的放置规则。gap 和带连接片段的主片段可自由拖拽,
但只能放置在主轴;启停状态不改变放置规则。
- 起点明确到达尾点时创建或延长同一个持久 gap,保留多选相对位置、拖回主轴、取消与历史语义。
主轴占位(包括连接片段拖入)绘制空心边框,拖拽片段不透明;选中边框向内绘制且不被邻片填色遮挡。
- 片段及拖拽片段在 18px header 显示名称,水平 padding 为 2px,无独立背景色,统一由主题管理。
空名称回退 ID,长名称省略,名称固定在片段左端并随视口裁切;不改 Layout 几何,不新增逐片段 widget。
- 指针裁剪读取 Kernel 素材极限,越过素材边界时停在合法位置,不再丢弃整个预览。
新增鼠标/触屏原速与半速边界测试;示例视频/音频声明有限范围,标题明确允许延展。
- 接入连接片段多选拖拽、携带后代和按顺序紧接插入主故事线,复用权威 Layout 编辑。
分别绘制活动片段与连接线,不显示连接区域的落点投影。转场重叠区拒绝放置但不中断手势;
固定示例状态区高度,避免拖拽时视口跳动。
- 新增统一主题的鼠标框选,命中当前 Layout 视口;支持取消恢复与过期根保护。
空白处鼠标拖动用于框选,空格/中键拖动及触屏/触控板仍用于平移。
- 拖拽片段的连接线保持可见,读取权威预览的连接关系并连接浮动片段;落点片段仍隐藏,
主故事线插入预览不画连接线。
- 新增统一主题的横纵 Camera 滚动条、点击轨道翻页及拖动期间固定的滑块映射。
缓存读取 Layout 聚合,不扫描全部片段。
- 新增统一主题的经过时间标尺和可定位播放位置线、指针锚定滚轮缩放、Shift 滚轮平移、
中键/空格拖拽平移、触屏和原生触控板双指缩放。按钮与手势共用 Camera 变换,
导航不提交编辑,第二根手指加入时取消活动片段拖拽。
- 新增单连接片段拖拽,包含权威预览/放置、跨上下侧、主故事线插入、协调撤销/重做、
主题控制的浮动预览与不可见落点占位、相机坐标映射和生命周期取消测试。修复 Flutter 已识别的
拖拽在指针取消时可能被误当作放置的问题。
- 新增可运行的 macOS 示例,包含由 Kernel 提供的场景、主题切换、视口导航、选择、
悬停以及验证相机坐标的组件测试。
- 新增 Flutter UI package、只持有表现层状态的 viewport controller,以及使用单个
painter 的 resident 时间线 surface。
- 新增全局和局部时间线样式共用的单一 Flutter `ThemeExtension`。
- 新增统一主题驱动的视觉/音频片段、gap、container、transition、直接连接线、悬停和
选中批量绘制原语,以及按绘制顺序反向扫描的命中测试。
+1
View File
@@ -0,0 +1 @@
TODO: Add your license here.
+295
View File
@@ -0,0 +1,295 @@
# Cutdex Timeline UI
This is an application-owned internal package. Timeline semantics come from `cutdex_core`; Flutter views and interaction state remain here. Run its tests from the application workspace.
[简体中文](README.zh-CN.md)
Flutter presentation for the Cutdex timeline. The package renders immutable
Kernel/Layout publications without owning timeline semantics.
## Timecode ruler layouts
Choose full project timecode independently of its visual arrangement:
```dart
TimelineViewport(
controller: controller,
rulerStyle: TimelineRulerStyle.timecode,
rulerTimecodeLayout: TimelineRulerTimecodeLayout.centered,
child: TimelineView(controller: controller),
)
```
`TimelineRulerTimecodeLayout.inline` (default) places labels to the right of
their major marks in the same band as subdivisions. `centered` centers labels
over their major marks, keeping that anchor at the viewport edges.
Both omit subdivisions in the text's horizontal span. `overlay` retains faint
marks behind the text and uses a glyph halo rather than a rectangular mask.
Edge labels clip progressively and remain visible until their text leaves the
viewport. All three share the adaptive frame-grid density, project timecode formatting,
camera and playhead interaction. Changing the layout only repaints the ruler.
Standalone `TimelineRuler` accepts the same enum through `timecodeLayout`.
These parameters affect only `TimelineRulerStyle.timecode`; the default elapsed
ruler keeps its existing appearance.
The initial `TimelineView` uses one `CustomPainter` and Layout's reusable
structure-of-arrays viewport frame. Its work is `O(V)`, where `V` is the
resident viewport population rather than the full project size.
The bulk painter distinguishes visual content, audio content, structural gaps,
containers, and transitions. Hover and selection are presentation-only states
on `TimelineViewController`. `hitTest` scans the exact frame in reverse paint
order and returns a copied result without retaining Layout's transient buffer.
Every clip body, including drag ghosts, paints its Kernel `name` in an internal
header (blank names fall back to the element ID). Long names use one-line
ellipsis; extremely narrow clips clip/omit unreadable text. Names stay anchored
to the clip's left edge plus header padding; horizontal panning clips text at
the viewport without repositioning it or changing its ellipsis. Transition boundaries are
not clip bodies and do not acquire a separate name header.
Headers have no separate background fill.
Hosts may supply `TimelineWaveforms` to render source audio envelopes beneath
the header. The painter requests visible sources and maps each screen interval
through Kernel source time, including trimming, retiming and reverse playback.
Waveform providers load asynchronously and notify the painter when ready; no
per-clip widget or project state is introduced. Without a provider, audio retains
its decorative accent line. With a provider, unavailable data is left blank.
For visual clips, `TimelineWaveforms.hasAudioFor` reports a bound audio source
without waiting for decoding. Clips with enough height reserve a 16 px audio
strip below the filmstrip, leaving at least 20 px for thumbnails. Source loading
does not resize these regions. Silent videos, images and clips whose audio
binding has been removed keep the full filmstrip; compact clips omit the strip.
Video and standalone audio share source-time and gain mapping.
`clipHeaderHeight` (18 px), `clipHeaderPadding` (2 px horizontally),
and `clipNameTextStyle` belong to the shared theme. Text honors
ambient direction, locale and scaling and is clipped inside existing geometry;
the header does not change lanes. One TextPainter is reused for visible labels
within a paint pass and disposed afterward; no per-clip widgets or document-wide
name cache are introduced.
Gaps can be dragged but only dropped on the opened scene's Primary axis. An
off-axis pointer retains the original Primary reservation; a valid Primary
boundary preview replaces it with the new reservation. Dropping off-axis cancels
the edit. Gap reservations remain visible alongside the pointer ghost, unlike
ordinary clip landing bodies. Reordering uses the existing boundary splice and
never splits another clip or creates a connected gap.
Primary clips with connected descendants share this Primary-only reservation
behavior: the whole group follows the pointer freely above or below the axis,
while the original Primary occupancy remains until a valid new Primary preview
replaces it. Off-axis release restores the original state without history. The
placement restriction never hides the pointer ghost or ends the gesture.
An eligible audio-only Primary clip dragged above the axis keeps its pointer
ghost there, but releases below at the requested time, outside overlapping
incumbents. Primary detach uses the same outside-overlap resolver as connected
audio; it does not create an above-axis audio connection.
All Primary sources, including clips without connections, show a pointer ghost
with an opaque default fill and an outline. Reservations are hollow outlined
rectangles; both outlines use the theme's selection outline color and width.
This ghost and serial reservation appear as soon as dragging moves within Primary,
even before crossing an insertion boundary. Unconnected clips still support a
legal off-axis detach; its prepared result closes the original Primary interval.
Primary detach and cross-side dragging use the same latest-preview incumbent
geometry as same-side dragging. Displaced clips refill only after the pointer
crosses their current top threshold, not their pre-drag top. Previous previews
are read-only interaction history tied to the exact published base; every edit
is still prepared from that base and only the latest result can be committed.
Below-axis audio can follow the pointer above Primary. Releasing there retains
the requested time interval and places it below, outside all overlapping
incumbents (lane 1 if none overlap). Only the ghost is above; canonical audio
ownership stays below. Primary-band drops retain their ordinary insertion rule.
Outside-viewport release remains invalid. This fallback currently requires an
all-audio below-side carried group; it does not silently migrate mixed groups.
Cross-side targeting uses the pointer position, not whether the entire ghost
rectangle has cleared Primary. A ghost may straddle the axis during crossing;
the canonical solver still keeps the final connected body outside Primary.
Ordinary drag into/out of Primary rejects roots with connected clips, including
when those children are also selected. Primary reordering still carries children;
internal compound contents are not external connections. Lift/overwrite commands
remain separate from drag transfer. See the [Apple drag-transfer rule](https://support.apple.com/guide/final-cut-pro/verc147f195/mac).
Kernel payloads remain opaque. The host passes the same `LayoutMediaClassifier`
to `classifyContent` that it uses for Layout's media index. Primary content is
then classified without a second policy; connected media class comes directly
from Layout's resolved `LayoutPlacementClass`.
See [the architecture contract](ARCHITECTURE.md).
## Runnable example
See the [macOS example](example/README.md) for a mixed timeline, theme switching,
pan, zoom, hover, selection, connected-clip group dragging and undo/redo.
```sh
cd packages/cutdex_timeline_ui/example
flutter pub get
flutter run -d macos
```
Run these commands from the repository root.
## Usage
```dart
final controller = TimelineViewController(
version: layoutVersion,
storyline: primaryStoryline,
geometry: TimelineViewportGeometry(primaryTop: 80, primaryHeight: 48),
camera: TimelineCamera(
baseTick: 0,
pixelsPerTick: pixelsPerSecond / TimelineClock.ticksPerSecond,
),
);
TimelineView(controller: controller);
```
The application owns and disposes the controller. Publish adjacent Layout
results with `applyLayout`; use `replaceLayout` only for an explicit open,
history jump, or global rebuild.
The optional `TimelineThumbnails` host receives each tile's desired source tick,
approximate source-span ticks, logical size, and device-pixel ratio. The painter
keeps tile centers stable for a fixed tile-count level, registers visible demand
before two tiles of bidirectional prefetch, and never paints prefetched tiles
outside the viewport. Hosts should quantize nearby source ticks onto a bounded
sampling pyramid and return a nearby cached frame while a finer level loads.
For editing, construct `TimelineViewController.editable(engine: ..., geometry: ...,
camera: ..., createConnectionId: ..., createElementId: ...)` from an engine initialized with
`buildComponents`. The component root may have an empty `expanded` set. It
retains the canonical projection for coordinated history; no UI history is added.
Wrap `TimelineView` in `TimelineInteractionRegion(controller: controller, child: ...)`.
Use `controller.undo()` / `redo()` for coordinated history. See the example for
a complete setup and the architecture contract for supported drag sources.
## Explicit editing commands
`cutSelectionAtPlayhead()` cuts selected clip interiors at the definition-local
playhead; `deleteSelection()` deletes whole selected owners and their connected
descendants, closing Primary magnetically. Each command is one coordinated
Kernel/Layout history entry. A connected right half anchors to the Primary member
at the cut, resolved by Kernel. Host ID factories must return fresh IDs, including
after undo; `createElementId` is used only by explicit blade, never by dragging.
`canCutSelection`/`canDeleteSelection` expose selection eligibility; Kernel still
validates the command and `commandRejection` explains rejected edits. While the
timeline or ruler has focus: Ctrl/Cmd+B cuts, Delete/Backspace deletes,
Ctrl/Cmd+Z undoes, and Ctrl/Cmd+Shift+Z redoes. Active pointer edits ignore these
shortcuts. No implicit blade is added to drag/drop.
## Ruler and navigation
Wrap the interaction region and `TimelineView` in `TimelineViewport`. It provides
a ruler with the same effective width and horizontal origin. The ruler displays definition-local elapsed time (not
SMPTE/drop-frame timecode), with adaptive second/millisecond ticks. Click or drag
the ruler to move the presentation-only playhead. Negative seek clamps to zero;
seeking beyond the tail is allowed. No playback or media decoding is started.
`TimelineInteractionRegion` supports:
- Wheel/trackpad scrolling: two-axis pan; Shift+wheel: horizontal pan.
- Hold a dragged clip at an edge to auto-pan; corners pan both axes. Configure
`edgeScrollExtent` (48 px) and `edgeScrollMaxSpeed` (600 px/s) on the region;
zero disables it. Cancel stops without editing and retains the scrolled Camera.
- Ctrl/Cmd+wheel: zoom around the pointer, up to 32 px/frame. The minimum
scale fits the sequence duration plus 25%, rounded up to 10/30 minutes,
1/2/4 hours, then doubled as needed. Connected clips count toward the duration.
Edits update the limits without applying a new zoom; `fitTimeline()` explicitly
shows the whole sequence with tail space.
- Middle-button drag or Space+primary-button drag: pan. A single touch on blank space also pans.
- Primary mouse drag on blank space: marquee-select intersecting visible items.
Release keeps the selection; Escape, cancellation or camera navigation restores
the previous selection. A changed document root cannot restore stale identities.
Drag a selected connected member to move the whole connected selection and
carried descendants. Into Primary, independent roots without connected children are inserted consecutively
in time order, with no automatic container; one undo restores the group.
- Touch pinch or native trackpad pan/zoom: one combined focal-point transform.
A second finger cancels any active clip edit before navigation; lifting one
finger does not resume that edit.
Ruler navigation is horizontal only. Its click/drag changes the playhead, not
selection. Camera and playhead changes create no Kernel history. Ruler colors,
height, typography and playhead appearance use `TimelineThemeData`.
## Scrollbars
Use `TimelineViewport(controller: controller, child: ...)` around the clip surface
and `TimelineInteractionRegion`. The viewport owns the ruler and reserves space
for horizontal and vertical scrollbars, so painting and pointer hit testing use
the same unobscured content rectangle. Use `showRuler: false` for a surface-only
host. `TimelineScrollbars` is now a rendering component requiring explicit viewport
dimensions and bounds; it no longer configures the camera. Drag a thumb or click its track to page. Wheel, pinch,
toolbar and scrollbar navigation all use the same Camera; none creates history.
Content bounds include connected clips. Horizontal navigation starts at zero;
scrollbars appear only on overflowing axes. The navigation range includes half
a viewport beyond the content tail without extending the authored duration.
An initially empty viewport fits twenty seconds once. Subsequent zooms, resizes,
and deleting all clips preserve the chosen scale. Thumb
mapping stays fixed during a drag. Thickness and colors use theme tokens.
The wrapper registers viewport and content bounds with the controller and applies
them after layout. Initial layout calls `focusPrimary()` to center the primary
lane by moving the whole viewport. Call `focusPrimary(resetHorizontal: true)`
for a reset-position command; omit the option to preserve horizontal position.
Resizing and editing reconcile content bounds without recentering the primary.
Custom hosts can use `configureViewport` and `reconcileViewport` for the same
behavior. Positioning does not edit the timeline or create history.
The ruler draws nonnegative elapsed time, with labels beside top-aligned ticks.
Minor ticks beneath labels are omitted. `primaryLaneBackgroundColor` controls
the full-width primary lane background independently from the canvas.
## Theme
Basic edge trimming is available through `TimelineInteractionRegion`: drag the
inner left/right edge to adjust source in/out, with magnetic serial ripple and
Layout avoidance. It shares preview, cancellation, edge scrolling and history
with moves. `trimHandleWidth` (3 px) and `trimHitExtent` (6 px) are theme tokens;
zero hit extent disables edge gestures. Apply custom edge tokens above both
the input region and painter. See the architecture contract for constraints.
Finite source limits come from Kernel's `constrainMediaTrimDuration`; dragging
beyond a known media edge stops at its exact rate-adjusted boundary. Supply full
`mediaRange` for video/audio, or explicitly set `sourceExtendable` for stills and
generators. Missing bounds do not imply unlimited media. Other edit constraints
still reject through Kernel. Media availability and trim rules are maintained by core in `packages/timeline/docs/model/MEDIA_AVAILABILITY.md`.
Every timeline painter resolves the same `TimelineThemeData`. Install it once
through Flutter's extension mechanism, or pass the same type directly to one
`TimelineView` for a local override:
```dart
ThemeData(
extensions: const [TimelineThemeData.dark()],
);
TimelineView(
controller: controller,
theme: const TimelineThemeData.dark(),
);
```
The theme is resolved once during widget build, never once per painted item.
`TimelineView.thumbnails` accepts an optional host-owned `TimelineThumbnails`. The painter declares visible frame demand through `beginFrame`, `aspectRatioFor`, resolution-aware `imageFor`, and `endFrame`, and repaints when that provider notifies. Providers receive the painted logical tile size plus device pixel ratio, then own resolution bucketing, asynchronous I/O, bounded decoded-image retention, and image disposal. Timeline UI has no runtime or file-access dependency. Filmstrip tiles follow the source display aspect ratio once the provider knows it and use Kernel source-time mapping beneath clip headers, including implicit and piecewise retiming; contextual nested occurrences currently retain their ordinary fill until an occurrence-specific source mapping is supplied.
### Frame-budget subscriptions
The controller's default `Listenable` includes every view update. Use
`contentChanges` for retained clip/ruler painters that do not draw the playhead,
and `editingChanges` for inspectors and native preview synchronization. The
latter includes selection, playhead, authored changes and keyframe previews;
camera/hover changes and private clip-placement/trim geometry stay within the
viewport. Committing or cancelling a gesture still notifies editing consumers.
Pointer-driven ripple trim coalesces updates to the latest position per display
frame. Release synchronously resolves the final pointer before publication;
cancellation, view replacement and disposal discard queued callbacks. Clip
labels retain a bounded cache of shaped text across panning and rebuilds.
+200
View File
@@ -0,0 +1,200 @@
# Cutdex Timeline UI
本包由 Cutdex 应用仓库持有。时间线语义来自 `cutdex_core`,Flutter 视图与交互状态留在本包;从应用工作区运行测试。
基础边缘裁剪已接入 `TimelineInteractionRegion`:拖动片段内侧左/右边缘调整入出点,
串行片段磁性移动后缀,由 Layout 处理避让;复用移动的预览、取消、边缘滚动和历史。
主题参数 `trimHandleWidth` 默认 3 px,`trimHitExtent` 默认 6 px;命中宽度为零关闭
边缘手势。自定义时在输入区域和 Painter 上方统一安装主题。具体约束见架构文档。
素材裁剪极限统一读取 Kernel 的 `constrainMediaTrimDuration`;拖过已知素材边界时,
停在按当前速度精确换算后的合法位置。视频/音频提供完整 `mediaRange`,图片和生成内容
明确设置 `sourceExtendable`。未知范围不等于无限素材,其他编辑约束仍由 Kernel 拒绝。
素材可用范围与裁剪规则见 core 的 `packages/timeline/docs/model/MEDIA_AVAILABILITY.zh-CN.md`。
[English](README.md)
Cutdex 时间线的 Flutter 表现层。本包渲染不可变的 Kernel/Layout 发布结果,不拥有时间线
语义。
## 完整时间码的刻度排布
时间格式与视觉排布分别通过参数选择:
```dart
TimelineViewport(
controller: controller,
rulerStyle: TimelineRulerStyle.timecode,
rulerTimecodeLayout: TimelineRulerTimecodeLayout.centered,
child: TimelineView(controller: controller),
)
```
`TimelineRulerTimecodeLayout` 包含三种排布:
- `inline`:同带交错,时间码位于主刻度右侧,默认值。
- `centered`:居中锚定,时间码中心始终对准主刻度,边缘也保持锚定。
- `overlay`:淡刻度叠印,保留文字背后的淡刻度,仅在字形周围描边避让。
边缘时间码逐步裁切,文字完全移出可视范围后才隐藏。
前两种会省略文字横向范围内的短刻度。三种排布共用向下刻度、自适应帧网格密度、
工程时间码格式和播放头交互;切换排布只重绘刻度,不修改相机或时间线内容。
单独使用 `TimelineRuler` 时,参数名为 `timecodeLayout`。
该参数仅作用于 `TimelineRulerStyle.timecode`,默认的 elapsed 刻度保持原有外观。
首版 `TimelineView` 使用一个 `CustomPainter` 和 Layout 的可复用 SoA viewport frame。
工作量为 `O(V)`,其中 `V` 是 resident viewport 中的元素数量,而不是工程总元素数。
批量 Painter 区分视觉内容、音频内容、结构 gap、container 和 transition。悬停与
选中是 `TimelineViewController` 中的纯表现层状态。`hitTest` 按绘制顺序反向扫描
精确 frame,返回复制后的结果,不保留 Layout 的临时 buffer。
每个片段(包括拖拽中的片段)在自身 header 绘制 Kernel 的 `name`,空名称回退到元素 ID。
长名称单行省略,极窄片段裁切/省去无法辨认的文字;名称固定在片段左端加 header 内边距的位置,
横向平移只在视口边界裁切文字,不重新定位或改变省略位置。转场是边界记录,不额外添加片段名称 header。
header 不绘制独立背景色。
`clipHeaderHeight`(18 px)、`clipHeaderPadding`(水平 2 px)和
`clipNameTextStyle` 统一由主题控制。文字使用环境方向、语言及文字缩放,并裁切在原有
片段矩形内,不改变 lane。每次绘制复用一个 TextPainter 处理可见名称并及时释放,
不为每个片段创建 widget,也不建立全工程名称缓存。
gap 可以拖拽,但只能放置在当前场景的主轴。指针离轴时保留原来的主轴占位;
进入合法主轴边界后,由新位置的占位替代原占位。离轴释放取消编辑。
与普通片段隐藏落点不同,gap 的占位与指针拖影同时显示。重排复用现有边界 splice,
不切割其他片段,也不创建连接 gap。
带连接后代的主轴片段与 gap 共用这套“只能放置在主轴”的占位逻辑:整个片段组可以
自由跟随指针拖到上方或下方,原主轴占位保留,直到新的合法主轴预览替代它。
离轴释放恢复原位,不产生历史。限制的是放置结果,不隐藏拖影,也不结束手势。
允许离轴的纯音频主片段拖到主轴上方时,拖影继续跟随指针;释放后保留目标时间,
放在下方时间重叠片段的外侧。主轴脱离复用连接音频的外侧避让求解器,不创建上方
音频连接。
所有主轴拖拽源(包括没有连接片段的主片段)在主轴内开始拖动时,就显示跟随指针的
不透明带边框拖影;占位只显示透明底的边框矩形。两者的边框统一使用主题的选中描边
颜色和宽度。拖影和主轴占位立即显示,无须先跨越插入边界。
没有连接片段的主片段仍支持合法离轴放置;
离轴预览会闭合原来的主轴区间。
主轴脱离、跨侧拖拽与同侧拖拽统一参考上一帧的实际避让位置。被避让片段在越过其
最新 top 阈值后才回填,不再使用拖拽前的 top。旧预览只作为绑定同一已发布版本的
只读交互历史;每次编辑仍从权威基线准备,最终只提交最新结果。
下方音频可跟随指针拖到主轴上方。在上方释放时保留目标时间区间,落在下方所有时间
重叠片段的最外侧;没有重叠则落在 lane1。只有拖影在上方,权威音频归属仍在下方。
主轴区域内释放仍按普通主轴插入处理;视口外释放仍无效。此回落规则目前要求携带组
全部为下方音频,不隐式迁移混合类型片段组。
跨侧目标按鼠标点判定,不要求整个拖影矩形先离开主轴。跨越时拖影可以覆盖主轴,
但最终连接片段仍由权威求解器布局在主轴之外,不会因拖影尚未完全越界而闪回原位。
普通拖入/拖出主轴拒绝带有连接片段的移动根,即使同时选中了子片段也不例外。
主轴内重排仍携带连接片段;复合片段内部内容不算外部连接。提取/覆盖命令与普通拖拽
分别处理。依据 [Apple 拖入/拖出规则](https://support.apple.com/zh-cn/guide/final-cut-pro/verc147f195/mac)。
Kernel payload 保持不透明。宿主向 `classifyContent` 传入构建 Layout 媒体索引时使用的
同一个 `LayoutMediaClassifier`,Primary 内容便不会出现第二套分类策略;connected
媒体类别直接使用 Layout 已解析的 `LayoutPlacementClass`。
参见[架构约束](ARCHITECTURE.zh-CN.md)。
## 可运行示例
[macOS 示例](example/README.zh-CN.md)包含混合时间线、主题切换、平移、缩放、悬停、选择、
连接片段多选拖拽和撤销/重做。
从仓库根目录运行:
```sh
cd packages/cutdex_timeline_ui/example
flutter pub get
flutter run -d macos
```
## 使用方式
```dart
final controller = TimelineViewController(
version: layoutVersion,
storyline: primaryStoryline,
geometry: TimelineViewportGeometry(primaryTop: 80, primaryHeight: 48),
camera: TimelineCamera(
baseTick: 0,
pixelsPerTick: pixelsPerSecond / TimelineClock.ticksPerSecond,
),
);
TimelineView(controller: controller);
```
应用负责持有并释放 controller。相邻 Layout 发布使用 `applyLayout`;只有显式打开工程、
历史跳转或全局重建时才使用 `replaceLayout`。
编辑模式使用 `TimelineViewController.editable(engine: ..., geometry: ...,
camera: ..., createConnectionId: ..., createElementId: ...)`。引擎先通过 `buildComponents` 初始化,`expanded`
可以为空;该根保留协调历史所需的权威投影,不额外建立 UI 历史。
在 `TimelineView` 外包裹 `TimelineInteractionRegion(controller: controller, child: ...)`,
通过 `controller.undo()` / `redo()` 协调撤销/重做。完整初始化见示例,支持的拖拽范围见架构约束。
## 显式编辑命令
`cutSelectionAtPlayhead()` 在定义局部播放头处切割选中片段内部;`deleteSelection()` 删除
选中完整片段及其连接后代,主线磁性闭合。每次命令只产生一条协调的 Kernel/Layout 历史。
连接片段右半段由 Kernel 查询切割点所在的主片段并连接它。宿主 ID 工厂必须持续生成新 ID,
撤销后也不能重用;`createElementId` 仅供显式切割,拖拽不调用它。
`canCutSelection`/`canDeleteSelection` 提供选区可用性,最终仍由 Kernel 校验,失败原因见
`commandRejection`。时间线或标尺获得焦点时,Ctrl/Cmd+B 切割、Delete/Backspace 删除、
Ctrl/Cmd+Z 撤销、Ctrl/Cmd+Shift+Z 重做。活动指针编辑期间忽略这些快捷键。
拖拽放置仍不会隐式切割。
## 时间标尺和导航
把 `TimelineRuler(controller: controller)` 放在 `TimelineView` 上方,两者保持相同宽度
和水平起点。标尺显示当前 definition 的经过时间(不是 SMPTE/drop-frame 时间码),
自动调整秒/毫秒刻度密度。点击或拖拽标尺移动表现层播放位置线:负时间钳制到零,允许超出
末尾;不启动播放或媒体解码。
`TimelineInteractionRegion` 支持:
- 滚轮/触控板滚动:双轴平移;Shift+滚轮:水平平移。
- 拖动片段停在边缘时自动平移,角落同时移动两轴。区域参数 `edgeScrollExtent` 默认
48 像素,`edgeScrollMaxSpeed` 默认 600 像素/秒,任一设零可禁用。取消不修改工程,保留滚动后的 Camera。
- Ctrl/Cmd+滚轮:以指针为中心缩放,最大放大至 32 像素/帧。最远缩放按当前序列
总时长(包含连接片段)加 25% 空间,取到 10/30 分钟、1/2/4 小时等档位,超过后倍增。
编辑只更新范围,不自动切换缩放;`fitTimeline()` 主动显示整个序列并保留尾部空间。
- 中键拖拽或空格+左键拖拽:平移;触屏单指在空白处拖动也保留平移。
- 空白处鼠标左键拖拽:框选与选框相交的可见元素。松开保留选择;Esc、取消或 Camera
导航恢复原选择。文档根变化时不会恢复过期元素。拖动已选中的连接片段会移动整个连接
选区及携带后代;拖入主故事线时,独立根按时间顺序紧接插入,不自动创建容器,一次撤销恢复整组。
- 触屏双指或原生触控板平移/捏合:一次组合焦点变换。第二根手指加入时先取消片段编辑,
抬起一根手指后也不会恢复原编辑。
标尺区域只做水平导航,点击/拖动只改变播放位置,不改变选择。Camera 和播放位置变化不产生
Kernel 历史。标尺颜色、高度、文字和播放位置线外观均由 `TimelineThemeData` 管理。
## 滚动条
在标尺下方,用 `TimelineScrollbars(controller: controller, child: ...)` 包住片段区域
(放在 `TimelineInteractionRegion` 外侧),即可显示横纵滚动条。滚动条覆盖底边/右边,
不改变视口坐标。拖动滑块平移,点击轨道翻页;与滚轮、捏合、按钮共用 Camera,不产生历史。
内容范围包含连接片段,另加 48 像素工作留白。允许平移到内容外,滚动范围会包含当前视口,
可以通过滚动条返回内容。拖动期间固定滑块映射;全部内容可见时,满长滑块不响应拖动。
粗细及颜色由 `TimelineThemeData` 的滚动条主题项统一控制。
## 主题
所有时间线 Painter 都解析同一个 `TimelineThemeData`。可以通过 Flutter extension
机制全局安装,也可以把同一类型直接传给某个 `TimelineView` 进行局部覆盖:
```dart
ThemeData(
extensions: const [TimelineThemeData.dark()],
);
TimelineView(
controller: controller,
theme: const TimelineThemeData.dark(),
);
```
主题只在 Widget build 阶段解析一次,不会在每个片段绘制时重复解析。
@@ -0,0 +1,19 @@
include: package:flutter_lints/flutter.yaml
analyzer:
exclude:
- build/**
language:
strict-casts: true
strict-inference: true
strict-raw-types: true
# Additional information about this file can be found at
# https://dart.dev/guides/language/analysis-options
linter:
rules:
unnecessary_lambdas: true
unnecessary_parenthesis: true
unnecessary_statements: true
prefer_const_constructors: true
@@ -0,0 +1,45 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# IntelliJ related
*.iml
*.ipr
*.iws
.idea/
# The .vscode folder contains launch configuration and tasks you configure in
# VS Code which you may wish to be included in version control, so this line
# is commented out by default.
#.vscode/
# Flutter/Dart/Pub related
**/doc/api/
**/ios/Flutter/.last_build_id
.dart_tool/
.flutter-plugins-dependencies
.pub-cache/
.pub/
/build/
/coverage/
# Symbolication related
app.*.symbols
# Obfuscation related
app.*.map.json
# Android Studio will place build artifacts here
/android/app/debug
/android/app/profile
/android/app/release
@@ -0,0 +1,30 @@
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: "058e0af2c2b57e369d905a03ac9748b0ebf543c6"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: 058e0af2c2b57e369d905a03ac9748b0ebf543c6
base_revision: 058e0af2c2b57e369d905a03ac9748b0ebf543c6
- platform: macos
create_revision: 058e0af2c2b57e369d905a03ac9748b0ebf543c6
base_revision: 058e0af2c2b57e369d905a03ac9748b0ebf543c6
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
@@ -0,0 +1,83 @@
# Timeline UI example
[简体中文](README.zh-CN.md)
Runnable macOS Flutter application using the local workspace packages.
Requires Flutter with macOS desktop support and Xcode; the example targets macOS 12 or later.
From the repository root:
```sh
cd packages/cutdex_timeline_ui/example
flutter pub get
flutter run -d macos
```
The generated 42-second, 24 fps scene includes six primary members (visual
clips, a gap, a compound clip, audio and a disabled clip), two overlapping
visual connections above, two overlapping audio connections below, and one
overlap transition. Compound contents remain inside their definition.
The app-bar menu also opens a deterministic 3-hour, 24 fps synthetic scene with
365 Primary members and 316 connected clips, including repeated visual/audio
members and overlapping title/overlay/audio attachments. These are generated
timeline records, not real decoded media or a performance benchmark. Switching
scenes retains each document's Camera and history. End navigates to the current
tail; Reset restores the initial Camera at time zero. Horizontal navigation never
passes into negative time. Hold a clip at any edge to auto-scroll;
release uses the latest Camera, while Escape/cancel stops without committing.
- Click a clip to select it and display its name; click blank space to clear.
- Move the mouse to highlight a clip.
- Drag a clip's inner left/right edge to trim; hover/selection reveals themed
grips. Serial clips ripple, connected left trim keeps the right edge, and
container trim preserves its internal definition. Edge scrolling and Undo/Redo
also work while trimming. Invalid trim releases leave the document unchanged.
- Use arrows to pan horizontally, or scroll in either axis.
- Zoom buttons retain a visible playhead; when it is offscreen, they use the viewport center.
- Click/drag the elapsed-time ruler to seek; the line shares the clip camera.
- Ctrl/Cmd+wheel retains a visible playhead (or the viewport center); Shift+wheel pans horizontally.
- Pan with Space+drag, middle-button drag or a trackpad. Mouse-drag blank space
to marquee-select; Escape cancels. Single-touch blank-space pan is preserved.
- Pinch with two fingers to zoom while retaining the visible playhead. Trackpad translation
pans when the gesture is not pinching; scale packets do not also shift the anchor.
- Toggle the theme in the title bar; Reset restores the camera and selection.
- Drag connected selections to preview avoidance, move them above/below Primary,
or insert it into Primary. Release publishes one coordinated edit.
- Escape and pointer cancellation discard the drop. Overshooting the viewport clamps
the target to its edge; horizontal overshoot keeps scrolling, and release commits
the latest preview. Audio dragged above Primary lands below it, outside incumbents.
- Undo/Redo restore the coordinated Kernel/Layout roots; Reset only resets the view.
- Blade/Delete toolbar buttons use the selected clips; with no selection, Blade cuts
only the Primary clip at the playhead and leaves connected clips unchanged. With
explicit selection, blade cuts only interiors
under the playhead, including mixed Primary/connected selections. A connected
right half anchors to the Primary at the cut. Delete cascades owned children
and closes Primary; no handoff or gap is synthesized. The focused timeline/ruler
also accepts Ctrl/Cmd+B, Delete/Backspace, Ctrl/Cmd+Z and Ctrl/Cmd+Shift+Z.
These commands are disabled during pointer editing and never add implicit cuts
to drag/drop. Rejections appear in the status line without a partial edit.
This example demonstrates drawing and connected-selection editing APIs, including
carried descendants and consecutive group insertion into Primary.
Primary groups can reorder with carried connections; direct drag transfer out of
Primary requires roots without connected children. Valid lifts close the source
magnetically (A→B→C becomes A→C). Returning to Primary resolves a boundary reorder. Primary and connected drops use pointer halves and never cut target clips.
Playback advances only the presentation playhead. Advanced trim (roll/slip/slide),
decoded media playback, thumbnails and waveforms are not implemented here. The audio
accent is a visual marker, not a generated waveform. Colors come from one
`TimelineThemeData`; all clip coordinates come from Layout.
`lib/demo_timeline.dart` builds DTOs, the Kernel and Layout, sharing one host
media classifier with `TimelineView`. `lib/main.dart` owns and disposes the
controller and uses `TimelineInteractionRegion` for pointer integration. All edits
publish through Layout; the example never directly mutates Kernel roots.
```sh
flutter test
```
Widget tests calculate clip-body and trim-edge positions from the resident Layout frame,
verify the hit target, and assert exact authored results and undo/redo roots. Trim
preview assertions pump a frame to flush the pointer update. Application CI includes
these tests and static analysis.
@@ -0,0 +1,69 @@
# Timeline UI 示例
[English](README.md)
标题栏菜单可切换到确定性生成的 3 小时、24 fps 合成场景,包含 365 个主线成员、316 个
连接片段,以及重复的视觉/音频成员和重叠标题、叠加画面、音频连接。这是生成的时间线
元数据,不是真实解码媒体,也不是性能基准。切换场景保留各自 Camera 和编辑历史。
“末尾”定位当前尾部,“重置”恢复从时间 0 开始的初始 Camera,水平导航不会进入负时间。拖动片段停在任意边缘可自动滚动,松手
使用最新 Camera 放置,Esc/取消会停止且不提交编辑。
使用本仓库各 package 的 macOS Flutter 可运行应用。需要安装支持 macOS 桌面的
Flutter 和 Xcode;示例最低系统版本为 macOS 12。
从仓库根目录运行:
```sh
cd packages/cutdex_timeline_ui/example
flutter pub get
flutter run -d macos
```
自动生成的 42 秒、24 fps 场景包含六个主故事线成员(视觉片段、gap、复合片段、
音频和禁用片段)、上方两个时间相交的视觉连接片段、下方两个时间相交的音频连接片段,
以及一个重叠转场。复合片段内部内容保留在独立定义中。
- 点击片段选中并显示名称;点击空白清除选择。
- 鼠标悬停高亮片段。
- 方向按钮水平平移,也可以在两个轴上滚动。
- 缩放按钮保持可见播放头的位置;播放头在视口外时围绕视口中心缩放。
- 点击/拖动经过时间标尺定位播放位置;位置线与片段共用相机。
- Ctrl/Cmd+滚轮保持可见播放头(或视口中心)的位置;Shift+滚轮水平平移。
- 空格+拖拽、中键拖拽或触控板均可平移。空白处鼠标左键拖动改为框选,Esc 取消;
触屏单指在空白处拖动仍可平移。
- 双指捏合缩放保持可见播放头的位置。触控板未进入捏合时可平移;缩放包不额外移动锚点。
- 标题栏切换主题;重置按钮恢复 Camera 并清空选择。
- 拖拽连接片段选区预览避让、跨主故事线上下侧移动,或按时间顺序紧接插入主故事线;
携带后代一起移动,松手只提交一次协调编辑。
- Esc 和指针取消会丢弃预览。越过视口边缘时目标限制在边界,水平越界继续自动滚动,
松手提交最新预览。音频拖到主故事线上方会落在下方并避开已有片段。
- 撤销/重做恢复协调的 Kernel/Layout 根;重置按钮只恢复视图,不清空编辑历史。
- 工具栏切割/删除作用于选中片段。没有选区时,切割只处理播放头所在的主片段,保持连接
片段不变;存在显式选区时只处理播放头穿过内部的选中片段,支持主片段和连接
片段混合选区;连接片段右半段连接切割点所在主片段。删除连带删除连接后代,主线磁性
闭合,不承接、不补 gap。时间线/标尺有焦点时还支持 Ctrl/Cmd+B、Delete/Backspace、
Ctrl/Cmd+Z、Ctrl/Cmd+Shift+Z。活动指针编辑期间禁用命令;拖拽仍不会隐式切割。
命令被拒绝时状态栏显示原因,不会留下部分编辑。
示例展示绘制和连接片段多选编辑 API。主片段组重排可携带连接片段;直接拖出主线只接受没有连接子片段的根。有效的移出会使
主线磁性闭合(A→B→C 变为 A→C);拖回主线解析边界重排。主片段与连接片段放入主线均按鼠标前后半区
插在目标前/后,不切割目标片段。播放只推进呈现层的播放头。尚未接入高级裁剪
(roll/slip/slide)、真实媒体解码播放、缩略图和波形。
音频片段内的线是视觉标记,并非生成的波形。颜色统一来自 `TimelineThemeData`,
片段坐标统一来自 Layout。
拖动片段内侧左/右边缘可做基础裁剪,悬浮或选中时显示主题管理的手柄。串行片段磁性
移动后缀,连接片段左裁剪保持右边缘,容器裁剪不修改内部定义。裁剪支持边缘自动滚动
及撤销重做;无效裁剪松手保持文档不变。
`lib/demo_timeline.dart` 创建 DTO、Kernel 和 Layout,并与 `TimelineView` 共用宿主的
媒体分类器。`lib/main.dart` 持有并释放 controller,通过 `TimelineInteractionRegion`
接入指针事件;所有编辑都经过 Layout 协调提交,示例不直接修改 Kernel 根。
```sh
flutter test
```
Widget 测试从当前 Layout 帧计算片段主体和裁剪边缘坐标,验证命中目标,再断言确切的
编辑结果和撤销/重做根。裁剪预览断言先推进一帧以处理指针更新。应用 CI 纳入这些测试
和示例源码的静态分析。
@@ -0,0 +1,5 @@
analyzer:
exclude:
- build/**
- macos/**
include: ../analysis_options.yaml
@@ -0,0 +1,184 @@
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';
/// The demo host owns this media catalog; payload references remain opaque to
/// the UI and Kernel. The same classifier also builds Layout's media index.
LayoutMediaLeafClass classifyDemoMedia(ElementRecord record) =>
record.payloadRef == PayloadRef('demo-audio')
? LayoutMediaLeafClass.audioOnly
: LayoutMediaLeafClass.nonAudio;
TimelineCamera initialDemoCamera() => TimelineCamera(
baseTick: 0,
pixelsPerTick: 24 / TimelineClock.ticksPerSecond,
);
/// Optional deterministic three-hour scene; synthetic metadata, not real media.
TimelineViewController createDemoController({bool longTimeline = false}) {
final tailCount = longTimeline ? 359 : 0;
final kernel = TimelineKernel.importDto(
TimelineDto(
id: SequenceId('demo'),
format: TimelineFormat.fps24,
primaryStorylineId: StorylineId('primary'),
storylines: [
StorylineDto(
id: StorylineId('primary'),
elementIds: [
for (final id in [
'opening',
'street',
'gap',
'compound',
'voice',
'ending',
])
ElementId(id),
for (var i = 0; i < tailCount; i++) ElementId('long-$i'),
],
),
StorylineDto(
id: StorylineId('compound-content'),
elementIds: [ElementId('inside-a'), ElementId('inside-b')],
),
],
elements: [
_clip('opening', 8),
_clip('street', 10),
_clip('gap', 3, structure: ElementStructure.gap),
_clip('compound', 8, structure: ElementStructure.container),
_clip('voice', 6, audio: true),
_clip('ending', 8, enabled: false),
_clip('inside-a', 4),
_clip('inside-b', 4),
_clip('title', 5, extendable: true),
_clip('overlay', 7),
_clip('music', 18, audio: true),
_clip('ambience', 14, audio: true),
// Base scene is 42 seconds: 358 * 30 + 18 brings it to exactly 3h.
for (var i = 0; i < tailCount; i++) ...[
_clip('long-$i', i == tailCount - 1 ? 18 : 30, audio: i % 11 == 7),
if (i % 3 == 0) ...[
_clip('long-title-$i', 8, extendable: true),
_clip('long-overlay-$i', 12),
],
if (i % 5 == 0) _clip('long-audio-$i', 25, audio: true),
],
],
connections: [
_connection('title', 'opening', 2, ConnectionSide.above),
_connection('overlay', 'opening', 4, ConnectionSide.above),
_connection('music', 'opening', 0, ConnectionSide.below),
_connection('ambience', 'street', 2, ConnectionSide.below),
for (var i = 0; i < tailCount; i++) ...[
if (i % 3 == 0) ...[
_connection('long-title-$i', 'long-$i', 2, ConnectionSide.above),
_connection('long-overlay-$i', 'long-$i', 4, ConnectionSide.above),
],
if (i % 5 == 0)
_connection('long-audio-$i', 'long-$i', 0, ConnectionSide.below),
],
],
transitions: [
TransitionDto(
id: TransitionId('dissolve'),
storylineId: StorylineId('primary'),
leftId: ElementId('opening'),
rightId: ElementId('street'),
duration: RationalTime.seconds(1),
timing: TransitionTiming.overlap,
),
],
),
);
final primary = kernel.current.query().primaryStoryline;
final media = TimelineLayoutMediaIndex.build(
version: kernel.current,
classify: classifyDemoMedia,
);
const domain = LayoutDomainId('main');
final projection = const TimelineLayoutSceneBuilder()
.projectDefinitionWithMedia(
media: media,
definition: primary,
geometry: (_, _, _) => (height: 44, domain: domain),
);
final engine = TimelineLayoutEngine(kernel: kernel);
engine.buildComponents(
kernel: kernel,
components: TimelineLayoutComponents.build(
semantic: projection,
expanded: const [],
resolve: (_, _, _, _) => const [],
),
policy: LayoutPolicy(
version: 1,
stacks: [
for (final side in ConnectionSide.values)
LayoutStackPolicy(
stack: LayoutStackKey(scope: primary, side: side),
primaryBoundary: side == ConnectionSide.above ? 150 : 206,
domains: const [domain],
innerGap: 16,
bodyGap: 8,
),
],
),
);
var nextId = 0;
return TimelineViewController.editable(
engine: engine,
createConnectionId: () => ConnectionId('demo-link-${nextId++}'),
createElementId: () => ElementId('demo-blade-${nextId++}'),
geometry: TimelineViewportGeometry(primaryTop: 150, primaryHeight: 56),
camera: initialDemoCamera(),
);
}
ElementDto _clip(
String id,
int seconds, {
bool audio = false,
bool extendable = false,
bool enabled = true,
ElementStructure structure = ElementStructure.content,
}) => ElementDto(
id: ElementId(id),
name: id,
structure: structure,
sourceRange: TimeRange(
start: RationalTime.zero,
duration: RationalTime.seconds(seconds),
),
duration: RationalTime.seconds(seconds),
sourceExtendable: extendable,
mediaRange: structure == ElementStructure.content && !extendable
? TimeRange(
start: RationalTime.zero,
duration: RationalTime.seconds(seconds),
)
: null,
enabled: enabled,
payloadRef: structure == ElementStructure.content
? PayloadRef(audio ? 'demo-audio' : 'demo-visual')
: null,
containerStorylineId: structure == ElementStructure.container
? StorylineId('compound-content')
: null,
);
ConnectionDto _connection(
String target,
String anchor,
int seconds,
ConnectionSide side,
) => ConnectionDto(
id: ConnectionId(target),
anchorId: ElementId(anchor),
targetId: ElementId(target),
anchorTime: RationalTime.seconds(seconds),
targetTime: RationalTime.zero,
side: side,
);
@@ -0,0 +1,338 @@
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/material.dart';
import 'package:flutter/scheduler.dart';
import 'demo_timeline.dart';
void main() => runApp(const TimelineExampleApp());
class TimelineExampleApp extends StatefulWidget {
const TimelineExampleApp({super.key});
@override
State<TimelineExampleApp> createState() => _TimelineExampleAppState();
}
class _TimelineExampleAppState extends State<TimelineExampleApp>
with SingleTickerProviderStateMixin, WidgetsBindingObserver {
late final TimelineViewController _shortController = createDemoController();
TimelineViewController? _longController;
bool _longScene = false;
TimelineViewController get _controller => _longScene
? (_longController ??= createDemoController(longTimeline: true))
: _shortController;
bool _light = false;
late final Ticker _ticker;
Duration _elapsed = Duration.zero;
Duration _anchorElapsed = Duration.zero;
int _anchorTick = 0;
bool _updatingPlayhead = false;
@override
void initState() {
super.initState();
_ticker = createTicker(_advancePlayback);
_controller.addListener(_timelineChanged);
WidgetsBinding.instance.addObserver(this);
}
int get _duration => _controller.version.kernelVersion.query().storylineSpan(
_controller.storyline,
);
void _pause() {
if (!_ticker.isActive) return;
_ticker.stop();
setState(() {});
}
void _togglePlayback() {
if (_ticker.isActive) {
_pause();
return;
}
if (_duration <= 0 || _controller.isDragging) return;
if (_controller.playheadTick >= _duration) _controller.seekTo(0);
_anchorTick = _controller.playheadTick;
_elapsed = _anchorElapsed = Duration.zero;
_ticker.start();
setState(() {});
}
void _advancePlayback(Duration elapsed) {
_elapsed = elapsed;
final tick =
_anchorTick +
(elapsed - _anchorElapsed).inMicroseconds *
TimelineClock.ticksPerSecond ~/
Duration.microsecondsPerSecond;
final end = _duration;
_updatingPlayhead = true;
try {
_controller.seekTo(tick.clamp(0, end));
} finally {
_updatingPlayhead = false;
}
if (tick >= end) _pause();
}
void _timelineChanged() {
if (!_ticker.isActive || _updatingPlayhead) return;
// Seeking rebases the clock; editing gestures pause playback.
_anchorTick = _controller.playheadTick;
_anchorElapsed = _elapsed;
if (_controller.isDragging || _anchorTick >= _duration) _pause();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state != AppLifecycleState.resumed) _pause();
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
_controller.removeListener(_timelineChanged);
_ticker.dispose();
_shortController.dispose();
_longController?.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
const dark = TimelineThemeData.dark();
final timelineTheme = _light
? dark.copyWith(
backgroundColor: const Color(0xfff1f3f6),
gapColor: const Color(0xffdce1e8),
connectionLineColor: const Color(0xff505966),
selectionOutlineColor: const Color(0xff111827),
rulerBackgroundColor: const Color(0xffe2e6ec),
rulerTickColor: const Color(0xff505966),
scrollbarTrackColor: const Color(0xffe2e6ec),
scrollbarThumbColor: const Color(0xff707986),
rulerTextStyle: dark.rulerTextStyle.copyWith(
color: const Color(0xff374151),
),
)
: dark;
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Cutdex Timeline Example',
theme: ThemeData(
brightness: _light ? Brightness.light : Brightness.dark,
colorSchemeSeed: const Color(0xff4e82d8),
extensions: [timelineTheme],
),
home: Scaffold(
appBar: AppBar(
title: const Text('Timeline · 示例 / Example'),
actions: [
PopupMenuButton<bool>(
tooltip: '切换场景 / Switch scene',
icon: const Icon(Icons.video_library_outlined),
initialValue: _longScene,
onSelected: (value) {
_pause();
_controller.cancelDrag();
_controller.removeListener(_timelineChanged);
setState(() => _longScene = value);
_controller.addListener(_timelineChanged);
},
itemBuilder: (_) => const [
PopupMenuItem(value: false, child: Text('短场景 / Short scene')),
PopupMenuItem(value: true, child: Text('3 小时 / 3 hours')),
],
),
IconButton(
tooltip: '切换主题 / Toggle theme',
onPressed: () => setState(() => _light = !_light),
icon: Icon(_light ? Icons.dark_mode : Icons.light_mode),
),
],
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.all(12),
child: Text(
'空白左键框选 · 标尺定位 · 滚动平移 · Ctrl/Cmd+滚轮缩放 · 空格拖动/中键平移\n'
'Blank mouse drag to select · Ruler to seek · Scroll to pan · Ctrl/Cmd+wheel to zoom · Space/middle to pan',
),
),
Expanded(
child: LayoutBuilder(
builder: (context, constraints) => Column(
children: [
Wrap(
alignment: WrapAlignment.center,
children: [
IconButton(
key: const Key('playback-toggle'),
tooltip: _ticker.isActive
? '暂停 / Pause'
: '播放 / Play',
onPressed: _togglePlayback,
icon: Icon(
_ticker.isActive ? Icons.pause : Icons.play_arrow,
),
),
IconButton(
tooltip: '向左 / Pan left',
onPressed: () =>
_controller.panBy(horizontalPixels: -120),
icon: const Icon(Icons.arrow_back),
),
IconButton(
tooltip: '向右 / Pan right',
onPressed: () =>
_controller.panBy(horizontalPixels: 120),
icon: const Icon(Icons.arrow_forward),
),
IconButton(
tooltip: '缩小 / Zoom out',
onPressed: () =>
_zoom(constraints.maxWidth, 1 / 1.25),
icon: const Icon(Icons.zoom_out),
),
IconButton(
tooltip: '放大 / Zoom in',
onPressed: () => _zoom(constraints.maxWidth, 1.25),
icon: const Icon(Icons.zoom_in),
),
TextButton.icon(
onPressed: () {
_controller.cancelDrag();
_pause();
_controller.seekTo(0);
_controller.setCamera(initialDemoCamera());
_controller.clearSelection();
_controller.setHoveredIdentity(null);
},
icon: const Icon(Icons.restart_alt),
label: const Text('重置 / Reset'),
),
TextButton(
onPressed: () {
_controller.cancelDrag();
final q = _controller.version.kernelVersion.query();
_controller.setCamera(
TimelineCamera(
baseTick: q.storylineSpan(
_controller.storyline,
),
pixelsPerTick: _controller.camera.pixelsPerTick,
verticalOffset:
_controller.camera.verticalOffset,
).panBy(
horizontalPixels: -constraints.maxWidth * 0.75,
),
);
},
child: const Text('末尾 / End'),
),
ListenableBuilder(
listenable: _controller,
builder: (context, _) => Row(
mainAxisSize: MainAxisSize.min,
children: [
IconButton(
tooltip: '切割 / Blade (Ctrl/Cmd+B)',
icon: const Icon(Icons.content_cut),
onPressed: _controller.canCutSelection
? _controller.cutSelectionAtPlayhead
: null,
),
IconButton(
tooltip: '删除 / Delete',
icon: const Icon(Icons.delete_outline),
onPressed: _controller.canDeleteSelection
? _controller.deleteSelection
: null,
),
IconButton(
tooltip: '撤销 / Undo',
icon: const Icon(Icons.undo),
onPressed: _controller.canUndo
? _controller.undo
: null,
),
IconButton(
tooltip: '重做 / Redo',
icon: const Icon(Icons.redo),
onPressed: _controller.canRedo
? _controller.redo
: null,
),
],
),
),
],
),
Expanded(
child: TimelineViewport(
controller: _controller,
child: TimelineInteractionRegion(
controller: _controller,
child: TimelineView(
key: const Key('timeline-surface'),
controller: _controller,
classifyContent: classifyDemoMedia,
),
),
),
),
],
),
),
),
ListenableBuilder(
listenable: _controller,
builder: (context, _) => Padding(
padding: const EdgeInsets.all(12),
child: SizedBox(
height: 40,
child: Text(
'选中 / Selected: ${_selectionLabel()} · '
'${(_controller.camera.pixelsPerTick * TimelineClock.ticksPerSecond).toStringAsFixed(1)} px/s\n'
'${_controller.commandRejection ?? _controller.dragRejection ?? (_controller.isDragging ? '预览中,靠边自动滚动 / Preview, hold at edge to scroll' : (_longScene ? '3 小时合成场景 / 3-hour synthetic scene' : '片段拖拽 / Clip drag'))}',
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
),
),
),
],
),
),
);
}
void _zoom(double width, double factor) {
_controller.zoomBy(
scale: factor,
viewport: TimelineViewportRect(width: width, height: 0),
);
}
String _selectionLabel() {
if (_controller.selectedIdentities.isEmpty) return '—';
final identity = _controller.selectedIdentities.first;
final handle = switch (identity) {
ElementHandle value => value,
LayoutBodyId value => value.owner,
_ => null,
};
if (handle == null) {
return identity is TransitionId ? identity.value : '$identity';
}
final record = _controller.version.kernelVersion.query().element(handle);
return record.name ?? record.id.value;
}
}
@@ -0,0 +1,7 @@
# Flutter-related
**/Flutter/ephemeral/
**/Pods/
# Xcode-related
**/dgph
**/xcuserdata/
@@ -0,0 +1 @@
#include "ephemeral/Flutter-Generated.xcconfig"
@@ -0,0 +1 @@
#include "ephemeral/Flutter-Generated.xcconfig"
@@ -0,0 +1,12 @@
//
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import cutdex_native_flutter
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
CutdexRuntimePlugin.register(with: registry.registrar(forPlugin: "CutdexRuntimePlugin"))
}
@@ -0,0 +1,705 @@
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 54;
objects = {
/* Begin PBXAggregateTarget section */
33CC111A2044C6BA0003C045 /* Flutter Assemble */ = {
isa = PBXAggregateTarget;
buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */;
buildPhases = (
33CC111E2044C6BF0003C045 /* ShellScript */,
);
dependencies = (
);
name = "Flutter Assemble";
productName = FLX;
};
/* End PBXAggregateTarget section */
/* Begin PBXBuildFile section */
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 331C80D7294CF71000263BE5 /* RunnerTests.swift */; };
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; };
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; };
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; };
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; };
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
331C80D9294CF71000263BE5 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 33CC10EC2044A3C60003C045;
remoteInfo = Runner;
};
33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = {
isa = PBXContainerItemProxy;
containerPortal = 33CC10E52044A3C60003C045 /* Project object */;
proxyType = 1;
remoteGlobalIDString = 33CC111A2044C6BA0003C045;
remoteInfo = FLX;
};
/* End PBXContainerItemProxy section */
/* Begin PBXCopyFilesBuildPhase section */
33CC110E2044A8840003C045 /* Bundle Framework */ = {
isa = PBXCopyFilesBuildPhase;
buildActionMask = 2147483647;
dstPath = "";
dstSubfolderSpec = 10;
files = (
);
name = "Bundle Framework";
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXCopyFilesBuildPhase section */
/* Begin PBXFileReference section */
331C80D5294CF71000263BE5 /* RunnerTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = RunnerTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };
331C80D7294CF71000263BE5 /* RunnerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunnerTests.swift; sourceTree = "<group>"; };
333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = "<group>"; };
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = "<group>"; };
33CC10ED2044A3C60003C045 /* timeline_ui_example.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "timeline_ui_example.app"; sourceTree = BUILT_PRODUCTS_DIR; };
33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = "<group>"; };
33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = "<group>"; };
33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = "<group>"; };
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = "<group>"; };
33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = "<group>"; };
33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = "<group>"; };
33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = "<group>"; };
33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = "<group>"; };
33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = "<group>"; };
33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = "<group>"; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = "<group>"; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
331C80D2294CF70F00263BE5 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
33CC10EA2044A3C60003C045 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
331C80D6294CF71000263BE5 /* RunnerTests */ = {
isa = PBXGroup;
children = (
331C80D7294CF71000263BE5 /* RunnerTests.swift */,
);
path = RunnerTests;
sourceTree = "<group>";
};
33BA886A226E78AF003329D5 /* Configs */ = {
isa = PBXGroup;
children = (
33E5194F232828860026EE4D /* AppInfo.xcconfig */,
9740EEB21CF90195004384FC /* Debug.xcconfig */,
7AFA3C8E1D35360C0083082E /* Release.xcconfig */,
333000ED22D3DE5D00554162 /* Warnings.xcconfig */,
);
path = Configs;
sourceTree = "<group>";
};
33CC10E42044A3C60003C045 = {
isa = PBXGroup;
children = (
33FAB671232836740065AC1E /* Runner */,
33CEB47122A05771004F2AC0 /* Flutter */,
331C80D6294CF71000263BE5 /* RunnerTests */,
33CC10EE2044A3C60003C045 /* Products */,
D73912EC22F37F3D000D13A0 /* Frameworks */,
);
sourceTree = "<group>";
};
33CC10EE2044A3C60003C045 /* Products */ = {
isa = PBXGroup;
children = (
33CC10ED2044A3C60003C045 /* timeline_ui_example.app */,
331C80D5294CF71000263BE5 /* RunnerTests.xctest */,
);
name = Products;
sourceTree = "<group>";
};
33CC11242044D66E0003C045 /* Resources */ = {
isa = PBXGroup;
children = (
33CC10F22044A3C60003C045 /* Assets.xcassets */,
33CC10F42044A3C60003C045 /* MainMenu.xib */,
33CC10F72044A3C60003C045 /* Info.plist */,
);
name = Resources;
path = ..;
sourceTree = "<group>";
};
33CEB47122A05771004F2AC0 /* Flutter */ = {
isa = PBXGroup;
children = (
335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */,
33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */,
33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */,
33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */,
);
path = Flutter;
sourceTree = "<group>";
};
33FAB671232836740065AC1E /* Runner */ = {
isa = PBXGroup;
children = (
33CC10F02044A3C60003C045 /* AppDelegate.swift */,
33CC11122044BFA00003C045 /* MainFlutterWindow.swift */,
33E51913231747F40026EE4D /* DebugProfile.entitlements */,
33E51914231749380026EE4D /* Release.entitlements */,
33CC11242044D66E0003C045 /* Resources */,
33BA886A226E78AF003329D5 /* Configs */,
);
path = Runner;
sourceTree = "<group>";
};
D73912EC22F37F3D000D13A0 /* Frameworks */ = {
isa = PBXGroup;
children = (
);
name = Frameworks;
sourceTree = "<group>";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
331C80D4294CF70F00263BE5 /* RunnerTests */ = {
isa = PBXNativeTarget;
buildConfigurationList = 331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */;
buildPhases = (
331C80D1294CF70F00263BE5 /* Sources */,
331C80D2294CF70F00263BE5 /* Frameworks */,
331C80D3294CF70F00263BE5 /* Resources */,
);
buildRules = (
);
dependencies = (
331C80DA294CF71000263BE5 /* PBXTargetDependency */,
);
name = RunnerTests;
productName = RunnerTests;
productReference = 331C80D5294CF71000263BE5 /* RunnerTests.xctest */;
productType = "com.apple.product-type.bundle.unit-test";
};
33CC10EC2044A3C60003C045 /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
33CC10E92044A3C60003C045 /* Sources */,
33CC10EA2044A3C60003C045 /* Frameworks */,
33CC10EB2044A3C60003C045 /* Resources */,
33CC110E2044A8840003C045 /* Bundle Framework */,
3399D490228B24CF009A79C7 /* ShellScript */,
);
buildRules = (
);
dependencies = (
33CC11202044C79F0003C045 /* PBXTargetDependency */,
);
name = Runner;
productName = Runner;
productReference = 33CC10ED2044A3C60003C045 /* timeline_ui_example.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
33CC10E52044A3C60003C045 /* Project object */ = {
isa = PBXProject;
attributes = {
BuildIndependentTargetsInParallel = YES;
LastSwiftUpdateCheck = 0920;
LastUpgradeCheck = 1510;
ORGANIZATIONNAME = "";
TargetAttributes = {
331C80D4294CF70F00263BE5 = {
CreatedOnToolsVersion = 14.0;
TestTargetID = 33CC10EC2044A3C60003C045;
};
33CC10EC2044A3C60003C045 = {
CreatedOnToolsVersion = 9.2;
LastSwiftMigration = 1100;
ProvisioningStyle = Automatic;
SystemCapabilities = {
com.apple.Sandbox = {
enabled = 1;
};
};
};
33CC111A2044C6BA0003C045 = {
CreatedOnToolsVersion = 9.2;
ProvisioningStyle = Manual;
};
};
};
buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */;
compatibilityVersion = "Xcode 9.3";
developmentRegion = en;
hasScannedForEncodings = 0;
knownRegions = (
en,
Base,
);
mainGroup = 33CC10E42044A3C60003C045;
productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
projectDirPath = "";
projectRoot = "";
targets = (
33CC10EC2044A3C60003C045 /* Runner */,
331C80D4294CF70F00263BE5 /* RunnerTests */,
33CC111A2044C6BA0003C045 /* Flutter Assemble */,
);
};
/* End PBXProject section */
/* Begin PBXResourcesBuildPhase section */
331C80D3294CF70F00263BE5 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
33CC10EB2044A3C60003C045 /* Resources */ = {
isa = PBXResourcesBuildPhase;
buildActionMask = 2147483647;
files = (
33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */,
33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
3399D490228B24CF009A79C7 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
alwaysOutOfDate = 1;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
);
outputFileListPaths = (
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n";
};
33CC111E2044C6BF0003C045 /* ShellScript */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
Flutter/ephemeral/FlutterInputs.xcfilelist,
);
inputPaths = (
Flutter/ephemeral/tripwire,
);
outputFileListPaths = (
Flutter/ephemeral/FlutterOutputs.xcfilelist,
);
outputPaths = (
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire";
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
331C80D1294CF70F00263BE5 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
331C80D8294CF71000263BE5 /* RunnerTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
33CC10E92044A3C60003C045 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */,
33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */,
335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXSourcesBuildPhase section */
/* Begin PBXTargetDependency section */
331C80DA294CF71000263BE5 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 33CC10EC2044A3C60003C045 /* Runner */;
targetProxy = 331C80D9294CF71000263BE5 /* PBXContainerItemProxy */;
};
33CC11202044C79F0003C045 /* PBXTargetDependency */ = {
isa = PBXTargetDependency;
target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */;
targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */;
};
/* End PBXTargetDependency section */
/* Begin PBXVariantGroup section */
33CC10F42044A3C60003C045 /* MainMenu.xib */ = {
isa = PBXVariantGroup;
children = (
33CC10F52044A3C60003C045 /* Base */,
);
name = MainMenu.xib;
path = Runner;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */
/* Begin XCBuildConfiguration section */
331C80DB294CF71000263BE5 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = dev.cutdex.timelineUiExample.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/timeline_ui_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/timeline_ui_example";
};
name = Debug;
};
331C80DC294CF71000263BE5 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = dev.cutdex.timelineUiExample.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/timeline_ui_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/timeline_ui_example";
};
name = Release;
};
331C80DD294CF71000263BE5 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
BUNDLE_LOADER = "$(TEST_HOST)";
CURRENT_PROJECT_VERSION = 1;
GENERATE_INFOPLIST_FILE = YES;
MARKETING_VERSION = 1.0;
PRODUCT_BUNDLE_IDENTIFIER = dev.cutdex.timelineUiExample.RunnerTests;
PRODUCT_NAME = "$(TARGET_NAME)";
SWIFT_VERSION = 5.0;
TEST_HOST = "$(BUILT_PRODUCTS_DIR)/timeline_ui_example.app/$(BUNDLE_EXECUTABLE_FOLDER_PATH)/timeline_ui_example";
};
name = Profile;
};
338D0CE9231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Profile;
};
338D0CEA231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
};
name = Profile;
};
338D0CEB231458BD00FA5F75 /* Profile */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Profile;
};
33CC10F92044A3C60003C045 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = dwarf;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_TESTABILITY = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_DYNAMIC_NO_PIC = NO;
GCC_NO_COMMON_BLOCKS = YES;
GCC_OPTIMIZATION_LEVEL = 0;
GCC_PREPROCESSOR_DEFINITIONS = (
"DEBUG=1",
"$(inherited)",
);
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = macosx;
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
};
name = Debug;
};
33CC10FA2044A3C60003C045 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */;
buildSettings = {
ALWAYS_SEARCH_USER_PATHS = NO;
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
CLANG_ANALYZER_NONNULL = YES;
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
CLANG_CXX_LIBRARY = "libc++";
CLANG_ENABLE_MODULES = YES;
CLANG_ENABLE_OBJC_ARC = YES;
CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
CLANG_WARN_BOOL_CONVERSION = YES;
CLANG_WARN_CONSTANT_CONVERSION = YES;
CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
CLANG_WARN_EMPTY_BODY = YES;
CLANG_WARN_ENUM_CONVERSION = YES;
CLANG_WARN_INFINITE_RECURSION = YES;
CLANG_WARN_INT_CONVERSION = YES;
CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
CLANG_WARN_SUSPICIOUS_MOVE = YES;
CODE_SIGN_IDENTITY = "-";
COPY_PHASE_STRIP = NO;
DEAD_CODE_STRIPPING = YES;
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
ENABLE_NS_ASSERTIONS = NO;
ENABLE_STRICT_OBJC_MSGSEND = YES;
ENABLE_USER_SCRIPT_SANDBOXING = NO;
GCC_C_LANGUAGE_STANDARD = gnu11;
GCC_NO_COMMON_BLOCKS = YES;
GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
MACOSX_DEPLOYMENT_TARGET = 15.0;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = macosx;
SWIFT_COMPILATION_MODE = wholemodule;
SWIFT_OPTIMIZATION_LEVEL = "-O";
};
name = Release;
};
33CC10FC2044A3C60003C045 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
SWIFT_VERSION = 5.0;
};
name = Debug;
};
33CC10FD2044A3C60003C045 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements;
CODE_SIGN_STYLE = Automatic;
COMBINE_HIDPI_IMAGES = YES;
INFOPLIST_FILE = Runner/Info.plist;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/../Frameworks",
);
PROVISIONING_PROFILE_SPECIFIER = "";
SWIFT_VERSION = 5.0;
};
name = Release;
};
33CC111C2044C6BA0003C045 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Manual;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Debug;
};
33CC111D2044C6BA0003C045 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
CODE_SIGN_STYLE = Automatic;
PRODUCT_NAME = "$(TARGET_NAME)";
};
name = Release;
};
/* End XCBuildConfiguration section */
/* Begin XCConfigurationList section */
331C80DE294CF71000263BE5 /* Build configuration list for PBXNativeTarget "RunnerTests" */ = {
isa = XCConfigurationList;
buildConfigurations = (
331C80DB294CF71000263BE5 /* Debug */,
331C80DC294CF71000263BE5 /* Release */,
331C80DD294CF71000263BE5 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
33CC10F92044A3C60003C045 /* Debug */,
33CC10FA2044A3C60003C045 /* Release */,
338D0CE9231458BD00FA5F75 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = {
isa = XCConfigurationList;
buildConfigurations = (
33CC10FC2044A3C60003C045 /* Debug */,
33CC10FD2044A3C60003C045 /* Release */,
338D0CEA231458BD00FA5F75 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = {
isa = XCConfigurationList;
buildConfigurations = (
33CC111C2044C6BA0003C045 /* Debug */,
33CC111D2044C6BA0003C045 /* Release */,
338D0CEB231458BD00FA5F75 /* Profile */,
);
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
};
rootObject = 33CC10E52044A3C60003C045 /* Project object */;
}
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,99 @@
<?xml version="1.0" encoding="UTF-8"?>
<Scheme
LastUpgradeVersion = "1510"
version = "1.3">
<BuildAction
parallelizeBuildables = "YES"
buildImplicitDependencies = "YES">
<BuildActionEntries>
<BuildActionEntry
buildForTesting = "YES"
buildForRunning = "YES"
buildForProfiling = "YES"
buildForArchiving = "YES"
buildForAnalyzing = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "timeline_ui_example.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildActionEntry>
</BuildActionEntries>
</BuildAction>
<TestAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
shouldUseLaunchSchemeArgsEnv = "YES">
<MacroExpansion>
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "timeline_ui_example.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</MacroExpansion>
<Testables>
<TestableReference
skipped = "NO"
parallelizable = "YES">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "331C80D4294CF70F00263BE5"
BuildableName = "RunnerTests.xctest"
BlueprintName = "RunnerTests"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</TestableReference>
</Testables>
</TestAction>
<LaunchAction
buildConfiguration = "Debug"
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
launchStyle = "0"
useCustomWorkingDirectory = "NO"
ignoresPersistentStateOnLaunch = "NO"
debugDocumentVersioning = "YES"
debugServiceExtension = "internal"
enableGPUValidationMode = "1"
allowLocationSimulation = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "timeline_ui_example.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</LaunchAction>
<ProfileAction
buildConfiguration = "Profile"
shouldUseLaunchSchemeArgsEnv = "YES"
savedToolIdentifier = ""
useCustomWorkingDirectory = "NO"
debugDocumentVersioning = "YES">
<BuildableProductRunnable
runnableDebuggingMode = "0">
<BuildableReference
BuildableIdentifier = "primary"
BlueprintIdentifier = "33CC10EC2044A3C60003C045"
BuildableName = "timeline_ui_example.app"
BlueprintName = "Runner"
ReferencedContainer = "container:Runner.xcodeproj">
</BuildableReference>
</BuildableProductRunnable>
</ProfileAction>
<AnalyzeAction
buildConfiguration = "Debug">
</AnalyzeAction>
<ArchiveAction
buildConfiguration = "Release"
revealArchiveInOrganizer = "YES">
</ArchiveAction>
</Scheme>
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Runner.xcodeproj">
</FileRef>
</Workspace>
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,13 @@
import Cocoa
import FlutterMacOS
@main
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
override func applicationSupportsSecureRestorableState(_ app: NSApplication) -> Bool {
return true
}
}
@@ -0,0 +1,68 @@
{
"images" : [
{
"size" : "16x16",
"idiom" : "mac",
"filename" : "app_icon_16.png",
"scale" : "1x"
},
{
"size" : "16x16",
"idiom" : "mac",
"filename" : "app_icon_32.png",
"scale" : "2x"
},
{
"size" : "32x32",
"idiom" : "mac",
"filename" : "app_icon_32.png",
"scale" : "1x"
},
{
"size" : "32x32",
"idiom" : "mac",
"filename" : "app_icon_64.png",
"scale" : "2x"
},
{
"size" : "128x128",
"idiom" : "mac",
"filename" : "app_icon_128.png",
"scale" : "1x"
},
{
"size" : "128x128",
"idiom" : "mac",
"filename" : "app_icon_256.png",
"scale" : "2x"
},
{
"size" : "256x256",
"idiom" : "mac",
"filename" : "app_icon_256.png",
"scale" : "1x"
},
{
"size" : "256x256",
"idiom" : "mac",
"filename" : "app_icon_512.png",
"scale" : "2x"
},
{
"size" : "512x512",
"idiom" : "mac",
"filename" : "app_icon_512.png",
"scale" : "1x"
},
{
"size" : "512x512",
"idiom" : "mac",
"filename" : "app_icon_1024.png",
"scale" : "2x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 520 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 36 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

@@ -0,0 +1,343 @@
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.Cocoa.XIB" version="3.0" toolsVersion="14490.70" targetRuntime="MacOSX.Cocoa" propertyAccessControl="none" useAutolayout="YES" customObjectInstantitationMethod="direct">
<dependencies>
<deployment identifier="macosx"/>
<plugIn identifier="com.apple.InterfaceBuilder.CocoaPlugin" version="14490.70"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<objects>
<customObject id="-2" userLabel="File's Owner" customClass="NSApplication">
<connections>
<outlet property="delegate" destination="Voe-Tx-rLC" id="GzC-gU-4Uq"/>
</connections>
</customObject>
<customObject id="-1" userLabel="First Responder" customClass="FirstResponder"/>
<customObject id="-3" userLabel="Application" customClass="NSObject"/>
<customObject id="Voe-Tx-rLC" customClass="AppDelegate" customModule="Runner" customModuleProvider="target">
<connections>
<outlet property="applicationMenu" destination="uQy-DD-JDr" id="XBo-yE-nKs"/>
<outlet property="mainFlutterWindow" destination="QvC-M9-y7g" id="gIp-Ho-8D9"/>
</connections>
</customObject>
<customObject id="YLy-65-1bz" customClass="NSFontManager"/>
<menu title="Main Menu" systemMenu="main" id="AYu-sK-qS6">
<items>
<menuItem title="APP_NAME" id="1Xt-HY-uBw">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="APP_NAME" systemMenu="apple" id="uQy-DD-JDr">
<items>
<menuItem title="About APP_NAME" id="5kV-Vb-QxS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontStandardAboutPanel:" target="-1" id="Exp-CZ-Vem"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="VOq-y0-SEH"/>
<menuItem title="Preferences…" keyEquivalent="," id="BOF-NM-1cW"/>
<menuItem isSeparatorItem="YES" id="wFC-TO-SCJ"/>
<menuItem title="Services" id="NMo-om-nkz">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Services" systemMenu="services" id="hz9-B4-Xy5"/>
</menuItem>
<menuItem isSeparatorItem="YES" id="4je-JR-u6R"/>
<menuItem title="Hide APP_NAME" keyEquivalent="h" id="Olw-nP-bQN">
<connections>
<action selector="hide:" target="-1" id="PnN-Uc-m68"/>
</connections>
</menuItem>
<menuItem title="Hide Others" keyEquivalent="h" id="Vdr-fp-XzO">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="hideOtherApplications:" target="-1" id="VT4-aY-XCT"/>
</connections>
</menuItem>
<menuItem title="Show All" id="Kd2-mp-pUS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="unhideAllApplications:" target="-1" id="Dhg-Le-xox"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="kCx-OE-vgT"/>
<menuItem title="Quit APP_NAME" keyEquivalent="q" id="4sb-4s-VLi">
<connections>
<action selector="terminate:" target="-1" id="Te7-pn-YzF"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Edit" id="5QF-Oa-p0T">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Edit" id="W48-6f-4Dl">
<items>
<menuItem title="Undo" keyEquivalent="z" id="dRJ-4n-Yzg">
<connections>
<action selector="undo:" target="-1" id="M6e-cu-g7V"/>
</connections>
</menuItem>
<menuItem title="Redo" keyEquivalent="Z" id="6dh-zS-Vam">
<connections>
<action selector="redo:" target="-1" id="oIA-Rs-6OD"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="WRV-NI-Exz"/>
<menuItem title="Cut" keyEquivalent="x" id="uRl-iY-unG">
<connections>
<action selector="cut:" target="-1" id="YJe-68-I9s"/>
</connections>
</menuItem>
<menuItem title="Copy" keyEquivalent="c" id="x3v-GG-iWU">
<connections>
<action selector="copy:" target="-1" id="G1f-GL-Joy"/>
</connections>
</menuItem>
<menuItem title="Paste" keyEquivalent="v" id="gVA-U4-sdL">
<connections>
<action selector="paste:" target="-1" id="UvS-8e-Qdg"/>
</connections>
</menuItem>
<menuItem title="Paste and Match Style" keyEquivalent="V" id="WeT-3V-zwk">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="pasteAsPlainText:" target="-1" id="cEh-KX-wJQ"/>
</connections>
</menuItem>
<menuItem title="Delete" id="pa3-QI-u2k">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="delete:" target="-1" id="0Mk-Ml-PaM"/>
</connections>
</menuItem>
<menuItem title="Select All" keyEquivalent="a" id="Ruw-6m-B2m">
<connections>
<action selector="selectAll:" target="-1" id="VNm-Mi-diN"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="uyl-h8-XO2"/>
<menuItem title="Find" id="4EN-yA-p0u">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Find" id="1b7-l0-nxx">
<items>
<menuItem title="Find…" tag="1" keyEquivalent="f" id="Xz5-n4-O0W">
<connections>
<action selector="performFindPanelAction:" target="-1" id="cD7-Qs-BN4"/>
</connections>
</menuItem>
<menuItem title="Find and Replace…" tag="12" keyEquivalent="f" id="YEy-JH-Tfz">
<modifierMask key="keyEquivalentModifierMask" option="YES" command="YES"/>
<connections>
<action selector="performFindPanelAction:" target="-1" id="WD3-Gg-5AJ"/>
</connections>
</menuItem>
<menuItem title="Find Next" tag="2" keyEquivalent="g" id="q09-fT-Sye">
<connections>
<action selector="performFindPanelAction:" target="-1" id="NDo-RZ-v9R"/>
</connections>
</menuItem>
<menuItem title="Find Previous" tag="3" keyEquivalent="G" id="OwM-mh-QMV">
<connections>
<action selector="performFindPanelAction:" target="-1" id="HOh-sY-3ay"/>
</connections>
</menuItem>
<menuItem title="Use Selection for Find" tag="7" keyEquivalent="e" id="buJ-ug-pKt">
<connections>
<action selector="performFindPanelAction:" target="-1" id="U76-nv-p5D"/>
</connections>
</menuItem>
<menuItem title="Jump to Selection" keyEquivalent="j" id="S0p-oC-mLd">
<connections>
<action selector="centerSelectionInVisibleArea:" target="-1" id="IOG-6D-g5B"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Spelling and Grammar" id="Dv1-io-Yv7">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Spelling" id="3IN-sU-3Bg">
<items>
<menuItem title="Show Spelling and Grammar" keyEquivalent=":" id="HFo-cy-zxI">
<connections>
<action selector="showGuessPanel:" target="-1" id="vFj-Ks-hy3"/>
</connections>
</menuItem>
<menuItem title="Check Document Now" keyEquivalent=";" id="hz2-CU-CR7">
<connections>
<action selector="checkSpelling:" target="-1" id="fz7-VC-reM"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="bNw-od-mp5"/>
<menuItem title="Check Spelling While Typing" id="rbD-Rh-wIN">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleContinuousSpellChecking:" target="-1" id="7w6-Qz-0kB"/>
</connections>
</menuItem>
<menuItem title="Check Grammar With Spelling" id="mK6-2p-4JG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleGrammarChecking:" target="-1" id="muD-Qn-j4w"/>
</connections>
</menuItem>
<menuItem title="Correct Spelling Automatically" id="78Y-hA-62v">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticSpellingCorrection:" target="-1" id="2lM-Qi-WAP"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Substitutions" id="9ic-FL-obx">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Substitutions" id="FeM-D8-WVr">
<items>
<menuItem title="Show Substitutions" id="z6F-FW-3nz">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="orderFrontSubstitutionsPanel:" target="-1" id="oku-mr-iSq"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="gPx-C9-uUO"/>
<menuItem title="Smart Copy/Paste" id="9yt-4B-nSM">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleSmartInsertDelete:" target="-1" id="3IJ-Se-DZD"/>
</connections>
</menuItem>
<menuItem title="Smart Quotes" id="hQb-2v-fYv">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticQuoteSubstitution:" target="-1" id="ptq-xd-QOA"/>
</connections>
</menuItem>
<menuItem title="Smart Dashes" id="rgM-f4-ycn">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDashSubstitution:" target="-1" id="oCt-pO-9gS"/>
</connections>
</menuItem>
<menuItem title="Smart Links" id="cwL-P1-jid">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticLinkDetection:" target="-1" id="Gip-E3-Fov"/>
</connections>
</menuItem>
<menuItem title="Data Detectors" id="tRr-pd-1PS">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticDataDetection:" target="-1" id="R1I-Nq-Kbl"/>
</connections>
</menuItem>
<menuItem title="Text Replacement" id="HFQ-gK-NFA">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="toggleAutomaticTextReplacement:" target="-1" id="DvP-Fe-Py6"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Transformations" id="2oI-Rn-ZJC">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Transformations" id="c8a-y6-VQd">
<items>
<menuItem title="Make Upper Case" id="vmV-6d-7jI">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="uppercaseWord:" target="-1" id="sPh-Tk-edu"/>
</connections>
</menuItem>
<menuItem title="Make Lower Case" id="d9M-CD-aMd">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="lowercaseWord:" target="-1" id="iUZ-b5-hil"/>
</connections>
</menuItem>
<menuItem title="Capitalize" id="UEZ-Bs-lqG">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="capitalizeWord:" target="-1" id="26H-TL-nsh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Speech" id="xrE-MZ-jX0">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Speech" id="3rS-ZA-NoH">
<items>
<menuItem title="Start Speaking" id="Ynk-f8-cLZ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="startSpeaking:" target="-1" id="654-Ng-kyl"/>
</connections>
</menuItem>
<menuItem title="Stop Speaking" id="Oyz-dy-DGm">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="stopSpeaking:" target="-1" id="dX8-6p-jy9"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="View" id="H8h-7b-M4v">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="View" id="HyV-fh-RgO">
<items>
<menuItem title="Enter Full Screen" keyEquivalent="f" id="4J7-dP-txa">
<modifierMask key="keyEquivalentModifierMask" control="YES" command="YES"/>
<connections>
<action selector="toggleFullScreen:" target="-1" id="dU3-MA-1Rq"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Window" id="aUF-d1-5bR">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Window" systemMenu="window" id="Td7-aD-5lo">
<items>
<menuItem title="Minimize" keyEquivalent="m" id="OY7-WF-poV">
<connections>
<action selector="performMiniaturize:" target="-1" id="VwT-WD-YPe"/>
</connections>
</menuItem>
<menuItem title="Zoom" id="R4o-n2-Eq4">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="performZoom:" target="-1" id="DIl-cC-cCs"/>
</connections>
</menuItem>
<menuItem isSeparatorItem="YES" id="eu3-7i-yIM"/>
<menuItem title="Bring All to Front" id="LE2-aR-0XJ">
<modifierMask key="keyEquivalentModifierMask"/>
<connections>
<action selector="arrangeInFront:" target="-1" id="DRN-fu-gQh"/>
</connections>
</menuItem>
</items>
</menu>
</menuItem>
<menuItem title="Help" id="EPT-qC-fAb">
<modifierMask key="keyEquivalentModifierMask"/>
<menu key="submenu" title="Help" systemMenu="help" id="rJ0-wn-3NY"/>
</menuItem>
</items>
<point key="canvasLocation" x="142" y="-258"/>
</menu>
<window title="APP_NAME" allowsToolTipsWhenApplicationIsInactive="NO" autorecalculatesKeyViewLoop="NO" releasedWhenClosed="NO" animationBehavior="default" id="QvC-M9-y7g" customClass="MainFlutterWindow" customModule="Runner" customModuleProvider="target">
<windowStyleMask key="styleMask" titled="YES" closable="YES" miniaturizable="YES" resizable="YES"/>
<rect key="contentRect" x="335" y="390" width="800" height="600"/>
<rect key="screenRect" x="0.0" y="0.0" width="2560" height="1577"/>
<view key="contentView" wantsLayer="YES" id="EiT-Mj-1SZ">
<rect key="frame" x="0.0" y="0.0" width="800" height="600"/>
<autoresizingMask key="autoresizingMask"/>
</view>
</window>
</objects>
</document>
@@ -0,0 +1,14 @@
// Application-level settings for the Runner target.
//
// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the
// future. If not, the values below would default to using the project name when this becomes a
// 'flutter create' template.
// The application's name. By default this is also the title of the Flutter window.
PRODUCT_NAME = timeline_ui_example
// The application's bundle identifier
PRODUCT_BUNDLE_IDENTIFIER = dev.cutdex.timelineUiExample
// The copyright displayed in application information
PRODUCT_COPYRIGHT = Copyright © 2026 dev.cutdex. All rights reserved.
@@ -0,0 +1,2 @@
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
@@ -0,0 +1,2 @@
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
@@ -0,0 +1,13 @@
WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings
GCC_WARN_UNDECLARED_SELECTOR = YES
CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES
CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES
CLANG_WARN_PRAGMA_PACK = YES
CLANG_WARN_STRICT_PROTOTYPES = YES
CLANG_WARN_COMMA = YES
GCC_WARN_STRICT_SELECTOR_MATCH = YES
CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES
CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES
GCC_WARN_SHADOW = YES
CLANG_WARN_UNREACHABLE_CODE = YES
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.network.server</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,32 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleDevelopmentRegion</key>
<string>$(DEVELOPMENT_LANGUAGE)</string>
<key>CFBundleExecutable</key>
<string>$(EXECUTABLE_NAME)</string>
<key>CFBundleIconFile</key>
<string></string>
<key>CFBundleIdentifier</key>
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
<key>CFBundleInfoDictionaryVersion</key>
<string>6.0</string>
<key>CFBundleName</key>
<string>$(PRODUCT_NAME)</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>
<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
<key>LSMinimumSystemVersion</key>
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
<key>NSHumanReadableCopyright</key>
<string>$(PRODUCT_COPYRIGHT)</string>
<key>NSMainNibFile</key>
<string>MainMenu</string>
<key>NSPrincipalClass</key>
<string>NSApplication</string>
</dict>
</plist>
@@ -0,0 +1,19 @@
import Cocoa
import FlutterMacOS
class MainFlutterWindow: NSWindow {
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
title = "Cutdex Timeline Example"
minSize = NSSize(width: 600, height: 480)
setContentSize(NSSize(width: 1200, height: 760))
center()
}
}
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.app-sandbox</key>
<true/>
</dict>
</plist>
@@ -0,0 +1,12 @@
import Cocoa
import FlutterMacOS
import XCTest
class RunnerTests: XCTestCase {
func testExample() {
// If you add code to the Runner application, consider adding tests here.
// See https://developer.apple.com/documentation/xctest for more information about using XCTest.
}
}
@@ -0,0 +1,24 @@
name: timeline_ui_example
description: Interactive Cutdex timeline painting and viewport example.
publish_to: none
version: 0.1.0
environment:
sdk: ^3.12.0
resolution: workspace
dependencies:
cutdex_core:
path: ../../../.dependencies/cutdex_core
cutdex_timeline_ui: ^0.1.0
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
flutter:
uses-material-design: true
@@ -0,0 +1,379 @@
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/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
import 'package:timeline_ui_example/main.dart';
import 'support/timeline_geometry.dart';
const second = TimelineClock.ticksPerSecond;
final viewport = TimelineViewportRect(width: 640, height: 360);
Widget surface(TimelineViewController c) => MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 640,
height: 360,
child: TimelineInteractionRegion(
controller: c,
edgeScrollExtent: 0,
child: TimelineView(controller: c),
),
),
),
);
Future<void> shortcut(
WidgetTester tester,
LogicalKeyboardKey modifier,
LogicalKeyboardKey key, {
bool shift = false,
}) async {
await tester.sendKeyDownEvent(modifier);
if (shift) await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
await tester.sendKeyEvent(key);
if (shift) await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
await tester.sendKeyUpEvent(modifier);
await tester.pump();
}
void main() {
test('playhead cuts an unselected clip on a three-hour timeline', () {
final c = createDemoController(longTimeline: true);
addTearDown(c.dispose);
final base = c.version;
c.seekTo(47 * second);
expect(c.selectedIdentities, isEmpty);
expect(c.canCutSelection, isTrue);
expect(c.cutSelectionAtPlayhead(), isTrue, reason: c.commandRejection);
final query = c.version.kernelVersion.query();
expect(
query.element(query.elementById(ElementId('long-0'))!).duration,
5 * second,
);
expect(query.storylineSpan(c.storyline), 10800 * second);
c.undo();
expect(c.version, same(base));
c.clearSelection();
c.seekTo(0);
expect(c.canCutSelection, isFalse);
});
test(
'playhead without selection cuts only Primary and preserves connected clips',
() {
final c = createDemoController();
addTearDown(c.dispose);
final before = c.version.kernelVersion.query();
final opening = before.elementById(ElementId('opening'))!;
final title = before.elementById(ElementId('title'))!;
c.seekTo(5 * second);
expect(c.selectedIdentities, isEmpty);
expect(c.cutSelectionAtPlayhead(), isTrue, reason: c.commandRejection);
final after = c.version.kernelVersion.query();
expect(after.element(opening).duration, 5 * second);
expect(after.element(title), before.element(title));
expect(c.selectedIdentities, isEmpty);
},
);
test(
'three-hour mixed selection cuts and deletes through one history entry each',
() {
final c = createDemoController(longTimeline: true);
addTearDown(c.dispose);
final base = c.version;
final q = base.kernelVersion.query();
final originals = <Object>{
q.elementById(ElementId('long-0'))!,
for (final id in ['long-title-0', 'long-overlay-0', 'long-audio-0'])
LayoutBodyId.element(q.elementById(ElementId(id))!),
};
c.setSelection(originals);
c.seekTo(47 * second);
expect(c.cutSelectionAtPlayhead(), isTrue, reason: c.commandRejection);
final cut = c.version;
expect(c.selectedIdentities.length, 8);
expect(
cut.kernelVersion.query().storylineSpan(c.storyline),
10800 * second,
);
final stale = c.selectedIdentities.toSet();
expect(c.deleteSelection(), isTrue, reason: c.commandRejection);
expect(
c.version.kernelVersion.query().storylineSpan(c.storyline),
10770 * second,
);
final deleted = c.version;
c.setSelection(stale);
expect(c.selectedIdentities, isEmpty);
c.seekTo(0);
expect(c.canCutSelection, isFalse);
expect(c.cutSelectionAtPlayhead(), isFalse);
expect(c.version, same(deleted));
// Retired identities become an empty selection, so Blade uses Primary.
c.seekTo(47 * second);
expect(c.canCutSelection, isTrue);
expect(c.cutSelectionAtPlayhead(), isTrue);
final fallback = c.version.kernelVersion.query();
final next = q.elementById(ElementId('long-1'))!;
expect(fallback.absoluteStart(next), 42 * second);
expect(fallback.element(next).duration, 5 * second);
expect(fallback.storylineSpan(c.storyline), 10770 * second);
expect(c.selectedIdentities, isEmpty);
c.undo();
expect(c.version, same(deleted));
c.undo();
expect(c.version, same(cut));
c.undo();
expect(c.version, same(base));
c.setSelection(stale.difference(originals));
expect(c.selectedIdentities, isEmpty);
expect(c.canDeleteSelection, isFalse);
expect(c.deleteSelection(), isFalse);
c.setSelection(stale);
expect(c.selectedIdentities, originals);
expect(c.version, same(base));
c.clearSelection();
expect(c.canDeleteSelection, isFalse);
expect(c.deleteSelection(), isFalse);
},
);
test(
'boundaries, outside playhead and unsupported mixed selections do not edit',
() {
final c = createDemoController();
addTearDown(c.dispose);
final base = c.version;
final title = base.kernelVersion.query().elementById(ElementId('title'))!;
c.setSelection([LayoutBodyId.element(title)]);
for (final tick in [0, 2, 7, 10]) {
c.seekTo(tick * second);
expect(c.canCutSelection, isFalse);
expect(c.cutSelectionAtPlayhead(), isFalse);
}
c.setSelection([title, TransitionId('dissolve')]);
expect(c.canDeleteSelection, isFalse);
expect(c.deleteSelection(), isFalse);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
},
);
test(
'multi-Primary and connected blade publishes together; both halves remain selected',
() {
final c = createDemoController();
addTearDown(c.dispose);
final base = c.version;
final q = base.kernelVersion.query();
c.setSelection([
q.elementById(ElementId('opening'))!,
LayoutBodyId.element(q.elementById(ElementId('title'))!),
]);
c.seekTo(5 * second);
expect(c.cutSelectionAtPlayhead(), isTrue, reason: c.commandRejection);
expect(c.selectedIdentities.length, 4);
expect(
c.version.kernelVersion.query().storylineSpan(c.storyline),
42 * second,
);
c.undo();
expect(c.version, same(base));
expect(c.canUndo, isFalse);
},
);
test(
'delete all Primary members leaves an empty timeline, not a replacement gap',
() {
final c = createDemoController();
addTearDown(c.dispose);
final base = c.version;
c.setSelection(base.kernelVersion.query().storylineElements(c.storyline));
expect(c.deleteSelection(), isTrue, reason: c.commandRejection);
expect(c.version.kernelVersion.query().storylineLength(c.storyline), 0);
expect(c.version.scene.bodies, isEmpty);
expect(c.project(viewport).length, 0);
c.undo();
expect(c.version, same(base));
},
);
testWidgets(
'move, trim, blade, delete and history restore every exact version',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final versions = [c.version];
final move = await tester.startGesture(clipPoint(tester, 'title'));
await move.moveBy(const Offset(24, 0));
await move.up();
versions.add(c.version);
final trim = await tester.startGesture(
clipPoint(tester, 'title', edge: TimelineTrimEdge.trailing),
);
await trim.moveBy(const Offset(-24, 0));
await trim.up();
versions.add(c.version);
c.seekTo(5 * second);
expect(c.cutSelectionAtPlayhead(), isTrue, reason: c.commandRejection);
versions.add(c.version);
expect(c.deleteSelection(), isTrue);
versions.add(c.version);
expect(versions.toSet().length, 5);
for (final previous in versions.reversed.skip(1)) {
c.undo();
expect(c.version, same(previous));
}
for (final next in versions.skip(1)) {
c.redo();
expect(c.version, same(next));
}
expect(tester.takeException(), isNull);
},
);
for (final modifier in [
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.controlLeft,
]) {
testWidgets('blade, delete, undo and redo shortcuts: $modifier', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
await tester.tapAt(clipPoint(tester, 'title'));
c.seekTo(4 * second);
final base = c.version;
await shortcut(tester, modifier, LogicalKeyboardKey.keyB);
final cut = c.version;
expect(cut, isNot(same(base)));
await tester.sendKeyEvent(
modifier == LogicalKeyboardKey.metaLeft
? LogicalKeyboardKey.backspace
: LogicalKeyboardKey.delete,
);
final deleted = c.version;
expect(deleted, isNot(same(cut)));
await shortcut(tester, modifier, LogicalKeyboardKey.keyZ);
expect(c.version, same(cut));
await shortcut(tester, modifier, LogicalKeyboardKey.keyZ, shift: true);
expect(c.version, same(deleted));
expect(tester.takeException(), isNull);
});
}
testWidgets('command shortcuts cannot mutate a running trim', (tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
c.seekTo(4 * second);
final base = c.version;
final trim = await tester.startGesture(
clipPoint(tester, 'title', edge: TimelineTrimEdge.trailing),
);
await trim.moveBy(const Offset(-24, 0));
await shortcut(
tester,
LogicalKeyboardKey.metaLeft,
LogicalKeyboardKey.keyB,
);
await tester.sendKeyEvent(LogicalKeyboardKey.delete);
expect(c.deleteSelection(), isFalse);
expect(c.version, same(base));
expect(c.isTrimming, isTrue);
await trim.cancel();
expect(c.canUndo, isFalse);
});
testWidgets(
'example buttons share commands and enablement with selection/playhead',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final view = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(view).controller;
final blade = find.byWidgetPredicate(
(w) => w is IconButton && w.tooltip == '切割 / Blade (Ctrl/Cmd+B)',
);
final delete = find.byWidgetPredicate(
(w) => w is IconButton && w.tooltip == '删除 / Delete',
);
expect(tester.widget<IconButton>(blade).onPressed, isNull);
await tester.tapAt(clipPoint(tester, 'title'));
c.seekTo(4 * second);
await tester.pump();
expect(tester.widget<IconButton>(blade).onPressed, isNotNull);
final base = c.version;
await tester.tap(blade);
await tester.pump();
final cut = c.version;
expect(cut, isNot(same(base)));
await tester.tap(delete);
await tester.pump();
expect(c.version, isNot(same(cut)));
await tester.tap(find.byTooltip('撤销 / Undo'));
await tester.pump();
expect(c.version, same(cut));
expect(tester.takeException(), isNull);
},
);
test('connected blade anchors its right half to the Primary at the cut', () {
final c = createDemoController();
addTearDown(c.dispose);
final base = c.version;
final q = base.kernelVersion.query();
final overlay = q.elementById(ElementId('overlay'))!;
final street = q.elementById(ElementId('street'))!;
c.setSelection([LayoutBodyId.element(overlay)]);
c.seekTo(9 * TimelineClock.ticksPerSecond);
expect(c.cutSelectionAtPlayhead(), isTrue);
final after = c.version;
final aq = after.kernelVersion.query();
final right = c.selectedIdentities
.whereType<LayoutBodyId>()
.singleWhere((id) => id.owner != overlay)
.owner;
expect(aq.absoluteStart(right), 9 * TimelineClock.ticksPerSecond);
expect(aq.connectionForTarget(right)!.anchor, street);
expect(
aq.connectionForTarget(overlay)!.anchor,
q.connectionForTarget(overlay)!.anchor,
);
expect(
aq.element(overlay).duration + aq.element(right).duration,
q.element(overlay).duration,
);
c.undo();
expect(c.version, same(base));
c.redo();
expect(c.version, same(after));
});
test(
'mixed ancestor/descendant selection deletes in one cascade publication',
() {
final c = createDemoController();
addTearDown(c.dispose);
final base = c.version;
final q = base.kernelVersion.query();
c.setSelection([
q.elementById(ElementId('opening'))!,
LayoutBodyId.element(q.elementById(ElementId('title'))!),
q.elementById(ElementId('gap'))!,
]);
expect(c.deleteSelection(), isTrue);
final aq = c.version.kernelVersion.query();
for (final id in ['opening', 'title', 'overlay', 'music', 'gap']) {
expect(aq.elementById(ElementId(id)), isNull);
}
expect(aq.elementById(ElementId('ambience')), isNotNull);
expect(aq.storylineSpan(c.storyline), 32 * TimelineClock.ticksPerSecond);
expect(c.selectedIdentities, isEmpty);
c.undo();
expect(c.version, same(base));
expect(c.canUndo, isFalse);
},
);
}
@@ -0,0 +1,357 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
import 'package:timeline_ui_example/main.dart';
const second = TimelineClock.ticksPerSecond;
final viewport = TimelineViewportRect(width: 1200, height: 500);
LayoutBodyId id(TimelineViewController c, String name) => LayoutBodyId.element(
c.version.kernelVersion.query().elementById(ElementId(name))!,
);
Offset grab(TimelineViewController c, LayoutBodyId source) {
final body = c.version.scene.bodies[source]!;
return Offset(
c.camera.screenXForTick(body.start + second, viewport),
c.camera.screenYForWorld(c.version.placementOf(source).top + 10, viewport),
);
}
Offset target(TimelineViewController c, int start, int top) => Offset(
c.camera.screenXForTick(start + second, viewport),
c.camera.screenYForWorld(top + 10, viewport),
);
void main() {
test(
'drop over a transition chooses a member boundary without source fragments',
() {
final c = createDemoController();
addTearDown(c.dispose);
final original = c.version;
final q = original.kernelVersion.query();
final source = id(c, 'title');
c.beginDrag(viewport: viewport, position: grab(c, source));
// Opening [0,8) and street [7,17) overlap. Street is the frontmost body;
// this point is in its front half, hence insertion before street.
final pointer = Offset(
c.camera.screenXForTick(75 * second ~/ 10, viewport),
178,
);
expect(c.finishDrag(viewport: viewport, position: pointer), isTrue);
final pq = c.version.kernelVersion.query();
expect(
pq.storylineElements(c.storyline).map((h) => pq.element(h).id.value),
['opening', 'title', 'street', 'gap', 'compound', 'voice', 'ending'],
);
expect(pq.absoluteStart(source.owner), 8 * second);
expect(pq.storylineSpan(c.storyline), 48 * second);
for (final h in q.storylineElements(c.storyline)) {
expect(pq.element(h).duration, q.element(h).duration);
expect(pq.element(h).sourceStart, q.element(h).sourceStart);
expect(pq.element(h).sourceDuration, q.element(h).sourceDuration);
}
c.undo();
expect(c.version, same(original));
},
);
test(
'latest camera controls preview and exact single drop; undo/redo reuse roots',
() {
final c = createDemoController();
addTearDown(c.dispose);
final source = id(c, 'title');
final base = c.version;
c.panBy(horizontalPixels: 30, verticalPixels: 15);
c.zoomAt(screenX: 100, newPixelsPerTick: 32 / second, viewport: viewport);
expect(
c.beginDrag(viewport: viewport, position: grab(c, source)),
isTrue,
);
final destination = target(c, 5 * second, 90);
c.updateDrag(viewport: viewport, position: destination);
final prepared = c.project(viewport).version;
expect(c.version, same(base));
expect(c.canUndo, isFalse);
expect(
prepared.kernelVersion.query().absoluteStart(source.owner),
5 * second,
);
expect(c.finishDrag(viewport: viewport, position: destination), isTrue);
expect(c.version, same(prepared));
expect(c.isDragging, isFalse);
c.undo();
expect(c.version, same(base));
expect(c.canUndo, isFalse, reason: 'only one edit was committed');
c.redo();
expect(c.version, same(prepared));
expect(
base.kernelVersion.query().absoluteStart(source.owner),
2 * second,
);
},
);
test('camera pan during drag re-resolves the stationary screen pointer', () {
final c = createDemoController();
addTearDown(c.dispose);
final source = id(c, 'title');
final start = grab(c, source);
c.beginDrag(viewport: viewport, position: start);
final pointer = start + const Offset(24, 0);
c.updateDrag(viewport: viewport, position: pointer);
c.panBy(horizontalPixels: 48);
expect(
c
.project(viewport)
.version
.kernelVersion
.query()
.absoluteStart(source.owner),
5 * second,
);
c.finishDrag(viewport: viewport, position: pointer);
expect(
c.version.kernelVersion.query().absoluteStart(source.owner),
5 * second,
);
});
test(
'lower dragged top displaces incumbent; lifting above latest top releases it',
() {
final c = createDemoController();
addTearDown(c.dispose);
final a = id(c, 'title');
final b = id(c, 'overlay');
final base = c.version;
c.beginDrag(viewport: viewport, position: grab(c, b));
c.updateDrag(viewport: viewport, position: target(c, 4 * second, 105));
final displaced = c.project(viewport).version;
expect(displaced.placementOf(b).lane, 1);
expect(displaced.placementOf(a).lane, 2);
c.updateDrag(
viewport: viewport,
position: target(c, 4 * second, displaced.placementOf(a).top - 5),
);
expect(c.project(viewport).version.placementOf(a).lane, 1);
c.cancelDrag();
expect(c.version, same(base));
expect(c.project(viewport).version, same(base));
expect(c.canUndo, isFalse);
},
);
test('capture into Primary chooses the back boundary without cutting', () {
final c = createDemoController();
addTearDown(c.dispose);
final source = id(c, 'title');
final base = c.version;
c.beginDrag(viewport: viewport, position: grab(c, source));
final destination = target(c, 12 * second, 168);
c.updateDrag(viewport: viewport, position: destination);
expect(c.dragRejection, isNull);
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
final prepared = c.project(viewport).version;
expect(prepared.scene.bodies[source], isNull);
expect(c.version, same(base));
expect(c.finishDrag(viewport: viewport, position: destination), isTrue);
final query = c.version.kernelVersion.query();
expect(query.connectionForTarget(source.owner), isNull);
expect(query.absoluteStart(source.owner), 17 * second);
expect(
query.storylineLength(c.storyline),
base.kernelVersion.query().storylineLength(c.storyline) + 1,
);
expect(query.storylineSpan(c.storyline), 47 * second);
expect(c.selectedIdentities, {source.owner});
c.undo();
expect(c.version, same(base));
c.redo();
expect(c.version, same(prepared));
});
test(
'diagonal side crossing commits time, side and audio avoidance together',
() {
final c = createDemoController();
addTearDown(c.dispose);
final source = id(c, 'title');
final audio = id(c, 'music');
c.beginDrag(viewport: viewport, position: grab(c, source));
final destination = target(c, 5 * second, 222);
c.updateDrag(viewport: viewport, position: destination);
expect(c.dragRejection, isNull);
final prepared = c.project(viewport).version;
expect(prepared.placementOf(source).lane, 1);
expect(prepared.placementOf(audio).lane, greaterThan(1));
c.finishDrag(viewport: viewport, position: destination);
expect(c.version, same(prepared));
expect(
c.version.kernelVersion.query().absoluteStart(source.owner),
5 * second,
);
expect(
c.version.kernelVersion
.query()
.connectionOrderLocation(source.owner)!
.side,
ConnectionSide.below,
);
},
);
test('audio above Primary lands below; left overshoot commits at zero', () {
for (final outside in [false, true]) {
final c = createDemoController();
final source = id(c, 'music');
final base = c.version;
c.beginDrag(viewport: viewport, position: grab(c, source));
final destination = outside
? const Offset(-10, 80)
: target(c, second, 70);
c.updateDrag(viewport: viewport, position: destination);
expect(c.dragRejection, isNull);
expect(c.dragGhost, isNotNull);
final prepared = c.project(viewport).version;
final query = prepared.kernelVersion.query();
expect(
query.connectionOrderLocation(source.owner)!.side,
ConnectionSide.below,
);
expect(query.absoluteStart(source.owner), outside ? 0 : second);
expect(
query.element(source.owner).duration,
base.kernelVersion.query().element(source.owner).duration,
);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
expect(c.finishDrag(viewport: viewport, position: destination), isTrue);
expect(c.version, same(prepared));
c.undo();
expect(c.version, same(base));
c.dispose();
}
});
test('no motion, cancellation and a second release never create history', () {
final c = createDemoController();
addTearDown(c.dispose);
final source = id(c, 'title');
final base = c.version;
final down = grab(c, source);
c.beginDrag(viewport: viewport, position: down);
expect(c.finishDrag(viewport: viewport, position: down), isFalse);
c.beginDrag(viewport: viewport, position: down);
c.updateDrag(viewport: viewport, position: down + const Offset(24, 0));
c.cancelDrag();
expect(c.finishDrag(viewport: viewport, position: down), isFalse);
expect(c.canUndo, isFalse);
expect(c.version, same(base));
});
test('new drop after undo clears redo and old roots stay immutable', () {
final c = createDemoController();
addTearDown(c.dispose);
final source = id(c, 'title');
void drop(int seconds) {
c.beginDrag(viewport: viewport, position: grab(c, source));
expect(
c.finishDrag(
viewport: viewport,
position: target(c, seconds * second, 90),
),
isTrue,
);
}
drop(5);
final old = c.version;
c.undo();
drop(6);
expect(c.canRedo, isFalse);
expect(old.kernelVersion.query().absoluteStart(source.owner), 5 * second);
expect(
c.version.kernelVersion.query().absoluteStart(source.owner),
6 * second,
);
});
testWidgets(
'native pointer adapter previews, drops and supports history buttons',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final finder = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(finder).controller;
final base = c.version;
final source = id(c, 'title');
final origin = tester.getTopLeft(finder);
final gesture = await tester.startGesture(
origin + const Offset(100, 112),
kind: PointerDeviceKind.mouse,
);
await gesture.moveBy(const Offset(48, 0));
await tester.pump();
expect(c.isDragging, isTrue);
expect(c.version, same(base));
expect(c.dragGhost, isNotNull);
final prepared = c
.project(
TimelineViewportRect(
width: 800,
height: tester.getSize(finder).height,
),
)
.version;
await gesture.up();
await tester.pump();
expect(c.version, same(prepared));
expect(
c.version.kernelVersion.query().absoluteStart(source.owner),
4 * second,
);
await tester.tap(find.byTooltip('撤销 / Undo'));
await tester.pump();
expect(c.version, same(base));
await tester.tap(find.byTooltip('重做 / Redo'));
await tester.pump();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
testWidgets('Escape and pointer cancellation discard prepared roots', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final finder = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(finder).controller;
final base = c.version;
final origin = tester.getTopLeft(finder);
for (final escape in [true, false]) {
final gesture = await tester.startGesture(
origin + const Offset(100, 112),
);
await gesture.moveBy(const Offset(48, 0));
await tester.pump();
expect(c.dragGhost, isNotNull);
if (escape) {
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await gesture.up();
} else {
await gesture.cancel();
}
await tester.pump();
expect(c.isDragging, isFalse);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
}
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,403 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
import 'package:timeline_ui_example/main.dart';
import 'support/timeline_geometry.dart';
final viewport = TimelineViewportRect(width: 640, height: 360);
const down = Offset(100, 110);
Widget surface(
TimelineViewController c, {
double width = 640,
double extent = 48,
}) => MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: width,
height: 360,
child: TimelineInteractionRegion(
controller: c,
edgeScrollExtent: extent,
child: TimelineView(controller: c),
),
),
),
);
Future<void> frames(WidgetTester tester, [int count = 12]) async {
for (var i = 0; i < count; i++) {
await tester.pump(const Duration(milliseconds: 16));
}
}
void main() {
for (final milliseconds in [8, 16, 32]) {
testWidgets(
'scroll distance is elapsed-time based at ${milliseconds}ms frames',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final gesture = await tester.startGesture(down);
await gesture.moveTo(const Offset(632, 110));
await tester.pump();
final before = c.camera.screenXForTick(0, viewport);
for (var elapsed = 0; elapsed < 192; elapsed += milliseconds) {
await tester.pump(Duration(milliseconds: milliseconds));
}
// 600 px/s * (40 / 48)^2 * 0.192 s = 80 px.
expect(
before - c.camera.screenXForTick(0, viewport),
closeTo(80, 0.001),
);
await gesture.cancel();
expect(c.canUndo, isFalse);
},
);
}
testWidgets('a stalled frame cannot catch up with a giant camera jump', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final gesture = await tester.startGesture(down);
await gesture.moveTo(const Offset(632, 110));
await tester.pump();
final before = c.camera.screenXForTick(0, viewport);
await tester.pump(const Duration(seconds: 5));
expect(
before - c.camera.screenXForTick(0, viewport),
closeTo(600 * (40 / 48) * (40 / 48) * 0.05, 0.001),
);
await gesture.cancel();
});
for (final point in [const Offset(8, 110), const Offset(400, 8)]) {
testWidgets('left/top edge scroll stops on returning to center: $point', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
c.panBy(horizontalPixels: 48, verticalPixels: 40);
await tester.pump();
final gesture = await tester.startGesture(
clipPoint(tester, 'title'),
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(point);
await tester.pump();
final before = c.camera;
await frames(tester, 3);
if (point.dx == 8) {
expect(c.camera.baseTick, lessThan(before.baseTick));
} else {
expect(c.camera.verticalOffset, lessThan(before.verticalOffset));
}
await gesture.moveTo(const Offset(300, 110));
final stopped = c.camera;
await frames(tester);
expect(c.camera, same(stopped));
await gesture.cancel();
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
});
}
testWidgets(
'horizontal overshoot keeps scrolling and commits only on release',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final original = c.version;
final gesture = await tester.startGesture(clipPoint(tester, 'title'));
await gesture.moveTo(const Offset(650, 110));
await tester.pump();
final before = c.camera;
await frames(tester, 3);
expect(c.camera.baseTick, greaterThan(before.baseTick));
expect(c.dragRejection, isNull);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
final prepared = c.project(viewport).version;
expect(prepared, isNot(same(original)));
await gesture.up();
await tester.pump();
expect(c.version, same(prepared));
final stopped = c.camera;
await frames(tester);
expect(c.camera, same(stopped));
c.undo();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
c.redo();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
testWidgets(
'vertical overshoot stops scrolling; cancellation discards preview',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final original = c.version;
final gesture = await tester.startGesture(clipPoint(tester, 'title'));
await gesture.moveTo(const Offset(632, 110));
await tester.pump();
await frames(tester, 3);
expect(c.project(viewport).version, isNot(same(original)));
await gesture.moveTo(const Offset(650, 370));
final stopped = c.camera;
await frames(tester);
expect(c.camera, same(stopped));
expect(c.version, same(original));
await gesture.cancel();
await tester.pump();
expect(c.isDragging, isFalse);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
},
);
for (final end in [
'cancel',
'external',
'resize',
'replace',
'unmount',
'inactive',
'second touch',
]) {
testWidgets('edge ticker stops on $end without publishing a stale drag', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final original = c.version;
final gesture = await tester.startGesture(down);
await gesture.moveTo(const Offset(632, 110));
await tester.pump();
await frames(tester, 3);
switch (end) {
case 'cancel':
await gesture.cancel();
case 'external':
c.undo();
case 'resize':
await tester.pumpWidget(surface(c, width: 620));
case 'replace':
final other = createDemoController();
addTearDown(other.dispose);
await tester.pumpWidget(surface(other));
case 'unmount':
await tester.pumpWidget(const SizedBox());
case 'inactive':
tester.binding.handleAppLifecycleStateChanged(
AppLifecycleState.inactive,
);
tester.binding.handleAppLifecycleStateChanged(
AppLifecycleState.resumed,
);
case 'second touch':
final second = await tester.startGesture(
const Offset(400, 240),
pointer: 2,
);
await second.up();
}
final stopped = c.camera;
await frames(tester);
expect(c.camera, same(stopped));
if (end != 'cancel') await gesture.up();
await tester.pump();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
});
}
testWidgets(
'zero edge extent disables auto scroll and idle has no ticker work',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c, extent: 0));
final original = c.camera;
await frames(tester);
expect(c.camera, same(original));
final gesture = await tester.startGesture(down);
await gesture.moveTo(const Offset(632, 110));
await tester.pump();
await frames(tester);
expect(c.camera, same(original));
await gesture.cancel();
expect(tester.binding.transientCallbackCount, 0);
},
);
testWidgets(
'long-scene switch retains independent history and exposes the end',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final view = find.byKey(const Key('timeline-surface'));
final short = tester.widget<TimelineView>(view).controller;
Future<void> select(String label) async {
await tester.tap(find.byTooltip('切换场景 / Switch scene'));
await tester.pumpAndSettle();
await tester.tap(find.text(label));
await tester.pumpAndSettle();
}
await select('3 小时 / 3 hours');
final c = tester.widget<TimelineView>(view).controller;
final q = c.version.kernelVersion.query();
expect(
q.storylineSpan(c.storyline),
10800 * TimelineClock.ticksPerSecond,
);
expect(q.storylineLength(c.storyline), 365);
final original = c.version;
final origin = tester.getTopLeft(view);
final gesture = await tester.startGesture(
origin + down,
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(origin + const Offset(140, 110));
await gesture.up();
await tester.pump();
expect(c.canUndo, isTrue);
final edited = c.version;
await select('短场景 / Short scene');
expect(tester.widget<TimelineView>(view).controller, same(short));
expect(short.canUndo, isFalse);
await select('3 小时 / 3 hours');
expect(tester.widget<TimelineView>(view).controller, same(c));
expect(c.version, same(edited));
c.undo();
expect(c.version, same(original));
await tester.tap(find.text('末尾 / End'));
await tester.pump();
expect(
c.camera.baseTick,
greaterThan(10700 * TimelineClock.ticksPerSecond),
);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'Primary edge scroll drops at latest boundary without splitting',
(tester) async {
final c = createDemoController(longTimeline: true);
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final original = c.version;
final q = original.kernelVersion.query();
final p = q.elementById(ElementId('opening'))!;
final gesture = await tester.startGesture(const Offset(100, 178));
await gesture.moveTo(const Offset(632, 178));
await tester.pump();
await frames(tester);
expect(c.dragRejection, isNull);
final prepared = c.project(viewport).version;
final pq = prepared.kernelVersion.query();
expect(pq.storylineLength(c.storyline), q.storylineLength(c.storyline));
expect(pq.element(p).sourceDuration, q.element(p).sourceDuration);
expect(pq.element(p).duration, q.element(p).duration);
await gesture.up();
expect(c.version, same(prepared));
c.undo();
expect(c.version, same(original));
expect(tester.takeException(), isNull);
},
);
testWidgets(
'held edge scroll keeps grab offset, commits latest preview and stops',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final original = c.version;
final source = LayoutBodyId.element(
original.kernelVersion.query().elementById(ElementId('title'))!,
);
final grabX =
down.dx -
c.camera.screenXForTick(
original.scene.bodies[source]!.start,
viewport,
);
final gesture = await tester.startGesture(
down,
kind: PointerDeviceKind.mouse,
);
const edge = Offset(632, 110);
await gesture.moveTo(edge);
await tester.pump();
final before = c.camera;
await frames(tester);
expect(c.camera.baseTick, greaterThan(before.baseTick));
expect(c.dragRejection, isNull);
expect(
c.camera.screenXForTick(c.dragGhost!.body.start, viewport) + grabX,
closeTo(edge.dx, 0.001),
);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
final prepared = c.project(viewport).version;
await gesture.up();
await tester.pump();
expect(c.version, same(prepared));
final stopped = c.camera;
await frames(tester);
expect(c.camera, same(stopped));
c.undo();
expect(c.version, same(original));
c.redo();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
testWidgets(
'corner scroll pans both axes and Escape stops without publishing',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final original = c.version;
final gesture = await tester.startGesture(
down,
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(const Offset(632, 352));
await tester.pump();
final before = c.camera;
await frames(tester);
expect(c.camera.baseTick, greaterThan(before.baseTick));
expect(c.camera.verticalOffset, greaterThan(before.verticalOffset));
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
final stopped = c.camera;
await frames(tester);
expect(c.camera, same(stopped));
await gesture.up();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
},
);
}
@@ -0,0 +1,131 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
import 'support/timeline_geometry.dart';
const second = TimelineClock.ticksPerSecond;
final surface = find.byKey(const Key('timeline-surface'));
void main() {
for (final grabSecond in [false, true]) {
testWidgets(
'marquee-selected overlap becomes consecutive Primary clips; grab B=$grabSecond',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final a = q.elementById(ElementId('title'))!,
b = q.elementById(ElementId('overlay'))!;
final rectangle = connectedMarquee(c, viewport);
final select = await tester.startGesture(
origin + rectangle.topLeft,
kind: PointerDeviceKind.mouse,
);
await select.moveTo(origin + rectangle.bottomRight);
await select.up();
await tester.pump();
expect(c.selectedIdentities, {
LayoutBodyId.element(a),
LayoutBodyId.element(b),
});
final down =
clipPoint(tester, grabSecond ? 'overlay' : 'title') - origin;
final primaryY = clipBody(c, viewport, 'street').center.dy;
final drop = Offset(
c.camera.screenXForTick(18 * second, viewport),
primaryY,
);
final grabbed = grabSecond ? b : a;
final grabOffset =
down.dx -
c.camera.screenXForTick(q.absoluteStart(grabbed), viewport);
final expectedGrabStart = c.camera.tickAtScreenX(
drop.dx - grabOffset,
viewport,
rounding: TimelineTickRounding.nearest,
);
final drag = await tester.startGesture(
origin + down,
kind: PointerDeviceKind.mouse,
);
if (grabSecond) {
await drag.moveTo(
origin +
Offset(
c.camera.screenXForTick(14 * second, viewport),
primaryY,
),
);
await tester.pump();
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
expect(c.dragRejection, isNull);
expect(c.version, same(original));
expect(tester.takeException(), isNull);
await drag.moveTo(origin + Offset(20, primaryY));
await tester.pump();
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
expect(
c.project(viewport).version.kernelVersion.query().absoluteStart(a),
0,
);
}
await drag.moveTo(origin + drop);
await tester.pump();
expect(c.dragRejection, isNull);
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
expect(c.dragGhosts.length, 2);
final prepared = c.project(viewport).version;
final pq = prepared.kernelVersion.query();
expect(pq.absoluteStart(b), pq.absoluteStart(a) + 5 * second);
expect(pq.absoluteStart(a), 17 * second);
expect(
c.dragGhostFor(LayoutBodyId.element(grabbed))!.body.start,
expectedGrabStart,
);
expect(
pq.storylineLength(c.storyline),
q.storylineLength(c.storyline) + 2,
);
for (final h in q.storylineElements(c.storyline)) {
expect(pq.element(h).duration, q.element(h).duration);
expect(pq.element(h).sourceStart, q.element(h).sourceStart);
expect(pq.element(h).sourceDuration, q.element(h).sourceDuration);
}
expect(pq.connectionForTarget(a), isNull);
expect(pq.connectionForTarget(b), isNull);
expect(
pq.storylineSpan(c.storyline),
q.storylineSpan(c.storyline) + 12 * second,
);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
await drag.up();
await tester.pump();
expect(c.version, same(prepared));
expect(c.selectedIdentities, {a, b});
final order = pq.storylineElements(c.storyline).toList();
expect(order[order.indexOf(a) + 1], b);
expect(pq.element(a).sourceStart, q.element(a).sourceStart);
expect(pq.element(a).sourceDuration, q.element(a).sourceDuration);
c.undo();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
c.redo();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
}
}
@@ -0,0 +1,318 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
void main() {
for (final grabChild in [false, true]) {
for (final finishOnPrimary in [false, true]) {
testWidgets(
'mixed group switches geometry; child=$grabChild primary=$finishOnPrimary',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final surface = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final a = q.elementById(ElementId('opening'))!;
final b = q.elementById(ElementId('street'))!;
final child = LayoutBodyId.element(
q.elementById(ElementId('title'))!,
);
final bId = LayoutBodyId.element(b);
final selected = {b, child};
c.setSelection(selected);
await tester.pump();
final down = grabChild
? const Offset(100, 110)
: const Offset(300, 178);
final drag = await tester.startGesture(
origin + down,
kind: PointerDeviceKind.mouse,
);
for (var i = 0; i < 3; i++) {
await drag.moveTo(origin + const Offset(720, 178));
await tester.pump();
expect(c.dragRejection, isNull);
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
final pq = c.project(viewport).version.kernelVersion.query();
expect(
pq.storylineElements(c.storyline).map((h) => pq.element(h).name),
[
'opening',
'gap',
'compound',
'title',
'street',
'voice',
'ending',
],
);
expect(pq.connectionForTarget(child.owner), isNull);
expect(
pq.absoluteStart(b),
pq.absoluteStart(child.owner) + pq.element(child.owner).duration,
);
expect(c.dragGhostFor(child)!.top, c.dragGhostFor(bId)!.top);
expect(
c.dragGhostFor(child)!.body.height,
c.geometry.primaryHeight,
);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
// Return B to its original time, with the pointer outside Primary.
final back = Offset(down.dx, grabChild ? down.dy : 110);
await drag.moveTo(origin + back);
await tester.pump();
expect(c.dragRejection, isNull);
expect(c.project(viewport).version, same(original));
final childGhost = c.dragGhostFor(child)!;
final bGhost = c.dragGhostFor(bId)!;
expect(bGhost.body.start, q.absoluteStart(b));
expect(childGhost.body.start, q.absoluteStart(child.owner));
expect(
childGhost.top - bGhost.top,
original.placementOf(child).top - c.geometry.primaryTop,
);
expect(
childGhost.body.height,
original.scene.bodies[child]!.height,
);
expect(q.connectionForTarget(child.owner)!.anchor, a);
if (grabChild) {
expect(bGhost.top, c.geometry.primaryTop);
expect(childGhost.top, original.placementOf(child).top);
}
expect(c.selectedIdentities, selected);
}
if (finishOnPrimary) {
await drag.moveTo(origin + const Offset(720, 178));
await tester.pump();
}
final prepared = c.project(viewport).version;
await drag.up();
await tester.pump();
expect(c.version, same(prepared));
expect(
c.selectedIdentities,
finishOnPrimary ? {b, child.owner} : selected,
);
if (finishOnPrimary) {
c.undo();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
c.redo();
expect(c.version, same(prepared));
} else {
expect(c.version, same(original));
expect(c.canUndo, isFalse);
}
expect(tester.takeException(), isNull);
},
);
}
}
testWidgets(
'off-axis release preserves connected identity and relative time',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final surface = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final b = q.elementById(ElementId('street'))!;
final child = LayoutBodyId.element(q.elementById(ElementId('title'))!);
c.setSelection({b, child});
await tester.pump();
final drag = await tester.startGesture(
origin + const Offset(300, 178),
kind: PointerDeviceKind.mouse,
);
await drag.moveTo(origin + const Offset(720, 178));
await tester.pump();
expect(
c
.project(viewport)
.version
.kernelVersion
.query()
.connectionForTarget(child.owner),
isNull,
);
await drag.moveTo(origin + const Offset(600, 110));
await tester.pump();
expect(c.dragRejection, isNull);
final prepared = c.project(viewport).version;
final pq = prepared.kernelVersion.query();
expect(prepared, isNot(same(original)));
expect(
pq.connectionForTarget(child.owner)!.id,
q.connectionForTarget(child.owner)!.id,
);
expect(
pq.absoluteStart(child.owner) - pq.absoluteStart(b),
q.absoluteStart(child.owner) - q.absoluteStart(b),
);
expect(
c.dragGhostFor(child)!.top -
c.dragGhostFor(LayoutBodyId.element(b))!.top,
original.placementOf(child).top - c.geometry.primaryTop,
);
await drag.up();
await tester.pump();
expect(c.version, same(prepared));
expect(c.selectedIdentities, {b, child});
c.undo();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
c.redo();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
for (final dropX in [20.0, 300.0]) {
testWidgets('mixed insertion includes child at boundary $dropX', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final surface = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final b = q.elementById(ElementId('street'))!;
final child = LayoutBodyId.element(q.elementById(ElementId('title'))!);
c.setSelection({b, child});
await tester.pump();
final drag = await tester.startGesture(
origin + const Offset(100, 110),
kind: PointerDeviceKind.mouse,
);
await drag.moveTo(origin + Offset(dropX, 178));
await tester.pump();
expect(c.dragRejection, isNull);
final pq = c.project(viewport).version.kernelVersion.query();
expect(
pq.storylineElements(c.storyline).map((h) => pq.element(h).name),
dropX == 20
? [
'title',
'street',
'opening',
'gap',
'compound',
'voice',
'ending',
]
: [
'opening',
'title',
'street',
'gap',
'compound',
'voice',
'ending',
],
);
await drag.cancel();
await tester.pump();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
});
}
for (final source in ['opening', 'title', 'overlay']) {
testWidgets(
'Primary and children drag from $source without duplicate moves',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final surface = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final opening = q.elementById(ElementId('opening'))!;
final street = q.elementById(ElementId('street'))!;
final title = LayoutBodyId.element(q.elementById(ElementId('title'))!);
final overlay = LayoutBodyId.element(
q.elementById(ElementId('overlay'))!,
);
final selected = {opening, street, title, overlay};
c.setSelection(selected);
await tester.pump();
final down = switch (source) {
'opening' => const Offset(100, 178),
'title' => const Offset(100, 110),
_ => const Offset(140, 60),
};
final drag = await tester.startGesture(
origin + down,
kind: PointerDeviceKind.mouse,
);
await drag.moveTo(origin + const Offset(720, 178));
await tester.pump();
expect(c.isDragging, isTrue);
expect(c.dragRejection, isNull);
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
expect(c.selectedIdentities, selected);
expect(c.dragGhosts.length, 6);
final prepared = c.project(viewport).version;
final pq = prepared.kernelVersion.query();
expect(
pq.storylineElements(c.storyline).map((h) => pq.element(h).name),
['gap', 'compound', 'opening', 'street', 'voice', 'ending'],
);
for (final child in [title, overlay]) {
expect(
pq.connectionForTarget(child.owner),
q.connectionForTarget(child.owner),
);
expect(
pq.absoluteStart(child.owner) - pq.absoluteStart(opening),
q.absoluteStart(child.owner) - q.absoluteStart(opening),
);
}
expect(pq.storylineSpan(c.storyline), q.storylineSpan(c.storyline));
expect(c.version, same(original));
await drag.up();
await tester.pump();
expect(c.version, same(prepared));
expect(c.selectedIdentities, selected);
c.undo();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
c.redo();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
}
}
@@ -0,0 +1,381 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
import 'package:timeline_ui_example/main.dart';
import 'support/timeline_geometry.dart';
const second = TimelineClock.ticksPerSecond;
final surface = find.byKey(const Key('timeline-surface'));
TimelineViewController controller(WidgetTester tester) =>
tester.widget<TimelineView>(surface).controller;
TimelineViewportRect viewport(WidgetTester tester) => TimelineViewportRect(
width: tester.getSize(surface).width,
height: tester.getSize(surface).height,
);
Future<void> wheel(WidgetTester tester, Offset delta, {Offset? at}) async {
await tester.sendEventToBinding(
PointerScrollEvent(
position: at ?? tester.getTopLeft(surface) + const Offset(300, 100),
scrollDelta: delta,
),
);
await tester.pump();
}
void main() {
test('demo camera starts at zero', () {
expect(initialDemoCamera().baseTick, 0);
final c = createDemoController();
addTearDown(c.dispose);
expect(c.camera.baseTick, 0);
});
testWidgets('left navigation stops at zero without editing the document', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final original = c.version;
await wheel(tester, const Offset(48, 0));
expect(c.camera.baseTick, 2 * second);
await wheel(tester, const Offset(-240, 0));
expect(c.camera.baseTick, 0);
expect(c.camera.screenXForTick(0, viewport(tester)), 0);
await wheel(tester, const Offset(-48, 0));
expect(c.camera.baseTick, 0);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
});
test('overview bands include margin for short and long sequences', () {
expect(TimelineViewController.overviewSecondsFor(0), 600);
expect(TimelineViewController.overviewSecondsFor(8 * 60 * second), 600);
expect(TimelineViewController.overviewSecondsFor(90 * 60 * second), 7200);
expect(TimelineViewController.overviewSecondsFor(3 * 3600 * second), 14400);
expect(
TimelineViewController.overviewSecondsFor(10 * 3600 * second),
57600,
);
});
for (final long in [false, true]) {
test('zoom endpoints and fit respect sequence duration: long=$long', () {
final c = createDemoController(longTimeline: long);
addTearDown(c.dispose);
final v = TimelineViewportRect(width: 800, height: 300);
c.configureViewport(
width: v.width,
height: v.height,
end: c.contentEndTick,
top: 0,
bottom: 300,
);
c.reconcileViewport();
c.zoomBy(scale: 1e-12, viewport: v);
expect(
c.camera.pixelsPerTick,
closeTo(800 / (c.maximumVisibleSeconds * second), 1e-12),
);
expect(c.maximumVisibleSeconds, long ? 14400 : 600);
c.zoomAt(screenX: 100, newPixelsPerTick: 1e-20, viewport: v);
expect(c.camera.pixelsPerTick, c.minimumPixelsPerTick(v.width));
c.zoomBy(scale: 1e12, viewport: v);
expect(c.camera.pixelsPerTick * c.frameTicks, closeTo(32, 1e-6));
c.fitTimeline();
expect(c.camera.baseTick, 0);
expect(c.camera.screenXForTick(c.contentEndTick, v), closeTo(640, 1e-6));
final before = c.camera;
c.configureViewport(
width: 800,
height: 300,
end: c.contentEndTick + 100 * second,
top: 0,
bottom: 300,
);
c.reconcileViewport();
expect(c.camera.pixelsPerTick, before.pixelsPerTick);
expect(c.canUndo, isFalse);
});
}
testWidgets('space-click navigation leaves selection unchanged', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.setSelection([]);
final before = c.selectedIdentities.toSet();
await tester.sendKeyDownEvent(LogicalKeyboardKey.space);
await tester.tapAt(tester.getTopLeft(surface) + const Offset(100, 112));
await tester.sendKeyUpEvent(LogicalKeyboardKey.space);
await tester.pump();
expect(c.selectedIdentities, before);
expect(c.canUndo, isFalse);
});
testWidgets(
'ruler seek shares the panned and zoomed camera without history',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final base = c.version;
c.panBy(horizontalPixels: 120, verticalPixels: 40);
c.navigate(
from: const Offset(300, 0),
to: const Offset(300, 0),
scale: 2,
viewport: viewport(tester),
);
await tester.pump();
final origin = tester.getTopLeft(find.byType(TimelineRuler));
final camera = c.camera;
final raw = c.camera.tickAtScreenX(
250,
viewport(tester),
rounding: TimelineTickRounding.nearest,
);
final frame = TimelineFormat.fps24.frameGrid.quantumTicks;
final expected = (raw / frame).round() * frame;
final selected = c.version.kernelVersion.query().elementById(
ElementId('opening'),
)!;
c.setSelection([selected]);
await tester.tapAt(origin + const Offset(250, 16));
await tester.pump();
expect(c.playheadTick, expected);
expect(c.selectedIdentities, {selected});
final drag = await tester.startGesture(origin + const Offset(250, 16));
await drag.moveBy(const Offset(96, 0));
await drag.up();
await tester.pump();
final draggedTick = c.camera.tickAtScreenX(
346,
viewport(tester),
rounding: TimelineTickRounding.nearest,
);
expect(c.playheadTick, (draggedTick / frame).round() * frame);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
expect(c.camera, same(camera));
expect(tester.takeException(), isNull);
},
);
testWidgets('wheel pans two axes; shift-wheel pans horizontally only', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final base = c.version;
final initialVertical = c.camera.verticalOffset;
await wheel(tester, const Offset(48, 30));
expect(c.camera.baseTick, 2 * second);
expect(c.camera.verticalOffset, initialVertical + 30);
await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft);
await wheel(tester, const Offset(0, 24));
await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft);
expect(c.camera.baseTick, 3 * second);
expect(c.camera.verticalOffset, initialVertical + 30);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
});
for (final key in [
LogicalKeyboardKey.controlLeft,
LogicalKeyboardKey.metaLeft,
]) {
testWidgets('modified wheel zoom retains the visible playhead: $key', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.seekTo(5 * second);
final before = c.camera;
final v = viewport(tester);
final anchorX = before.screenXForTick(c.playheadTick, v);
final tick = before.tickAtScreenX(
anchorX,
v,
rounding: TimelineTickRounding.nearest,
);
await tester.sendKeyDownEvent(key);
await wheel(tester, const Offset(0, -100));
await tester.sendKeyUpEvent(key);
expect(c.camera.pixelsPerTick, greaterThan(before.pixelsPerTick));
expect(c.camera.screenXForTick(tick, v), closeTo(anchorX, 1e-6));
expect(c.canUndo, isFalse);
});
}
for (final middle in [true, false]) {
testWidgets('pan over a connected clip does not move it: middle=$middle', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final base = c.version;
c.panBy(horizontalPixels: 96);
await tester.pump();
final initialVertical = c.camera.verticalOffset;
if (!middle) await tester.sendKeyDownEvent(LogicalKeyboardKey.space);
final gesture = await tester.startGesture(
clipPoint(tester, 'title'),
kind: PointerDeviceKind.mouse,
buttons: middle ? kMiddleMouseButton : kPrimaryButton,
);
await gesture.moveBy(const Offset(48, 20));
await gesture.up();
if (!middle) await tester.sendKeyUpEvent(LogicalKeyboardKey.space);
await tester.pump();
expect(c.camera.baseTick, 2 * second);
expect(c.camera.verticalOffset, initialVertical - 20);
expect(c.version, same(base));
expect(c.isDragging, isFalse);
expect(c.canUndo, isFalse);
});
}
testWidgets(
'native trackpad cumulative scale applies once and retains the playhead',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.panBy(horizontalPixels: 240);
c.seekTo(20 * second);
final base = c.version;
final origin = tester.getTopLeft(surface);
final v = viewport(tester);
final anchor = c.playheadTick;
final anchorX = c.camera.screenXForTick(anchor, v);
final initialScale = c.camera.pixelsPerTick;
final initialVertical = c.camera.verticalOffset;
final trackpad = await tester.createGesture(
kind: PointerDeviceKind.trackpad,
);
await trackpad.panZoomStart(origin + const Offset(300, 120));
await trackpad.panZoomUpdate(
origin + const Offset(300, 120),
scale: 1.5,
pan: const Offset(40, 10),
);
await trackpad.panZoomUpdate(
origin + const Offset(300, 120),
scale: 2,
pan: const Offset(60, 20),
);
await trackpad.panZoomEnd();
await tester.pump();
expect(c.camera.pixelsPerTick, closeTo(initialScale * 2, 1e-15));
expect(c.camera.screenXForTick(anchor, v), closeTo(anchorX, 1e-6));
// The example content fits vertically, so panning retains its fitted bounds.
expect(c.camera.verticalOffset, initialVertical);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'second touch cancels clip preview and pinches without committing',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final base = c.version;
final origin = tester.getTopLeft(surface);
final one = await tester.startGesture(
origin + const Offset(100, 112),
pointer: 1,
);
await one.moveBy(const Offset(40, 0));
await tester.pump();
expect(c.isDragging, isTrue);
final two = await tester.startGesture(
origin + const Offset(240, 112),
pointer: 2,
);
await tester.pump();
expect(c.isDragging, isFalse);
await one.moveTo(origin + const Offset(100, 112));
await two.moveTo(origin + const Offset(300, 112));
await tester.pump();
expect(c.camera.pixelsPerTick, greaterThan(24 / second));
await two.up();
await one.moveBy(const Offset(20, 0));
await one.up();
expect(c.version, same(base));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
},
);
testWidgets(
'camera gestures followed by clip drop use current local coordinates',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
await wheel(tester, const Offset(24, 10));
await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft);
await wheel(
tester,
const Offset(0, -60),
at: tester.getTopLeft(surface) + const Offset(100, 110),
);
await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft);
final v = viewport(tester);
final id = c.version.kernelVersion.query().elementById(
ElementId('title'),
)!;
final point = Offset(
c.camera.screenXForTick(3 * second, v),
c.camera.screenYForWorld(100, v),
);
final g = await tester.startGesture(tester.getTopLeft(surface) + point);
final delta = 2 * second * c.camera.pixelsPerTick;
await g.moveBy(Offset(delta, 0));
await g.up();
await tester.pump();
expect(
c.version.kernelVersion.query().absoluteStart(id),
closeTo(4 * second, 1),
);
expect(c.canUndo, isTrue);
expect(tester.takeException(), isNull);
},
);
test(
'navigation is precise at large origins and zoom clamps around anchor',
() {
final c = createDemoController();
addTearDown(c.dispose);
final v = TimelineViewportRect(width: 800, height: 300);
const origin = 9007199254740993;
c.setCamera(TimelineCamera(baseTick: origin, pixelsPerTick: 1));
c.navigate(
from: const Offset(20, 10),
to: const Offset(40, 25),
viewport: v,
);
expect(c.camera.baseTick, origin - 20);
expect(c.camera.verticalOffset, -15);
c.setCamera(initialDemoCamera());
c.navigate(
from: const Offset(100, 0),
to: const Offset(100, 0),
scale: 1e10,
viewport: v,
);
expect(c.camera.pixelsPerTick * c.frameTicks, closeTo(32, 1e-6));
c.seekTo(-100);
expect(c.playheadTick, 0);
expect(c.canUndo, isFalse);
},
);
}
@@ -0,0 +1,100 @@
import 'package:cutdex_core/timeline/model.dart';
import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
void main() {
const second = TimelineClock.ticksPerSecond;
final toggle = find.byKey(const Key('playback-toggle'));
TimelineViewController controller(WidgetTester tester) => tester
.widget<TimelineView>(find.byKey(const Key('timeline-surface')))
.controller;
testWidgets('play, pause and resume advance only presentation time', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final original = c.version;
c.seekTo(2 * second);
await tester.tap(toggle);
await tester.pump();
await tester.pump(const Duration(seconds: 2));
expect(c.playheadTick, 4 * second);
expect(find.byTooltip('暂停 / Pause'), findsOneWidget);
await tester.tap(toggle);
await tester.pump(const Duration(seconds: 3));
expect(c.playheadTick, 4 * second);
expect(find.byTooltip('播放 / Play'), findsOneWidget);
await tester.tap(toggle);
await tester.pump();
await tester.pump(const Duration(milliseconds: 500));
expect(c.playheadTick, 4 * second + second ~/ 2);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
await tester.pumpWidget(const SizedBox());
expect(tester.takeException(), isNull);
});
testWidgets('seek rebases playback; end pauses and play restarts', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final end = c.version.kernelVersion.query().storylineSpan(c.storyline);
await tester.tap(toggle);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
c.seekTo(10 * second);
await tester.pump(const Duration(seconds: 1));
expect(c.playheadTick, 11 * second);
c.seekTo(end - second ~/ 2);
await tester.pump(const Duration(seconds: 1));
expect(c.playheadTick, end);
expect(find.byTooltip('播放 / Play'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
expect(c.playheadTick, end);
await tester.tap(toggle);
await tester.pump();
expect(c.playheadTick, 0);
await tester.pump(const Duration(seconds: 1));
expect(c.playheadTick, second);
await tester.pumpWidget(const SizedBox());
});
testWidgets('scene switch pauses the previous playhead', (tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final short = controller(tester);
await tester.tap(toggle);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
await tester.tap(find.byTooltip('切换场景 / Switch scene'));
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
await tester.tap(find.text('3 小时 / 3 hours'));
await tester.pump();
final stopped = short.playheadTick;
await tester.pumpAndSettle();
expect(controller(tester), isNot(same(short)));
expect(find.byTooltip('播放 / Play'), findsOneWidget);
await tester.pump(const Duration(seconds: 2));
expect(short.playheadTick, stopped);
expect(controller(tester).playheadTick, 0);
});
testWidgets('backgrounding pauses playback', (tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
await tester.tap(toggle);
await tester.pump();
await tester.pump(const Duration(seconds: 1));
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.inactive);
await tester.pump(const Duration(seconds: 2));
expect(c.playheadTick, second);
expect(find.byTooltip('播放 / Play'), findsOneWidget);
tester.binding.handleAppLifecycleStateChanged(AppLifecycleState.resumed);
await tester.pump(const Duration(seconds: 1));
expect(c.playheadTick, second);
});
}
@@ -0,0 +1,83 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
void main() {
for (final dx in [0.0, 24.0]) {
test('ending keeps its off-axis ghost with horizontal delta $dx', () {
final c = createDemoController();
addTearDown(c.dispose);
final viewport = TimelineViewportRect(width: 2000, height: 400);
final base = c.version;
final q = base.kernelVersion.query();
final ending = q.elementById(ElementId('ending'))!;
final x = c.camera.screenXForTick(q.absoluteStart(ending), viewport) + 50;
expect(c.beginDrag(viewport: viewport, position: Offset(x, 178)), isTrue);
c.updateDrag(viewport: viewport, position: Offset(x + dx, 90));
expect(c.dragGhost, isNotNull, reason: c.dragRejection);
expect(c.dragGhost!.top, 62);
expect(c.version, same(base));
c.cancelDrag();
expect(c.canUndo, isFalse);
});
}
for (final name in ['opening', 'street']) {
testWidgets(
'detach $name rejects connected owners without changing transitions',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final surface = find.byKey(const Key('timeline-surface'));
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final source = q.elementById(ElementId(name))!;
final carried = q.connectionsInElementSubtrees([
source,
], includeStoryline: (s) => s == c.storyline);
final x = name == 'opening' ? 100.0 : 300.0;
final gesture = await tester.startGesture(
origin + Offset(x, 178),
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(origin + Offset(x + 30, 110));
await tester.pump();
expect(carried, isNotEmpty);
expect(c.dragRejection, contains('connected clips'));
expect(c.dragGhosts.length, 1 + carried.length);
final prepared = c.project(viewport).version;
final pq = prepared.kernelVersion.query();
expect(pq.storylineLength(c.storyline), q.storylineLength(c.storyline));
// A rejected drag must not remove the neighboring overlap transition.
expect(pq.storylineSpan(c.storyline), q.storylineSpan(c.storyline));
for (final child in carried) {
expect(
pq.absoluteStart(child.target) - pq.absoluteStart(source),
q.absoluteStart(child.target) - q.absoluteStart(source),
);
expect(
pq.connectionOrderLocation(child.target)!.side,
q.connectionOrderLocation(child.target)!.side,
);
}
expect(c.version, same(original));
await gesture.up();
await tester.pump();
expect(c.version, same(prepared));
expect(c.version, same(original));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
},
);
}
}
@@ -0,0 +1,157 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
void main() {
final surface = find.byKey(const Key('timeline-surface'));
for (final dropX in [20.0, 470.0, 1020.0]) {
test('noncontiguous Primary group moves to boundary $dropX', () {
final c = createDemoController();
addTearDown(c.dispose);
final viewport = TimelineViewportRect(width: 2000, height: 400);
final q = c.version.kernelVersion.query();
final a = q.elementById(ElementId('street'))!;
final b = q.elementById(ElementId('voice'))!;
c.setSelection([b, a]);
expect(
c.beginDrag(viewport: viewport, position: const Offset(300, 178)),
isTrue,
);
c.updateDrag(viewport: viewport, position: Offset(dropX, 178));
expect(c.dragRejection, isNull);
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
final pq = c.project(viewport).version.kernelVersion.query();
expect(
pq.storylineElements(c.storyline).map((h) => pq.element(h).name),
dropX == 20
? ['street', 'voice', 'opening', 'gap', 'compound', 'ending']
: dropX == 470
? ['opening', 'gap', 'street', 'voice', 'compound', 'ending']
: ['opening', 'gap', 'compound', 'ending', 'street', 'voice'],
);
c.cancelDrag();
expect(c.canUndo, isFalse);
});
}
for (final drop in [
const Offset(100, 178),
const Offset(420, 178),
const Offset(500, 90),
]) {
test(
'Primary group no-op or rejected drop $drop leaves history unchanged',
() {
final c = createDemoController();
addTearDown(c.dispose);
final viewport = TimelineViewportRect(width: 2000, height: 400);
final original = c.version;
final q = original.kernelVersion.query();
final a = q.elementById(ElementId('opening'))!;
final b = q.elementById(ElementId('street'))!;
c.setSelection([a, b]);
expect(
c.beginDrag(viewport: viewport, position: const Offset(300, 178)),
isTrue,
);
c.updateDrag(viewport: viewport, position: const Offset(720, 178));
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
c.updateDrag(viewport: viewport, position: drop);
expect(c.project(viewport).version, same(original));
expect(c.dragGhosts.length, 6);
expect(c.finishDrag(viewport: viewport, position: drop), isFalse);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
expect(c.selectedIdentities, {a, b});
},
);
}
for (final contiguous in [true, false]) {
for (final grabSecond in [false, true]) {
testWidgets(
'Primary group reorder contiguous=$contiguous grabSecond=$grabSecond',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = tester.widget<TimelineView>(surface).controller;
final origin = tester.getTopLeft(surface);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final original = c.version;
final q = original.kernelVersion.query();
final a = q.elementById(ElementId('opening'))!;
final b = q.elementById(
ElementId(contiguous ? 'street' : 'compound'),
)!;
// Reverse selection order must not reverse timeline order.
c.setSelection([b, a]);
await tester.pump();
final grabbed = grabSecond ? b : a;
final downX =
c.camera.screenXForTick(q.absoluteStart(grabbed), viewport) + 100;
final drag = await tester.startGesture(
origin + Offset(downX, 178),
kind: PointerDeviceKind.mouse,
);
await drag.moveTo(origin + const Offset(720, 178));
await tester.pump();
expect(c.isDragging, isTrue);
expect(c.dragRejection, isNull);
expect(c.dragMode, LayoutPreviewMode.primaryInsert);
expect(c.version, same(original));
expect(c.canUndo, isFalse);
final prepared = c.project(viewport).version;
final pq = prepared.kernelVersion.query();
final names = pq
.storylineElements(c.storyline)
.map((h) => pq.element(h).name)
.toList();
expect(
names,
contiguous
? ['gap', 'compound', 'opening', 'street', 'voice', 'ending']
: ['street', 'gap', 'opening', 'compound', 'voice', 'ending'],
);
final carried = q.connectionsInElementSubtrees([
a,
b,
], includeStoryline: (s) => s == c.storyline).toList();
expect(c.dragGhosts.length, 2 + carried.length);
for (final connection in carried) {
expect(pq.connectionForTarget(connection.target), connection);
expect(
pq.absoluteStart(connection.target) -
pq.absoluteStart(connection.anchor),
q.absoluteStart(connection.target) -
q.absoluteStart(connection.anchor),
);
}
for (final h in q.storylineElements(c.storyline)) {
expect(pq.element(h).sourceStart, q.element(h).sourceStart);
expect(pq.element(h).duration, q.element(h).duration);
}
if (contiguous) {
expect(pq.storylineSpan(c.storyline), q.storylineSpan(c.storyline));
}
await drag.up();
await tester.pump();
expect(c.version, same(prepared));
expect(c.selectedIdentities, {a, b});
c.undo();
expect(c.version, same(original));
expect(c.canUndo, isFalse);
c.redo();
expect(c.version, same(prepared));
expect(tester.takeException(), isNull);
},
);
}
}
}
@@ -0,0 +1,249 @@
import 'dart:math' as math;
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/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
import 'package:timeline_ui_example/main.dart';
Finder thumb(Axis axis) => find.byKey(ValueKey('timeline-${axis.name}-thumb'));
Finder bar(Axis axis) =>
find.byKey(ValueKey('timeline-${axis.name}-scrollbar'));
final surface = find.byKey(const Key('timeline-surface'));
TimelineViewController controller(WidgetTester tester) =>
tester.widget<TimelineView>(surface).controller;
void main() {
testWidgets('scrollbar navigation then clip drop uses the current camera', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final g = await tester.startGesture(
tester.getCenter(thumb(Axis.horizontal)),
);
await g.moveBy(const Offset(30, 0));
await g.up();
await tester.pump();
const second = TimelineClock.ticksPerSecond;
final v = TimelineViewportRect(
width: tester.getSize(surface).width,
height: tester.getSize(surface).height,
);
final id = c.version.kernelVersion.query().elementById(ElementId('title'))!;
final point = Offset(
c.camera.screenXForTick(3 * second, v),
c.camera.screenYForWorld(100, v),
);
final clip = await tester.startGesture(tester.getTopLeft(surface) + point);
await clip.moveBy(Offset(2 * second * c.camera.pixelsPerTick, 0));
await clip.up();
await tester.pump();
expect(
c.version.kernelVersion.query().absoluteStart(id),
closeTo(4 * second, 1),
);
expect(c.canUndo, isTrue);
expect(tester.takeException(), isNull);
});
for (final axis in Axis.values) {
testWidgets('$axis thumb drag pans only that axis and retains roots', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(
MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: 400,
height: 120,
child: TimelineViewport(
controller: c,
showRuler: false,
child: const SizedBox.expand(),
),
),
),
),
);
await tester.pumpAndSettle();
// Begin at the start of both scroll ranges with guaranteed overflow.
c.panBy(horizontalPixels: -200, verticalPixels: -300);
await tester.pump();
final before = c.camera;
final version = c.version;
final initial = tester.getRect(thumb(axis));
final gesture = await tester.startGesture(initial.center);
final delta = axis == Axis.horizontal
? const Offset(35, 0)
: const Offset(0, 35);
await gesture.moveBy(delta);
await tester.pump();
final moved = tester.getRect(thumb(axis));
expect(moved.width, closeTo(initial.width, 1e-6));
expect(moved.height, closeTo(initial.height, 1e-6));
expect((moved.topLeft - initial.topLeft).distance, closeTo(35, 1e-6));
await gesture.up();
await tester.pump();
if (axis == Axis.horizontal) {
expect(c.camera.baseTick, greaterThan(before.baseTick));
expect(c.camera.verticalOffset, before.verticalOffset);
} else {
expect(c.camera.verticalOffset, greaterThan(before.verticalOffset));
expect(c.camera.baseTick, before.baseTick);
expect(c.camera.fractionalTick, before.fractionalTick);
}
expect(c.version, same(version));
expect(c.canUndo, isFalse);
expect(c.selectedIdentities, isEmpty);
expect(tester.takeException(), isNull);
});
}
testWidgets('zoom resizes thumb, pan updates position, track click pages', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final width = tester.getSize(thumb(Axis.horizontal)).width;
c.navigate(
from: Offset.zero,
to: Offset.zero,
scale: 2,
viewport: TimelineViewportRect(
width: tester.getSize(surface).width,
height: 0,
),
);
await tester.pump();
expect(tester.getSize(thumb(Axis.horizontal)).width, lessThan(width));
final left = tester.getTopLeft(thumb(Axis.horizontal)).dx;
c.panBy(horizontalPixels: 100);
await tester.pump();
expect(tester.getTopLeft(thumb(Axis.horizontal)).dx, greaterThan(left));
final before = c.camera;
final track = tester.getRect(bar(Axis.horizontal));
await tester.tapAt(Offset(track.right - 2, track.center.dy));
await tester.pump();
expect(c.camera.baseTick, greaterThan(before.baseTick));
expect(c.canUndo, isFalse);
});
testWidgets('external zoom during thumb drag cannot restore stale camera', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final gesture = await tester.startGesture(
tester.getCenter(thumb(Axis.horizontal)),
);
await gesture.moveBy(const Offset(25, 0));
await tester.pump();
c.navigate(
from: Offset.zero,
to: Offset.zero,
scale: 2,
viewport: TimelineViewportRect(
width: tester.getSize(surface).width,
height: 0,
),
);
await tester.pump();
final zoomed = c.camera;
await gesture.moveBy(const Offset(25, 0));
await gesture.up();
expect(c.camera, same(zoomed));
});
testWidgets('small and fitting viewports remain finite and do not scroll', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
c.setCamera(
TimelineCamera(baseTick: 0, pixelsPerTick: c.camera.pixelsPerTick / 100),
);
await tester.pumpWidget(
MaterialApp(
home: TimelineViewport(
controller: c,
showRuler: false,
child: const SizedBox.expand(),
),
),
);
expect(thumb(Axis.vertical), findsNothing);
await tester.pumpWidget(
MaterialApp(
home: Center(
child: SizedBox(
width: 8,
height: 8,
child: TimelineViewport(
showRuler: false,
controller: c,
child: const SizedBox.expand(),
),
),
),
),
);
expect(tester.takeException(), isNull);
});
test(
'scroll extent getters agree with body scans and projected placements',
() {
final c = createDemoController();
addTearDown(c.dispose);
final v = c.version;
for (final entry in v.rangeIndexRoot.entries) {
final bodies = v.partitionBodies[entry.key]!.map(
(id) => v.scene.bodies[id]!,
);
if (bodies.isEmpty) {
expect(entry.value.timeBounds, isNull);
} else {
expect(entry.value.timeBounds, (
start: bodies.map((b) => b.start).reduce(math.min),
end: bodies.map((b) => b.end).reduce(math.max),
));
}
}
for (final entry in v.domainRoot.entries) {
final placements = v.placements.values.where(
(p) => p.partition.stack == entry.key,
);
for (final p in placements) {
final outer = entry.value.outerBoundary;
expect(outer <= p.top || outer >= p.top + p.height, isTrue);
}
}
},
);
test('scrollbar theme tokens copy and interpolate', () {
const a = TimelineThemeData.dark();
final b = a.copyWith(
scrollbarThickness: 20,
scrollbarThumbColor: Colors.red,
scrollbarTrackColor: Colors.blue,
);
expect(b, isNot(a));
expect(b.copyWith(), b);
expect(a.lerp(b, .5).scrollbarThickness, 16);
expect(
a.lerp(b, .5).scrollbarThumbColor,
Color.lerp(a.scrollbarThumbColor, Colors.red, .5),
);
expect(
a.lerp(b, .5).scrollbarTrackColor,
Color.lerp(a.scrollbarTrackColor, Colors.blue, .5),
);
});
}
@@ -0,0 +1,292 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
import 'support/timeline_geometry.dart';
final surface = find.byKey(const Key('timeline-surface'));
final marquee = find.byKey(const ValueKey('timeline-marquee'));
TimelineViewController controller(WidgetTester tester) =>
tester.widget<TimelineView>(surface).controller;
Set<Object> connected(TimelineViewController c) => {
for (final name in ['title', 'overlay'])
LayoutBodyId.element(
c.version.kernelVersion.query().elementById(ElementId(name))!,
),
};
void main() {
testWidgets('blank marquee selects without moving the playhead', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.seekTo(TimelineClock.ticksPerSecond);
final origin = tester.getTopLeft(surface);
final rectangle = connectedMarquee(c, viewportFor(tester));
final gesture = await tester.startGesture(
origin + rectangle.topLeft,
kind: PointerDeviceKind.mouse,
);
await gesture.moveTo(origin + rectangle.bottomRight);
await tester.pump();
expect(marquee, findsOneWidget);
expect(c.playheadTick, TimelineClock.ticksPerSecond);
await gesture.up();
await tester.pump();
expect(c.selectedIdentities, isNotEmpty);
expect(c.playheadTick, TimelineClock.ticksPerSecond);
expect(marquee, findsNothing);
});
testWidgets(
'blank click seeks on release, clears selection and allows tail time',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final base = c.version;
c.setSelection(connected(c));
c.seekTo(TimelineClock.ticksPerSecond);
c.panBy(horizontalPixels: 1800);
final size = tester.getSize(surface);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
await tester.pump();
const point = Offset(253, 10);
final raw = c.camera.tickAtScreenX(
point.dx,
viewport,
rounding: TimelineTickRounding.nearest,
);
final frame = TimelineFormat.fps24.frameGrid.quantumTicks;
final expected = (raw / frame).round() * frame;
final gesture = await tester.startGesture(
tester.getTopLeft(surface) + point,
kind: PointerDeviceKind.mouse,
);
await tester.pump();
expect(c.playheadTick, TimelineClock.ticksPerSecond);
expect(c.selectedIdentities, connected(c));
await gesture.up();
await tester.pump();
expect(c.playheadTick, expected);
expect(c.playheadTick % frame, 0);
expect(c.selectedIdentities, isEmpty);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
},
);
testWidgets(
'clip click selects without seeking and cancelled blank click does not seek',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.seekTo(TimelineClock.ticksPerSecond);
final origin = tester.getTopLeft(surface);
await tester.tapAt(origin + const Offset(100, 110));
await tester.pump();
expect(c.selectedIdentities, isNotEmpty);
expect(c.playheadTick, TimelineClock.ticksPerSecond);
final selected = c.selectedIdentities.toSet();
final gesture = await tester.startGesture(
origin + const Offset(10, 10),
kind: PointerDeviceKind.mouse,
);
await gesture.cancel();
await tester.pump();
expect(c.selectedIdentities, selected);
expect(c.playheadTick, TimelineClock.ticksPerSecond);
},
);
testWidgets('history change during marquee cannot restore stale selection', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final size = tester.getSize(surface);
final v = TimelineViewportRect(width: size.width, height: size.height);
c.beginDrag(viewport: v, position: const Offset(100, 110));
c.finishDrag(viewport: v, position: const Offset(140, 110));
final origin = tester.getTopLeft(surface);
final rectangle = connectedMarquee(c, viewportFor(tester));
final g = await tester.startGesture(
origin + rectangle.topLeft,
kind: PointerDeviceKind.mouse,
);
await g.moveTo(origin + rectangle.bottomRight);
await tester.pump();
c.undo();
final restored = c.version;
await g.up();
await tester.pump();
expect(c.version, same(restored));
expect(c.selectedIdentities, isEmpty);
expect(marquee, findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('disposing active marquee restores the old view selection', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final origin = tester.getTopLeft(surface);
final rectangle = connectedMarquee(c, viewportFor(tester));
final g = await tester.startGesture(
origin + rectangle.topLeft,
kind: PointerDeviceKind.mouse,
);
await g.moveTo(origin + rectangle.bottomRight);
await tester.pump();
await tester.pumpWidget(const SizedBox());
await g.up();
expect(c.selectedIdentities, isEmpty);
expect(tester.takeException(), isNull);
});
for (final reverse in [false, true]) {
testWidgets(
'blank mouse drag selects overlapping clips; reverse=$reverse',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final camera = c.camera;
final version = c.version;
final origin = tester.getTopLeft(surface);
final rectangle = connectedMarquee(c, viewportFor(tester));
final g = await tester.startGesture(
origin + (reverse ? rectangle.bottomRight : rectangle.topLeft),
kind: PointerDeviceKind.mouse,
);
await g.moveTo(
origin + (reverse ? rectangle.topLeft : rectangle.bottomRight),
);
await tester.pump();
expect(marquee, findsOneWidget);
expect(c.selectedIdentities, connected(c));
await g.up();
await tester.pump();
expect(marquee, findsNothing);
expect(c.selectedIdentities, connected(c));
expect(c.camera, same(camera));
expect(c.version, same(version));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
},
);
}
for (final cancel in ['escape', 'pointer', 'camera', 'inactive']) {
testWidgets('$cancel cancels marquee and restores previous selection', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
final opening = c.version.kernelVersion.query().elementById(
ElementId('opening'),
)!;
c.setSelection([opening]);
final origin = tester.getTopLeft(surface);
final rectangle = connectedMarquee(c, viewportFor(tester));
final g = await tester.startGesture(
origin + rectangle.topLeft,
kind: PointerDeviceKind.mouse,
);
await g.moveTo(origin + rectangle.bottomRight);
await tester.pump();
expect(c.selectedIdentities, connected(c));
switch (cancel) {
case 'escape':
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
case 'pointer':
await g.cancel();
case 'camera':
c.panBy(horizontalPixels: 20);
case 'inactive':
tester.binding.handleAppLifecycleStateChanged(
AppLifecycleState.inactive,
);
}
if (cancel != 'pointer') await g.up();
if (cancel == 'inactive') {
tester.binding.handleAppLifecycleStateChanged(
AppLifecycleState.resumed,
);
}
await tester.pump();
expect(marquee, findsNothing);
expect(c.selectedIdentities, {opening});
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
});
}
testWidgets('rectangle selection uses the panned and zoomed frame', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.panBy(horizontalPixels: 15, verticalPixels: 10);
final size = tester.getSize(surface);
final v = TimelineViewportRect(width: size.width, height: size.height);
c.navigate(from: Offset.zero, to: Offset.zero, scale: 1.25, viewport: v);
await tester.pump();
final origin = tester.getTopLeft(surface);
final rectangle = connectedMarquee(c, viewportFor(tester));
final g = await tester.startGesture(
origin + rectangle.topLeft,
kind: PointerDeviceKind.mouse,
);
await g.moveTo(origin + rectangle.bottomRight);
await g.up();
await tester.pump();
expect(c.selectedIdentities, connected(c));
expect(c.hitTestRect(viewport: v, rectangle: Rect.zero), isEmpty);
expect(
c.hitTestRect(
viewport: v,
rectangle: const Rect.fromLTWH(-100, -100, 5, 5),
),
isEmpty,
);
expect(c.canUndo, isFalse);
});
testWidgets('group selection moves all selected connected clips together', (
tester,
) async {
await tester.pumpWidget(const TimelineExampleApp());
final c = controller(tester);
c.setSelection(connected(c));
final version = c.version;
final origin = tester.getTopLeft(surface);
final g = await tester.startGesture(
origin + const Offset(100, 110),
kind: PointerDeviceKind.mouse,
);
await g.moveBy(const Offset(50, 0));
await g.up();
await tester.pump();
expect(c.selectedIdentities, connected(c));
expect(c.version, isNot(same(version)));
expect(c.isDragging, isFalse);
expect(c.dragRejection, isNull);
final q = c.version.kernelVersion.query();
expect(
q.absoluteStart(q.elementById(ElementId('overlay'))!) -
q.absoluteStart(q.elementById(ElementId('title'))!),
2 * TimelineClock.ticksPerSecond,
);
c.undo();
expect(c.version, same(version));
});
}
@@ -0,0 +1,84 @@
import 'dart:math' as math;
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/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
final timelineView = find.byType(TimelineView);
TimelineViewportRect viewportFor(WidgetTester tester) {
final size = tester.getSize(timelineView);
return TimelineViewportRect(width: size.width, height: size.height);
}
Rect clipBody(
TimelineViewController controller,
TimelineViewportRect viewport,
String name,
) {
final owner = controller.version.kernelVersion.query().elementById(
ElementId(name),
)!;
final frame = controller.project(viewport);
final index = [
for (var i = 0; i < frame.length; i++)
if (controller.elementForIdentity(frame.identityAt(i)) == owner &&
frame.kindAt(i) != TimelineViewportItemKind.transition)
i,
].single;
final layout = controller.clipLayout(
controller.presentationBoundsAt(frame, index),
owner: owner,
);
return layout.toViewport(layout.body);
}
Offset clipPoint(WidgetTester tester, String name, {TimelineTrimEdge? edge}) {
final controller = tester.widget<TimelineView>(timelineView).controller;
final body = clipBody(controller, viewportFor(tester), name);
final local = Offset(switch (edge) {
TimelineTrimEdge.leading => body.left + 1,
TimelineTrimEdge.trailing => body.right - 1,
null => body.center.dx,
}, body.center.dy);
final hit = controller.hitTest(
viewport: viewportFor(tester),
position: local,
);
expect(
controller.elementForIdentity(hit!.identity),
controller.version.kernelVersion.query().elementById(ElementId(name)),
);
if (edge != null) {
expect(
controller.trimEdgeAt(
hit: hit,
position: local,
extent: TimelineThemeData.of(
tester.element(timelineView),
).trimHitExtent,
),
edge,
);
}
return tester.getTopLeft(timelineView) + local;
}
Rect connectedMarquee(
TimelineViewController controller,
TimelineViewportRect viewport,
) {
final bodies = clipBody(
controller,
viewport,
'title',
).expandToInclude(clipBody(controller, viewport, 'overlay'));
return Rect.fromLTRB(
math.max(0, bodies.left - 4),
math.max(0, bodies.top - 4),
math.min(viewport.width - 1, bodies.right + 4),
math.min(viewport.height - 1, bodies.bottom + 4),
);
}
@@ -0,0 +1,333 @@
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/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/demo_timeline.dart';
import 'support/timeline_geometry.dart';
const second = TimelineClock.ticksPerSecond;
Widget surface(
TimelineViewController c, {
double width = 960,
double extent = 0,
}) => MaterialApp(
home: Align(
alignment: Alignment.topLeft,
child: SizedBox(
width: width,
height: 360,
child: TimelineInteractionRegion(
controller: c,
edgeScrollExtent: extent,
child: TimelineView(controller: c),
),
),
),
);
void main() {
test('trim theme tokens copy, interpolate and affect equality', () {
const dark = TimelineThemeData.dark();
final other = dark.copyWith(trimHandleWidth: 5, trimHitExtent: 10);
expect(other.copyWith(), other);
expect(dark == other, isFalse);
expect(dark.lerp(other, 0.5).trimHandleWidth, 3.5);
expect(dark.lerp(other, 0.5).trimHitExtent, 8);
});
testWidgets('Primary leading audio trim keeps its serial edit point', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
c.setCamera(
TimelineCamera(baseTick: 24 * second, pixelsPerTick: 24 / second),
);
await tester.pumpWidget(surface(c));
final voice = c.version.kernelVersion.query().elementById(
ElementId('voice'),
)!;
final gesture = await tester.startGesture(
clipPoint(tester, 'voice', edge: TimelineTrimEdge.leading),
);
await gesture.moveBy(const Offset(48, 0));
await gesture.up();
final q = c.version.kernelVersion.query();
expect(q.positionOf(voice).position, 28 * second);
expect(q.element(voice).duration, 4 * second);
expect(q.element(voice).sourceStart, 2 * second);
expect(q.storylineSpan(c.storyline), 40 * second);
expect(tester.takeException(), isNull);
});
for (final leading in [true, false]) {
testWidgets(
'container ${leading ? "leading" : "trailing"} trim keeps definition',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
c.setCamera(
TimelineCamera(baseTick: 19 * second, pixelsPerTick: 24 / second),
);
await tester.pumpWidget(surface(c));
final h = c.version.kernelVersion.query().elementById(
ElementId('compound'),
)!;
final gesture = await tester.startGesture(
clipPoint(
tester,
'compound',
edge: leading
? TimelineTrimEdge.leading
: TimelineTrimEdge.trailing,
),
);
await gesture.moveBy(Offset(leading ? 48 : -48, 0));
await gesture.up();
final q = c.version.kernelVersion.query();
expect(q.element(h).duration, 6 * second);
expect(q.element(h).sourceStart, (leading ? 2 : 0) * second);
expect(q.storylineSpan(q.element(h).containerStoryline!), 8 * second);
expect(q.storylineSpan(c.storyline), 40 * second);
expect(tester.takeException(), isNull);
},
);
}
for (final end in [
'escape',
'cancel',
'history',
'resize',
'unmount',
'second pointer',
]) {
testWidgets('trim cannot publish after $end', (tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final viewport = viewportFor(tester);
final base = c.version;
final down = clipPoint(tester, 'title', edge: TimelineTrimEdge.leading);
final gesture = await tester.startGesture(down);
await gesture.moveBy(const Offset(48, 0));
await tester.pump();
expect(c.isTrimming, isTrue);
expect(c.project(viewport).version, isNot(same(base)));
switch (end) {
case 'escape':
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
case 'cancel':
await gesture.cancel();
case 'history':
c.undo();
case 'resize':
await tester.pumpWidget(surface(c, width: 700));
case 'unmount':
await tester.pumpWidget(const SizedBox());
case 'second pointer':
final second = await tester.startGesture(
const Offset(400, 200),
pointer: 2,
);
await second.up();
}
if (end != 'cancel') await gesture.up();
await tester.pump();
expect(c.isDragging, isFalse);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
expect(tester.takeException(), isNull);
});
}
testWidgets(
'invalid trim clears old preview and can recover in the same gesture',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final viewport = viewportFor(tester);
final base = c.version;
final down = clipPoint(tester, 'title', edge: TimelineTrimEdge.leading);
final gesture = await tester.startGesture(down);
await gesture.moveTo(down + const Offset(48, 0));
await tester.pump();
expect(c.project(viewport).version, isNot(same(base)));
await gesture.moveTo(down + const Offset(168, 0));
await tester.pump();
expect(c.dragRejection, isNotNull);
expect(c.project(viewport).version, same(base));
await gesture.moveTo(down + const Offset(24, 0));
await tester.pump();
expect(c.dragRejection, isNull);
final prepared = c.project(viewport).version;
await gesture.up();
expect(c.version, same(prepared));
expect(
c.version.kernelVersion
.query()
.element(
base.kernelVersion.query().elementById(ElementId('title'))!,
)
.duration,
4 * second,
);
},
);
testWidgets('invalid release and returning to grab point create no history', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final base = c.version;
for (final delta in [168.0, 0.0]) {
final down = clipPoint(tester, 'title', edge: TimelineTrimEdge.leading);
final gesture = await tester.startGesture(down);
await gesture.moveTo(down + const Offset(48, 0));
await tester.pump();
await gesture.moveTo(down + Offset(delta, 0));
await gesture.up();
expect(c.version, same(base));
expect(c.canUndo, isFalse);
}
});
testWidgets(
'Camera pan while trimming re-resolves once and zoom retains pointer time',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final viewport = viewportFor(tester);
final title = c.version.kernelVersion.query().elementById(
ElementId('title'),
)!;
final down = clipPoint(tester, 'title', edge: TimelineTrimEdge.trailing);
final gesture = await tester.startGesture(down);
await gesture.moveBy(const Offset(-48, 0));
c.panBy(horizontalPixels: 24);
expect(
c
.project(viewport)
.version
.kernelVersion
.query()
.element(title)
.duration,
4 * second,
);
c.zoomAt(
screenX: down.dx - 48,
newPixelsPerTick: 48 / second,
viewport: viewport,
);
final prepared = c.project(viewport).version;
expect(
prepared.kernelVersion.query().element(title).duration,
4 * second,
);
await gesture.up();
expect(c.version, same(prepared));
},
);
testWidgets(
'long-scene edge auto-scroll trims to latest Camera and stops on release',
(tester) async {
final c = createDemoController(longTimeline: true);
addTearDown(c.dispose);
await tester.pumpWidget(surface(c, width: 640, extent: 48));
final viewport = TimelineViewportRect(width: 640, height: 360);
final base = c.version;
final title = base.kernelVersion.query().elementById(ElementId('title'))!;
final down = clipPoint(tester, 'title', edge: TimelineTrimEdge.trailing);
final gesture = await tester.startGesture(down);
await gesture.moveTo(Offset(632, down.dy));
await tester.pump();
final before = c.camera;
for (var i = 0; i < 12; i++) {
await tester.pump(const Duration(milliseconds: 16));
}
expect(c.camera.baseTick, greaterThan(before.baseTick));
expect(c.dragRejection, isNull);
final prepared = c.project(viewport).version;
final q = prepared.kernelVersion.query();
expect(
c.camera.screenXForTick(
q.absoluteStart(title) + q.element(title).duration,
viewport,
),
closeTo(633, 0.001),
);
await gesture.up();
final camera = c.camera;
await tester.pump(const Duration(seconds: 1));
expect(c.camera, same(camera));
expect(c.version, same(prepared));
c.undo();
expect(c.version, same(base));
expect(tester.takeException(), isNull);
},
);
for (final leading in [true, false]) {
testWidgets(
'connected ${leading ? "left" : "right"} edge trims, not moves',
(tester) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final viewport = viewportFor(tester);
final base = c.version;
final title = base.kernelVersion.query().elementById(
ElementId('title'),
)!;
final down = clipPoint(
tester,
'title',
edge: leading ? TimelineTrimEdge.leading : TimelineTrimEdge.trailing,
);
final up = down + Offset(leading ? 48 : -48, 0);
final gesture = await tester.startGesture(down);
await gesture.moveTo(up);
await tester.pump();
final preview = c.project(viewport).version;
final q = preview.kernelVersion.query();
expect(q.element(title).duration, 3 * second);
expect(q.absoluteStart(title), (leading ? 4 : 2) * second);
expect(q.element(title).sourceStart, (leading ? 2 : 0) * second);
expect(c.dragGhosts, isEmpty);
expect(c.version, same(base));
expect(c.canUndo, isFalse);
await gesture.up();
await tester.pump();
expect(c.version, same(preview));
c.undo();
expect(c.version, same(base));
c.redo();
expect(c.version, same(preview));
expect(tester.takeException(), isNull);
},
);
}
testWidgets('Primary trailing trim ripples the following serial members', (
tester,
) async {
final c = createDemoController();
addTearDown(c.dispose);
await tester.pumpWidget(surface(c));
final base = c.version.kernelVersion.query();
final street = base.elementById(ElementId('street'))!;
final gap = base.elementById(ElementId('gap'))!;
final gesture = await tester.startGesture(
clipPoint(tester, 'street', edge: TimelineTrimEdge.trailing),
);
await gesture.moveBy(const Offset(-48, 0));
await gesture.up();
final q = c.version.kernelVersion.query();
expect(q.element(street).duration, 8 * second);
expect(q.positionOf(gap).position, 15 * second);
expect(q.storylineSpan(c.storyline), 40 * second);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,80 @@
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/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:timeline_ui_example/main.dart';
void main() {
testWidgets(
'example selects in current camera coordinates and preserves roots',
(tester) async {
await tester.pumpWidget(const TimelineExampleApp());
final finder = find.byKey(const Key('timeline-surface'));
final controller = tester.widget<TimelineView>(finder).controller;
final original = controller.version;
final initialCamera = controller.camera;
final query = original.kernelVersion.query();
final opening = query.elementById(ElementId('opening'))!;
final connected = query.elementById(ElementId('title'))!;
final frame = controller.project(
TimelineViewportRect(width: 1200, height: 400),
);
expect(frame.length, 11); // Six primary, four connected, one transition.
expect(frame.signedLaneAt(frame.length - 1), isNegative);
await tester.tap(find.byTooltip('向右 / Pan right'));
await tester.pump();
expect(controller.camera.baseTick, greaterThan(initialCamera.baseTick));
await tester.tap(find.byTooltip('放大 / Zoom in'));
await tester.pump();
expect(
controller.camera.pixelsPerTick,
greaterThan(initialCamera.pixelsPerTick),
);
final origin = tester.getTopLeft(finder);
final size = tester.getSize(finder);
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final street = query.elementById(ElementId('street'))!;
final x = controller.camera.screenXForTick(
13 * TimelineClock.ticksPerSecond,
viewport,
);
await tester.tapAt(origin + Offset(x, 178));
await tester.pump();
expect(controller.selectedIdentities, {street});
expect(find.textContaining('Selected: street'), findsOneWidget);
await tester.tap(find.byTooltip('切换主题 / Toggle theme'));
await tester.pumpAndSettle();
expect(controller.version, same(original));
expect(Theme.of(tester.element(finder)).brightness, Brightness.light);
expect(controller.selectedIdentities, {street});
await tester.tap(find.text('重置 / Reset'));
await tester.pump();
expect(controller.camera.baseTick, initialCamera.baseTick);
expect(controller.selectedIdentities, isEmpty);
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
await mouse.moveTo(origin + const Offset(100, 112));
await tester.pump();
expect(controller.hoveredIdentity, LayoutBodyId.element(connected));
await mouse.removePointer();
await tester.tapAt(origin + const Offset(100, 178));
await tester.pump();
expect(controller.selectedIdentities, {opening});
await tester.tapAt(origin + const Offset(10, 10));
await tester.pump();
expect(controller.selectedIdentities, isEmpty);
expect(controller.version, same(original));
expect(tester.takeException(), isNull);
},
);
}
@@ -0,0 +1,13 @@
library;
export 'src/timeline_theme.dart';
export 'src/timeline_ruler.dart';
export 'src/timeline_scrollbars.dart';
export 'src/timeline_viewport.dart';
export 'src/timeline_interaction_region.dart';
export 'src/timeline_view.dart';
export 'src/timeline_clip_layout.dart';
export 'src/timeline_view_controller.dart';
export 'src/timeline_thumbnails.dart';
export 'src/timeline_waveforms.dart';
@@ -0,0 +1,98 @@
import 'dart:math' as math;
import 'package:cutdex_core/timeline/layout.dart';
import 'package:cutdex_core/timeline/model.dart';
/// Immutable dimensions and content bounds of one viewport layout.
typedef TimelineCameraBounds = ({
double width,
double height,
int end,
double top,
double bottom,
});
/// Placement requested by the viewport lifecycle or an explicit focus action.
enum TimelineCameraPlacement {
preserve,
initialize,
focusPrimary,
resetPrimary,
}
/// Resolves viewport placement without changing state or notifying listeners.
///
/// Initialization fits an empty timeline to twenty seconds. The controller
/// requests it only for the first valid layout of an uninitialized view.
/// Preserved views retain their scale, including restored empty timelines.
/// When content fits vertically, [restingVerticalOffset] keeps navigation from
/// moving the centered lane while allowing resize to constrain its position.
TimelineCamera resolveTimelineCamera({
required TimelineCamera camera,
required TimelineCameraBounds? bounds,
required double primaryCenter,
required double restingVerticalOffset,
TimelineCameraPlacement placement = TimelineCameraPlacement.preserve,
}) {
if (bounds == null || bounds.width <= 0 || bounds.height <= 0) return camera;
final initializing = placement == TimelineCameraPlacement.initialize;
final scale = initializing && bounds.end == 0
? bounds.width / (20 * TimelineClock.ticksPerSecond)
: camera.pixelsPerTick;
final visible = bounds.width / scale;
final wholeVisible = visible.ceil();
final end = timelineNavigationEnd(
contentEnd: bounds.end,
width: bounds.width,
pixelsPerTick: scale,
);
final maxBase = math.max(0, end - wholeVisible);
final maxFraction = end >= wholeVisible ? wholeVisible - visible : 0.0;
final reset =
placement == TimelineCameraPlacement.resetPrimary ||
initializing && bounds.end == 0;
final exceedsEnd =
camera.baseTick > maxBase ||
(camera.baseTick == maxBase && camera.fractionalTick > maxFraction);
final overflows = bounds.bottom - bounds.top > bounds.height;
final verticalOffset = placement != TimelineCameraPlacement.preserve
? primaryCenter - bounds.height / 2
: overflows
? camera.verticalOffset.clamp(bounds.top, bounds.bottom - bounds.height)
: restingVerticalOffset.clamp(bounds.bottom - bounds.height, bounds.top);
return TimelineCamera(
baseTick: reset
? 0
: exceedsEnd
? maxBase
: camera.baseTick,
fractionalTick: reset
? 0
: exceedsEnd
? maxFraction
: camera.fractionalTick,
pixelsPerTick: scale,
verticalOffset: verticalOffset,
);
}
/// Includes half a viewport beyond content without changing authored duration.
int timelineNavigationEnd({
required int contentEnd,
required double width,
required double pixelsPerTick,
}) {
if (contentEnd == 0 || width <= 0) return contentEnd;
final padding = (width / pixelsPerTick / 2).ceil();
return contentEnd + math.min(padding, 0x7fffffffffffffff - contentEnd);
}
/// Restricts editing views to the nonnegative time domain.
TimelineCamera clampTimelineCameraOrigin(TimelineCamera camera) =>
camera.baseTick < 0
? TimelineCamera(
baseTick: 0,
pixelsPerTick: camera.pixelsPerTick,
verticalOffset: camera.verticalOffset,
)
: camera;
@@ -0,0 +1,92 @@
import 'dart:math' as math;
import 'dart:ui';
/// Clip regions in local coordinates, shared by painting and interaction.
/// [bounds] is the only viewport translation; header changes move every body
/// region together without changing the body's internal layout.
final class TimelineClipLayout {
TimelineClipLayout({
required this.bounds,
double headerHeight = 0,
double nameHeight = 18,
bool audioOnly = false,
bool hasVideoAudio = false,
}) {
final width = math.max(0.0, bounds.width);
final height = math.max(0.0, bounds.height);
final reserved = headerHeight.clamp(0.0, height);
header = Rect.fromLTWH(0, 0, width, reserved);
body = Rect.fromLTWH(0, reserved, width, height - reserved);
bodyPaintBounds = insetBounds(body);
name = Rect.fromLTWH(
bodyPaintBounds.left,
body.top,
bodyPaintBounds.width,
nameHeight.clamp(0.0, body.height),
);
final contentHeight = body.bottom - name.bottom;
final videoWaveformHeight =
hasVideoAudio &&
contentHeight >= waveformStripHeight + minimumPreviewHeight
? waveformStripHeight
: 0.0;
preview = Rect.fromLTRB(
bodyPaintBounds.left,
name.bottom,
bodyPaintBounds.right,
body.bottom - videoWaveformHeight,
);
waveformBackground = audioOnly
? Rect.fromLTRB(
bodyPaintBounds.left,
name.bottom,
bodyPaintBounds.right,
body.bottom,
)
: Rect.fromLTWH(
bodyPaintBounds.left,
body.bottom - videoWaveformHeight,
bodyPaintBounds.width,
videoWaveformHeight,
);
// Audio content keeps its full horizontal span; video uses an inset strip.
waveform =
waveformBackground.height <= 4 ||
(!audioOnly && waveformBackground.width <= 4)
? Rect.fromLTWH(waveformBackground.left, waveformBackground.top, 0, 0)
: audioOnly
? Rect.fromLTRB(
waveformBackground.left,
waveformBackground.top + 2,
waveformBackground.right,
waveformBackground.bottom - 2,
)
: waveformBackground.deflate(2);
}
static const waveformStripHeight = 16.0;
static const minimumPreviewHeight = 20.0;
final Rect bounds;
late final Rect header;
late final Rect body;
late final Rect bodyPaintBounds;
late final Rect name;
late final Rect preview;
late final Rect waveformBackground;
late final Rect waveform;
Offset get keyframeCenter => body.center;
Rect toViewport(Rect region) => region.shift(bounds.topLeft);
static Rect insetBounds(Rect bounds) {
final inset = math.min(1.0, math.max(0.0, bounds.width) / 4);
return Rect.fromLTRB(
bounds.left + inset,
bounds.top,
bounds.right - inset,
bounds.bottom,
);
}
}
@@ -0,0 +1,19 @@
import 'dart:math' as math;
/// Signed pixels per second while a pointer is near or beyond a viewport edge.
double timelineEdgeVelocity(
double position,
double size, {
required double extent,
required double maxSpeed,
}) {
final edge = math.min(extent, size / 2);
if (edge <= 0 || maxSpeed <= 0) return 0;
final penetration = position < edge
? -(edge - position) / edge
: position > size - edge
? (position - size + edge) / edge
: 0.0;
final limited = penetration.clamp(-1.0, 1.0);
return limited * limited.abs() * maxSpeed;
}
@@ -0,0 +1,683 @@
import 'dart:math' as math;
import 'package:cutdex_core/timeline/layout.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'timeline_view_controller.dart';
import 'timeline_theme.dart';
import 'timeline_edge_scroll.dart';
enum _PointerMode { idle, clip, navigate, scrub, marquee, ignored }
/// One input adapter for the ruler and clip surface. Gesture classification is
/// fixed at press (except a second finger, which cancels editing for navigation).
/// ScaleGestureRecognizer handles both touch and native trackpad pan/zoom.
final class TimelineInteractionRegion extends StatefulWidget {
const TimelineInteractionRegion({
required this.controller,
required this.child,
this.ruler = false,
this.keyframes = false,
this.edgeScrollExtent = 48,
this.edgeScrollMaxSpeed = 600,
super.key,
}) : assert(edgeScrollExtent >= 0 && edgeScrollExtent < double.infinity),
assert(edgeScrollMaxSpeed >= 0 && edgeScrollMaxSpeed < double.infinity);
final TimelineViewController controller;
final Widget child;
final bool ruler;
final bool keyframes;
/// Logical pixels inside each edge. Zero disables automatic scrolling.
final double edgeScrollExtent;
/// Logical pixels per second per axis at the edge (quadratic ramp inward).
final double edgeScrollMaxSpeed;
@override
State<TimelineInteractionRegion> createState() =>
_TimelineInteractionRegionState();
}
final class _TimelineInteractionRegionState
extends State<TimelineInteractionRegion>
with WidgetsBindingObserver, SingleTickerProviderStateMixin {
late final Ticker _edgeTicker;
Duration _lastEdgeElapsed = Duration.zero;
final _focus = FocusNode();
final _pointers = <int>{};
_PointerMode _mode = _PointerMode.idle;
Offset? _down;
Offset? _position;
Offset? _focal;
double _scale = 1;
bool _middle = false;
bool _hand = false;
bool _multi = false;
bool _pinching = false;
MouseCursor _cursor = SystemMouseCursors.basic;
TimelineViewportRect? _viewport;
({
Set<Object> before,
LayoutVersion version,
TimelineCamera camera,
TimelineViewportGeometry geometry,
})?
_marquee;
Rect? _selectionRect;
void _controllerChanged() {
_syncEdgeScroll();
final marquee = _marquee;
if (marquee == null) return;
final c = widget.controller;
final sameVersion = identical(marquee.version, c.version);
if (!sameVersion ||
!identical(marquee.camera, c.camera) ||
marquee.geometry != c.geometry) {
_endMarquee(restore: sameVersion);
_mode = _PointerMode.ignored;
}
}
Offset get _edgeVelocity {
final incoming = widget.controller.incomingPointer;
final point = incoming?.position ?? _position;
final viewport = incoming?.viewport ?? _viewport;
final scrubbing =
widget.ruler &&
_mode == _PointerMode.scrub &&
!_multi &&
_pointers.isNotEmpty &&
widget.controller.isScrubbing;
if ((!scrubbing && widget.ruler) ||
(!scrubbing &&
incoming == null &&
(_mode != _PointerMode.clip || _multi || _pointers.isEmpty)) ||
(!scrubbing && !widget.controller.isDragging) ||
point == null ||
viewport == null ||
(!scrubbing && (point.dy < 0 || point.dy >= viewport.height))) {
return Offset.zero;
}
return Offset(
timelineEdgeVelocity(
point.dx,
viewport.width,
extent: widget.edgeScrollExtent,
maxSpeed: widget.edgeScrollMaxSpeed,
),
scrubbing || widget.controller.isDraggingKeyframe
? 0
: timelineEdgeVelocity(
point.dy,
viewport.height,
extent: widget.edgeScrollExtent,
maxSpeed: widget.edgeScrollMaxSpeed,
),
);
}
void _syncEdgeScroll() {
if (_edgeVelocity == Offset.zero) {
_stopEdgeScroll();
} else if (!_edgeTicker.isActive) {
_lastEdgeElapsed = Duration.zero;
_edgeTicker.start();
}
}
void _stopEdgeScroll() {
_edgeTicker.stop();
_lastEdgeElapsed = Duration.zero;
}
void _edgeTick(Duration elapsed) {
final velocity = _edgeVelocity;
if (velocity == Offset.zero) {
_stopEdgeScroll();
return;
}
// Never catch up a suspended/background frame with one giant camera jump.
final seconds = ((elapsed - _lastEdgeElapsed).inMicroseconds / 1000000)
.clamp(0.0, 0.05);
_lastEdgeElapsed = elapsed;
if (seconds == 0) return;
try {
// setCamera re-resolves the retained pointer against the new Camera once.
// No separate drag offset, timeline mutation or layout solver lives here.
final before = widget.controller.camera;
widget.controller.panBy(
horizontalPixels: velocity.dx * seconds,
verticalPixels: velocity.dy * seconds,
);
if (widget.ruler && _mode == _PointerMode.scrub && _position != null) {
_seek(_position!);
}
if (widget.controller.camera == before) _stopEdgeScroll();
} catch (_) {
_cancel();
rethrow;
}
}
void _endMarquee({required bool restore, bool repaint = true}) {
final marquee = _marquee;
_marquee = null;
_selectionRect = null;
if (marquee == null) return;
if (restore && identical(marquee.version, widget.controller.version)) {
widget.controller.setSelection(marquee.before);
}
if (repaint && mounted) setState(() {});
}
void _updateMarquee(Offset point) {
if (_marquee == null || _down == null) return;
_controllerChanged();
if (_marquee == null) return;
final rect = Rect.fromPoints(
_down!,
point,
).intersect(Rect.fromLTWH(0, 0, _viewport!.width, _viewport!.height));
setState(() => _selectionRect = rect);
widget.controller.setSelection(
widget.controller.hitTestRect(viewport: _viewport!, rectangle: rect),
);
}
@override
void initState() {
super.initState();
_edgeTicker = createTicker(_edgeTick);
WidgetsBinding.instance.addObserver(this);
widget.controller.addListener(_controllerChanged);
}
@override
void didUpdateWidget(TimelineInteractionRegion oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller ||
oldWidget.ruler != widget.ruler ||
oldWidget.keyframes != widget.keyframes) {
oldWidget.controller.removeListener(_controllerChanged);
final before = _marquee;
_marquee = null;
_selectionRect = null;
if (before != null &&
identical(before.version, oldWidget.controller.version)) {
oldWidget.controller.setSelection(before.before);
}
oldWidget.controller.cancelDrag();
_reset();
widget.controller.addListener(_controllerChanged);
}
_syncEdgeScroll();
}
int? _trimFrame;
Offset? _pendingTrimPosition;
void _cancelTrimFrame() {
if (_trimFrame case final id?) {
SchedulerBinding.instance.cancelFrameCallbackWithId(id);
}
_trimFrame = null;
_pendingTrimPosition = null;
}
void _queueTrim(Offset position) {
_pendingTrimPosition = position;
_trimFrame ??= SchedulerBinding.instance.scheduleFrameCallback((_) {
_trimFrame = null;
final latest = _pendingTrimPosition;
_pendingTrimPosition = null;
if (!mounted ||
_mode != _PointerMode.clip ||
!widget.controller.isTrimming ||
latest == null) {
return;
}
widget.controller.updateDrag(viewport: _viewport!, position: latest);
});
}
void _reset() {
if (_mode == _PointerMode.scrub) widget.controller.endScrubbing();
_cancelTrimFrame();
_stopEdgeScroll();
_mode = _PointerMode.idle;
_down = _position = _focal = null;
_pointers.clear();
_middle = _multi = _hand = false;
_pinching = false;
_scale = 1;
}
void _cancel() {
_endMarquee(restore: true);
widget.controller.cancelDrag();
_reset();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state != AppLifecycleState.resumed) _cancel();
}
@override
void dispose() {
if (_mode == _PointerMode.scrub) widget.controller.endScrubbing();
_cancelTrimFrame();
WidgetsBinding.instance.removeObserver(this);
widget.controller.removeListener(_controllerChanged);
_edgeTicker.dispose();
_endMarquee(restore: true, repaint: false);
widget.controller.cancelDrag();
_focus.dispose();
super.dispose();
}
void _seek(Offset point) => widget.controller.seekAt(
screenX: point.dx.clamp(0.0, _viewport!.width),
viewport: _viewport!,
);
void _navigate(
Offset from,
Offset to, {
double scale = 1,
bool anchorToPlayhead = false,
}) {
widget.controller.navigate(
from: from,
to: widget.ruler ? Offset(to.dx, from.dy) : to,
scale: scale,
anchorToPlayhead: anchorToPlayhead,
viewport: _viewport!,
);
widget.controller.setHoveredIdentity(null);
}
void _downEvent(PointerDownEvent event) {
if (event.buttons == kSecondaryMouseButton &&
!widget.ruler &&
!widget.controller.isDragging) {
final hit = widget.controller.hitTest(
viewport: _viewport!,
position: event.localPosition,
);
if (hit == null) {
widget.controller.clearSelection();
} else if (!widget.controller.selectedIdentities.contains(hit.identity)) {
widget.controller.setSelection([hit.identity]);
}
return;
}
if (event.buttons != kPrimaryButton &&
event.buttons != kMiddleMouseButton) {
return;
}
_pointers.add(event.pointer);
_focus.requestFocus();
if (_pointers.length > 1) {
_endMarquee(restore: true);
widget.controller.cancelDrag();
_mode = _PointerMode.navigate;
_multi = true;
_focal = null;
return;
}
_down = _position = event.localPosition;
_middle = event.buttons == kMiddleMouseButton;
final space = HardwareKeyboard.instance.logicalKeysPressed.contains(
LogicalKeyboardKey.space,
);
_hand = _middle || space;
if (_hand) {
_mode = _PointerMode.navigate;
} else if (widget.ruler) {
_mode = _PointerMode.scrub;
} else {
final hit = widget.controller.hitTest(
viewport: _viewport!,
position: event.localPosition,
);
_mode = hit != null
? _PointerMode.clip
: event.kind == PointerDeviceKind.touch
? _PointerMode.navigate
: _PointerMode.marquee;
}
}
void _scaleStart(ScaleStartDetails details) {
if (_middle) return;
_scale = 1;
_pinching = false;
// Native trackpad gestures have no ordinary PointerDown and count as >=2.
if (details.pointerCount >= 2) {
_endMarquee(restore: true);
widget.controller.cancelDrag();
_multi = true;
_mode = _PointerMode.navigate;
}
_focal = details.localFocalPoint;
if (_mode == _PointerMode.marquee && _down != null) {
final c = widget.controller;
_marquee = (
before: c.selectedIdentities.toSet(),
version: c.version,
camera: c.camera,
geometry: c.geometry,
);
c.setHoveredIdentity(null);
_updateMarquee(details.localFocalPoint);
}
if (_mode == _PointerMode.clip && _down != null) {
if (!widget.controller.beginDrag(
viewport: _viewport!,
position: _down!,
trimHitExtent: TimelineThemeData.of(context).trimHitExtent,
keyframes: widget.keyframes,
keyframeHeaderHeight: TimelineThemeData.of(context).clipHeaderHeight,
)) {
_mode = _PointerMode.ignored;
}
}
if (_mode == _PointerMode.navigate && !_multi && _down != null) {
_navigate(_down!, details.localFocalPoint);
} else if (_mode == _PointerMode.clip) {
widget.controller.updateDrag(
viewport: _viewport!,
position: details.localFocalPoint,
);
} else if (_mode == _PointerMode.scrub) {
widget.controller.beginScrubbing();
_seek(details.localFocalPoint);
}
_position = details.localFocalPoint;
_syncEdgeScroll();
}
void _scaleUpdate(ScaleUpdateDetails details) {
if (_middle || _mode == _PointerMode.idle) return;
final focal = details.localFocalPoint;
if (_mode == _PointerMode.navigate) {
// Windows DirectManipulation reports translation alongside pinch scale.
// Once scaling starts, retain zoom intent until the fingers lift, even
// when later packets keep the same scale but move their focal point.
_pinching |= (details.scale - 1).abs() > 0.000001;
_navigate(
_pinching ? focal : _focal ?? focal,
focal,
scale: details.scale / _scale,
anchorToPlayhead: true,
);
} else if (_mode == _PointerMode.clip) {
// Ripple trim prepares a canonical layout. Multiple pointer packets in
// one display interval must not each rebuild that same private preview.
if (widget.controller.isTrimming) {
_queueTrim(focal);
} else {
widget.controller.updateDrag(viewport: _viewport!, position: focal);
}
} else if (_mode == _PointerMode.scrub) {
_seek(focal);
} else if (_mode == _PointerMode.marquee) {
_updateMarquee(focal);
}
_scale = details.scale;
_focal = _position = focal;
_syncEdgeScroll();
}
void _scaleEnd(ScaleEndDetails details) {
if (_middle || details.pointerCount > 0) return;
_stopEdgeScroll();
if (_mode == _PointerMode.marquee) {
if (_position != null) _updateMarquee(_position!);
_endMarquee(restore: false);
}
if (_mode == _PointerMode.clip && _position != null) {
widget.controller.finishDrag(viewport: _viewport!, position: _position!);
}
_reset();
}
void _scroll(PointerSignalEvent event) {
if (event is! PointerScrollEvent) return;
final keys = HardwareKeyboard.instance;
final zoom = keys.isControlPressed || keys.isMetaPressed;
final horizontal = keys.isShiftPressed;
GestureBinding.instance.pointerSignalResolver.register(event, (_) {
if (zoom) {
final delta = event.scrollDelta.dy == 0
? event.scrollDelta.dx
: event.scrollDelta.dy;
_navigate(
event.localPosition,
event.localPosition,
scale: math.exp((-delta * 0.002).clamp(-20.0, 20.0)),
anchorToPlayhead: true,
);
} else {
final delta = horizontal
? Offset(event.scrollDelta.dx + event.scrollDelta.dy, 0)
: event.scrollDelta;
widget.controller.panBy(
horizontalPixels: delta.dx,
verticalPixels: widget.ruler ? 0 : delta.dy,
);
widget.controller.setHoveredIdentity(null);
}
});
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, constraints) {
final previous = _viewport;
if (previous != null &&
_mode == _PointerMode.clip &&
(previous.width != constraints.maxWidth ||
previous.height != constraints.maxHeight)) {
// End the old-coordinate gesture before using resized viewport bounds.
// Publication/notifications must not run during build.
_stopEdgeScroll();
final owner = widget.controller;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && identical(owner, widget.controller)) _cancel();
});
}
_viewport = TimelineViewportRect(
width: constraints.maxWidth,
height: constraints.maxHeight,
);
return Focus(
focusNode: _focus,
onFocusChange: (focused) {
if (!focused) _cancel();
},
onKeyEvent: (_, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
_cancel();
return KeyEventResult.handled;
}
if (event is KeyDownEvent &&
_mode == _PointerMode.idle &&
_pointers.isEmpty &&
!widget.controller.isDragging) {
final keys = HardwareKeyboard.instance;
final command = keys.isMetaPressed || keys.isControlPressed;
final key = event.logicalKey;
if (command &&
!keys.isAltPressed &&
!keys.isShiftPressed &&
key == LogicalKeyboardKey.keyB) {
widget.controller.cutSelectionAtPlayhead();
return KeyEventResult.handled;
}
if (!command &&
!keys.isAltPressed &&
!keys.isShiftPressed &&
(key == LogicalKeyboardKey.delete ||
key == LogicalKeyboardKey.backspace)) {
widget.controller.deleteSelection();
return KeyEventResult.handled;
}
if (command &&
!keys.isAltPressed &&
key == LogicalKeyboardKey.keyZ) {
keys.isShiftPressed
? widget.controller.redo()
: widget.controller.undo();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
},
child: MouseRegion(
cursor: widget.controller.isDraggingKeyframe
? widget.controller.dragRejection == null
? SystemMouseCursors.resizeLeftRight
: SystemMouseCursors.forbidden
: _cursor,
onHover: (event) {
if (!widget.ruler && !widget.controller.isDragging) {
final hit = widget.controller.hitTest(
viewport: _viewport!,
position: event.localPosition,
);
widget.controller.setHoveredIdentity(hit?.identity);
final edge = widget.controller.trimEdgeAt(
hit: hit,
position: event.localPosition,
extent: TimelineThemeData.of(context).trimHitExtent,
);
final onKey =
widget.keyframes &&
widget.controller.hitTestKeyframe(
viewport: _viewport!,
position: event.localPosition,
headerHeight: TimelineThemeData.of(
context,
).clipHeaderHeight,
) !=
null;
final cursor = edge == null && !onKey
? SystemMouseCursors.basic
: SystemMouseCursors.resizeLeftRight;
if (_cursor != cursor) setState(() => _cursor = cursor);
}
},
onExit: (_) {
widget.controller.setHoveredIdentity(null);
if (_cursor != SystemMouseCursors.basic) {
setState(() => _cursor = SystemMouseCursors.basic);
}
},
child: Listener(
onPointerDown: _downEvent,
onPointerMove: (event) {
if (_middle && _pointers.contains(event.pointer)) {
_navigate(_position!, event.localPosition);
_position = event.localPosition;
}
},
onPointerUp: (event) {
if (!_pointers.remove(event.pointer)) return;
_stopEdgeScroll();
if (_middle) {
_reset();
return;
}
if (!_multi) _position = event.localPosition;
},
// Accepted scales may end even on cancellation: clear before publish.
onPointerCancel: (event) {
if (_pointers.contains(event.pointer)) _cancel();
},
onPointerSignal: _scroll,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: (details) {
if (widget.ruler && _mode == _PointerMode.scrub) {
_seek(details.localPosition);
_reset();
return;
}
if (widget.keyframes &&
_mode == _PointerMode.clip &&
!widget.ruler &&
!_hand &&
!_multi &&
widget.controller.selectKeyframeAt(
viewport: _viewport!,
position: details.localPosition,
headerHeight: TimelineThemeData.of(
context,
).clipHeaderHeight,
)) {
_reset();
return;
}
if (!widget.ruler &&
!_hand &&
!_multi &&
(_mode == _PointerMode.clip ||
_mode == _PointerMode.marquee ||
_mode == _PointerMode.navigate)) {
final hit = widget.controller.hitTest(
viewport: _viewport!,
position: details.localPosition,
);
widget.controller.setSelection([
if (hit != null) hit.identity,
]);
if (hit == null) _seek(details.localPosition);
}
_reset();
},
onScaleStart: _scaleStart,
onScaleUpdate: _scaleUpdate,
onScaleEnd: _scaleEnd,
child: Stack(
fit: StackFit.expand,
children: [
widget.child,
if (_selectionRect case final rect?)
Positioned.fromRect(
rect: rect,
child: IgnorePointer(
child: DecoratedBox(
key: const ValueKey('timeline-marquee'),
decoration: BoxDecoration(
color: TimelineThemeData.of(
context,
).selectionOutlineColor.withValues(alpha: 0.12),
border: Border.all(
color: TimelineThemeData.of(
context,
).selectionOutlineColor,
width: TimelineThemeData.of(
context,
).selectionOutlineWidth,
),
),
),
),
),
],
),
),
),
),
);
},
);
}
@@ -0,0 +1,15 @@
import 'package:cutdex_core/timeline/engine.dart';
/// Adapt viewport pixel bounds to the shared clip-local keyframe query.
List<int> timelineKeyframeOffsets(
ElementRecord element, {
required double start,
required double end,
}) {
final curves = <ParameterCurveRecord>[];
element.parameters?.forEach((_, curve) => curves.add(curve));
if (curves.isEmpty || end <= start || element.duration <= 0) return const [];
return TimelineSourceClock(
element,
).keyframeOffsets(curves, start: start.floor(), end: end.ceil());
}
@@ -0,0 +1,479 @@
import 'dart:math' as math;
import 'package:cutdex_core/timeline/layout.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/widgets.dart';
import 'timeline_interaction_region.dart';
import 'timeline_ruler_scale.dart';
import 'timeline_theme.dart';
import 'timeline_view_controller.dart';
enum TimelineRulerStyle { elapsed, timecode }
/// The arrangement of full timecode labels and downward tick marks.
enum TimelineRulerTimecodeLayout {
/// Labels follow their major marks in the same band as subdivisions.
inline,
/// Labels stay centered on major marks, including at the viewport edges.
centered,
/// Faint marks continue behind labels with a halo around each glyph.
overlay,
}
/// Elapsed-time or full project timecode ruler.
/// Shares its horizontal origin/width with TimelineView, independently of y pan.
final class TimelineRuler extends StatelessWidget {
const TimelineRuler({
required this.controller,
this.theme,
this.showPlayhead = true,
this.style = TimelineRulerStyle.elapsed,
this.timecodeLayout = TimelineRulerTimecodeLayout.inline,
super.key,
});
/// Clock intervals keep minute/hour labels and subdivisions readable.
static int majorStepSecondsFor(double desiredSeconds) {
if (!desiredSeconds.isFinite || desiredSeconds < 0) {
throw ArgumentError.value(desiredSeconds, 'desiredSeconds');
}
for (final seconds in const [
1,
2,
5,
10,
15,
30,
60,
120,
300,
600,
900,
1800,
3600,
7200,
10800,
21600,
43200,
86400,
]) {
if (desiredSeconds <= seconds) return seconds;
}
var seconds = 86400;
const maximumSeconds = 0x3fffffffffffffff ~/ TimelineClock.ticksPerSecond;
while (seconds < desiredSeconds && seconds < maximumSeconds) {
seconds = math.min(seconds * 2, maximumSeconds);
}
return seconds;
}
/// Finer detail belongs to the frame ruler, not fractional-second marks.
static int minorDivisionsFor(int majorSeconds) => majorSeconds % 5 == 0
? 5
: majorSeconds % 2 == 0
? 2
: 1;
final bool showPlayhead;
final TimelineRulerStyle style;
/// The visual arrangement used when [style] is [TimelineRulerStyle.timecode].
final TimelineRulerTimecodeLayout timecodeLayout;
final TimelineViewController controller;
final TimelineThemeData? theme;
/// Keeps the label row readable when the host increases text size.
static double heightFor(
TimelineThemeData theme,
TextScaler textScaler, {
TimelineRulerStyle style = TimelineRulerStyle.elapsed,
}) => style == TimelineRulerStyle.timecode
? math.max(
theme.rulerHeight,
textScaler.scale(theme.rulerTextStyle.fontSize ?? 12) *
(theme.rulerTextStyle.height ?? 1.2) +
12,
)
: theme.rulerHeight;
@override
Widget build(BuildContext context) {
final resolved = theme ?? TimelineThemeData.of(context);
return SizedBox(
height: heightFor(
resolved,
MediaQuery.textScalerOf(context),
style: style,
),
child: TimelineInteractionRegion(
controller: controller,
ruler: true,
child: RepaintBoundary(
child: CustomPaint(
painter: _RulerPainter(
controller,
resolved,
MediaQuery.textScalerOf(context),
showPlayhead,
style,
timecodeLayout,
),
child: const SizedBox.expand(),
),
),
),
);
}
}
final class _RulerPainter extends CustomPainter {
_RulerPainter(
this.controller,
this.theme,
this.textScaler,
this.showPlayhead,
this.style,
this.timecodeLayout,
) : super(repaint: showPlayhead ? controller : controller.contentChanges);
final TimelineViewController controller;
final TimelineThemeData theme;
final TextScaler textScaler;
final bool showPlayhead;
final TimelineRulerStyle style;
final TimelineRulerTimecodeLayout timecodeLayout;
@override
void paint(Canvas canvas, Size size) {
canvas.drawRect(
Offset.zero & size,
Paint()..color = theme.rulerBackgroundColor,
);
if (size.width <= 0 || size.height <= 0) return;
if (style == TimelineRulerStyle.timecode) {
_paintTimecode(canvas, size);
return;
}
final camera = controller.camera;
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final label = TextPainter(
textDirection: TextDirection.ltr,
textScaler: textScaler,
text: TextSpan(text: '0000:00:00.000', style: theme.rulerTextStyle),
)..layout();
final spacing = math.max(80.0, label.width + 16);
final desired = spacing / camera.pixelsPerTick;
final frameMode = camera.pixelsPerTick * controller.frameTicks >= 8;
final unit = TimelineClock.ticksPerSecond;
final seconds = TimelineRuler.majorStepSecondsFor(desired / unit);
final step = seconds * unit;
final firstVisibleTick = math.max(0, camera.baseTick);
const maxTick = 0x7fffffffffffffff;
// Keep the preceding label and subdivisions until the viewport clips them.
var tick = firstVisibleTick - firstVisibleTick % step;
final stroke = Paint()
..color = theme.rulerTickColor
..strokeWidth = 1;
canvas.save();
canvas.clipRect(Offset.zero & size);
if (frameMode) {
_paintFrames(canvas, size, viewport, label, stroke);
} else {
// The loop is bounded by viewport width, not project length or element count.
final limit = (size.width / spacing).ceil() + 2;
for (var i = 0; i < limit; i++) {
final x = camera.screenXForTick(tick, viewport);
if (x >= size.width) break;
canvas.drawLine(Offset(x, 0), Offset(x, 6), stroke);
label.text = TextSpan(
text: _elapsed(tick),
style: theme.rulerTextStyle,
);
label.layout();
final labelLeft = x + 4;
label.paint(canvas, Offset(labelLeft, 0));
final labelRight = labelLeft + label.width + 4;
// Minor marks are display subdivisions, not an alternative edit grid.
final divisions = TimelineRuler.minorDivisionsFor(seconds);
final minor = step ~/ divisions;
for (var j = 1; j < divisions; j++) {
final minorX = x + minor * j * camera.pixelsPerTick;
if (minorX > labelRight) {
canvas.drawLine(Offset(minorX, 0), Offset(minorX, 3), stroke);
}
}
if (tick > maxTick - step) break;
tick += step;
}
}
label.dispose();
final x = camera.screenXForTick(controller.playheadTick, viewport);
final pointer = Path()
..moveTo(x - 3.5, 0)
..lineTo(x + 3.5, 0)
..lineTo(x + 4.5, 1)
..lineTo(x + 4.5, 7)
..lineTo(x, 12)
..lineTo(x - 4.5, 7)
..lineTo(x - 4.5, 1)
..close();
if (showPlayhead) {
canvas.drawPath(
pointer,
Paint()
..color = theme.playheadColor
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
}
canvas.restore();
}
void _paintTimecode(Canvas canvas, Size size) {
final camera = controller.camera;
final viewport = TimelineViewportRect(
width: size.width,
height: size.height,
);
final timecode = TimelineRulerTimecode(controller.format);
final frame = timecode.frameTicks;
final pixelsPerFrame = camera.pixelsPerTick * frame;
final visibleFirst = math.max(0, camera.baseTick ~/ frame);
final visibleLast = visibleFirst + (size.width / pixelsPerFrame).ceil();
final firstText = timecode.formatFrame(visibleFirst);
final lastText = timecode.formatFrame(visibleLast);
final sample = (firstText.length > lastText.length ? firstText : lastText)
.replaceAll(RegExp(r'\d'), '8');
final label = TextPainter(
textDirection: TextDirection.ltr,
textScaler: textScaler,
text: TextSpan(text: sample, style: theme.rulerTextStyle),
)..layout();
final scale = TimelineRulerScale.resolve(
pixelsPerFrame: pixelsPerFrame,
nominalFramesPerSecond: timecode.framesPerSecond,
labelSpacing: label.width + 24,
);
final tickSpacing = scale.minorFrames * pixelsPerFrame;
final first = visibleFirst - visibleFirst % scale.minorFrames;
final count = (size.width / tickSpacing).ceil() + 2;
final centerY = size.height / 2;
final labels = <({int frame, Rect bounds})>[];
final marks = <({double x, bool major, bool middle})>[];
final stroke = Paint()..strokeWidth = 1;
final color = theme.rulerTickColor;
var labelRight = double.negativeInfinity;
// Resolve label bounds before painting so subdivisions can avoid them
// without erasing a rectangular section of the ruler. Include neighboring
// major marks: their text can remain visible after the mark leaves view.
final firstLabel = visibleFirst - visibleFirst % scale.majorFrames;
final labelCount =
(size.width / (scale.majorFrames * pixelsPerFrame)).ceil() + 2;
final maxFrame = 0x7fffffffffffffff ~/ frame;
for (var i = 0; i < labelCount; i++) {
if (i > (maxFrame - firstLabel) ~/ scale.majorFrames) break;
final index = firstLabel + i * scale.majorFrames;
final x = camera.screenXForTick(index * frame, viewport);
label.text = TextSpan(
text: timecode.formatFrame(index),
style: theme.rulerTextStyle,
);
label.layout();
if (label.height > size.height) continue;
final left = timecodeLayout == TimelineRulerTimecodeLayout.centered
? x - label.width / 2
: x + 7;
if (left + label.width <= 0 ||
left >= size.width ||
left < labelRight + 24) {
continue;
}
final bounds = Rect.fromLTWH(
left,
(size.height - label.height) / 2,
label.width,
label.height,
);
labels.add((frame: index, bounds: bounds));
labelRight = bounds.right;
}
// Subdivision work remains bounded by viewport width, independently of
// how far the preceding label's major mark lies outside the viewport.
for (var i = 0; i < count; i++) {
if (i > (maxFrame - first) ~/ scale.minorFrames) break;
final index = first + i * scale.minorFrames;
final x = camera.screenXForTick(index * frame, viewport);
if (x >= size.width) break;
marks.add((
x: x,
major: index % scale.majorFrames == 0,
middle: scale.middleFrames != null && index % scale.middleFrames! == 0,
));
}
canvas.save();
canvas.clipRect(Offset.zero & size);
var labelCursor = 0;
for (final mark in marks) {
final x = mark.x;
// Both lists are ordered by x, keeping avoidance linear in viewport marks.
while (labelCursor < labels.length &&
labels[labelCursor].bounds.right + 4 < x) {
labelCursor++;
}
if (timecodeLayout != TimelineRulerTimecodeLayout.overlay &&
!mark.major &&
labelCursor < labels.length &&
x > labels[labelCursor].bounds.left - 4 &&
x < labels[labelCursor].bounds.right + 4) {
continue;
}
var top = centerY - (mark.major ? 8 : 6);
var bottom = mark.major ? centerY + 7 : top + (mark.middle ? 10 : 7);
var alpha = mark.major ? 1.0 : (mark.middle ? .85 : .6);
switch (timecodeLayout) {
case TimelineRulerTimecodeLayout.inline:
break;
case TimelineRulerTimecodeLayout.centered:
if (mark.major) {
top = math.max(centerY + 6, centerY + label.height / 2 - 2);
bottom = size.height - 2;
}
case TimelineRulerTimecodeLayout.overlay:
top = centerY - 8;
bottom = mark.major
? size.height - 3
: centerY + (mark.middle ? 5 : 2);
alpha = mark.major ? .75 : .45;
}
stroke.color = color.withValues(alpha: color.a * alpha);
canvas.drawLine(
Offset(x, math.max(0.0, top)),
Offset(x, math.min(size.height, bottom)),
stroke,
);
}
final halo = timecodeLayout == TimelineRulerTimecodeLayout.overlay
? TextPainter(textDirection: TextDirection.ltr, textScaler: textScaler)
: null;
final haloStyle = theme.rulerTextStyle.copyWith(
foreground: Paint()
..color = theme.rulerBackgroundColor
..style = PaintingStyle.stroke
..strokeWidth = 2.5
..strokeJoin = StrokeJoin.round,
);
for (final entry in labels) {
final text = timecode.formatFrame(entry.frame);
if (halo != null) {
halo.text = TextSpan(text: text, style: haloStyle);
halo.layout();
halo.paint(canvas, entry.bounds.topLeft);
}
label.text = TextSpan(text: text, style: theme.rulerTextStyle);
label.layout();
label.paint(canvas, entry.bounds.topLeft);
}
halo?.dispose();
label.dispose();
if (showPlayhead) {
final x = camera.screenXForTick(controller.playheadTick, viewport);
canvas.drawPath(
Path()
..moveTo(x - 3.5, 0)
..lineTo(x + 3.5, 0)
..lineTo(x + 4.5, 1)
..lineTo(x + 4.5, 7)
..lineTo(x, 12)
..lineTo(x - 4.5, 7)
..lineTo(x - 4.5, 1)
..close(),
Paint()
..color = theme.playheadColor
..style = PaintingStyle.stroke
..strokeWidth = 1,
);
}
canvas.restore();
}
void _paintFrames(
Canvas canvas,
Size size,
TimelineViewportRect viewport,
TextPainter label,
Paint stroke,
) {
final camera = controller.camera;
final frame = controller.frameTicks;
const second = TimelineClock.ticksPerSecond;
final pixelsPerFrame = camera.pixelsPerTick * frame;
final labelEvery = math.max(5, (64 / pixelsPerFrame / 5).ceil() * 5);
final visibleFirst = math.max(0, camera.baseTick ~/ frame);
final visibleSecond = visibleFirst * frame ~/ second;
final secondStart = (visibleSecond * second + frame - 1) ~/ frame;
final first =
secondStart + (visibleFirst - secondStart) ~/ labelEvery * labelEvery;
final count =
(size.width / pixelsPerFrame).ceil() + visibleFirst - first + 2;
var labelRight = double.negativeInfinity;
for (var i = 0; i < count; i++) {
final index = first + i;
final tick = index * frame;
if (tick > 0x7fffffffffffffff) break;
final x = camera.screenXForTick(tick, viewport);
if (x >= size.width) break;
final elapsedSecond = tick ~/ second;
// Non-integer frame rates keep the real frame grid. The first frame
// at or after each second carries that second's label.
final firstInSecond = (elapsedSecond * second + frame - 1) ~/ frame;
final offset = index - firstInSecond;
final wholeSecond = offset == 0;
canvas.drawLine(
Offset(x, wholeSecond ? 0 : size.height - 3),
Offset(x, wholeSecond ? 6 : size.height),
stroke,
);
if (!wholeSecond && offset % labelEvery != 0) continue;
label.text = TextSpan(
text: wholeSecond ? _elapsed(elapsedSecond * second) : '${offset}f',
style: theme.rulerTextStyle,
);
label.layout();
final nextSecondFrame =
((elapsedSecond + 1) * second + frame - 1) ~/ frame;
final nextSecondX = camera.screenXForTick(
nextSecondFrame * frame,
viewport,
);
if (!wholeSecond &&
(x + 4 < labelRight || x + label.width + 8 > nextSecondX)) {
continue;
}
label.paint(canvas, Offset(x + 4, 0));
labelRight = x + label.width + 8;
}
}
@override
bool shouldRepaint(_RulerPainter old) =>
old.controller != controller ||
old.showPlayhead != showPlayhead ||
old.style != style ||
old.timecodeLayout != timecodeLayout ||
old.theme != theme ||
old.textScaler != textScaler;
}
String _elapsed(int tick) {
assert(tick >= 0);
final seconds = tick ~/ TimelineClock.ticksPerSecond;
final hours = (seconds ~/ 3600).toString().padLeft(2, '0');
final minutes = (seconds ~/ 60 % 60).toString().padLeft(2, '0');
final remainder = (seconds % 60).toString().padLeft(2, '0');
return '$hours:$minutes:$remainder';
}
@@ -0,0 +1,164 @@
import 'dart:math' as math;
import 'package:cutdex_core/timeline/model.dart';
/// Display-only intervals on the project frame grid, anchored at frame zero.
final class TimelineRulerScale {
const TimelineRulerScale._({
required this.majorFrames,
required this.minorFrames,
required this.middleFrames,
});
factory TimelineRulerScale.resolve({
required double pixelsPerFrame,
required int nominalFramesPerSecond,
required double labelSpacing,
}) {
if (!pixelsPerFrame.isFinite || pixelsPerFrame <= 0) {
throw ArgumentError.value(pixelsPerFrame, 'pixelsPerFrame');
}
if (nominalFramesPerSecond < 1) {
throw ArgumentError.value(
nominalFramesPerSecond,
'nominalFramesPerSecond',
);
}
if (!labelSpacing.isFinite || labelSpacing <= 0) {
throw ArgumentError.value(labelSpacing, 'labelSpacing');
}
final fps = nominalFramesPerSecond;
final major = _stepFrames(
math.max(120, labelSpacing) / pixelsPerFrame,
fps,
);
// Reveal every frame at 8 px; below that, aim for roughly 12 px per mark.
final minor = pixelsPerFrame >= 8 - 1e-9
? 1
: _stepFrames(12 / pixelsPerFrame, fps, divides: major);
int? middle;
for (var multiplier = 2; multiplier < major ~/ minor; multiplier++) {
final candidate = minor * multiplier;
if (major % candidate == 0 && candidate * pixelsPerFrame >= 24) {
middle = candidate;
break;
}
}
return TimelineRulerScale._(
majorFrames: major,
minorFrames: minor,
middleFrames: middle,
);
}
final int majorFrames;
final int minorFrames;
final int? middleFrames;
static int _stepFrames(double desired, int fps, {int? divides}) {
if (desired <= fps + 1e-9) {
for (var frames = 1; frames <= fps; frames++) {
// Rates divisible by five use familiar 1/2/5/10/15-frame groups.
if (fps % 5 == 0 && frames > 2 && frames % 5 != 0) continue;
if (frames + 1e-9 >= desired &&
fps % frames == 0 &&
(divides == null || divides % frames == 0)) {
return frames;
}
}
}
final desiredSeconds = desired / fps;
for (final seconds in clockStepsSeconds) {
final frames = seconds * fps;
if (seconds + 1e-9 >= desiredSeconds &&
(divides == null || divides % frames == 0)) {
return frames;
}
}
if (divides != null) return divides;
var seconds = clockStepsSeconds.last;
final maximumSeconds = 0x7fffffffffffffff ~/ fps;
while (seconds < desiredSeconds && seconds < maximumSeconds) {
seconds = seconds > maximumSeconds ~/ 2 ? maximumSeconds : seconds * 2;
}
return seconds * fps;
}
static const clockStepsSeconds = [
1,
2,
5,
10,
15,
30,
60,
120,
300,
600,
900,
1800,
3600,
7200,
10800,
21600,
43200,
86400,
];
}
/// Frame addresses for the project's nominal rate and timecode metadata.
/// NTSC drop-frame skips labels, never project frames or tick positions.
final class TimelineRulerTimecode {
TimelineRulerTimecode(TimelineFormat format)
: framesPerSecond = math.max(
1,
(format.frameDuration.denominator / format.frameDuration.numerator)
.round(),
),
frameTicks = format.frameGrid.quantumTicks,
startFrame =
TimelineClock.standard.toTicks(format.startTime) ~/
format.frameGrid.quantumTicks,
_format = format;
final int framesPerSecond;
final int frameTicks;
final int startFrame;
final TimelineFormat _format;
bool get dropFrame =>
_format.timecodeFormat == TimelineTimecodeFormat.dropFrame &&
framesPerSecond % 30 == 0 &&
_format.frameDuration == RationalTime(1001, framesPerSecond * 1000);
String formatTick(int tick) => formatFrame(tick ~/ frameTicks);
String formatFrame(int localFrame) {
var frames = localFrame + startFrame;
final negative = frames < 0;
frames = frames.abs();
if (dropFrame) {
final skippedPerMinute = framesPerSecond ~/ 30 * 2;
final tenMinutes = framesPerSecond * 600 - skippedPerMinute * 9;
final remaining = frames % tenMinutes;
frames += skippedPerMinute * 9 * (frames ~/ tenMinutes);
if (remaining >= skippedPerMinute) {
frames +=
skippedPerMinute *
((remaining - skippedPerMinute) ~/
(framesPerSecond * 60 - skippedPerMinute));
}
}
final seconds = frames ~/ framesPerSecond;
final hours = (seconds ~/ 3600).toString().padLeft(2, '0');
final minutes = (seconds ~/ 60 % 60).toString().padLeft(2, '0');
final remainder = (seconds % 60).toString().padLeft(2, '0');
final frameWidth = math.max(2, (framesPerSecond - 1).toString().length);
final frame = (frames % framesPerSecond).toString().padLeft(
frameWidth,
'0',
);
final separator = dropFrame ? ';' : ':';
return '${negative ? '-' : ''}$hours:$minutes:$remainder$separator$frame';
}
}
@@ -0,0 +1,323 @@
import 'dart:async';
import 'dart:math' as math;
import 'package:cutdex_core/timeline/layout.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart' show ScrollbarTheme;
import 'timeline_theme.dart';
import 'timeline_view_controller.dart';
/// Transparent overlay controls that never change the content viewport.
final class TimelineScrollbars extends StatelessWidget {
const TimelineScrollbars({
required this.controller,
required this.viewport,
required this.horizontal,
required this.vertical,
required this.end,
required this.top,
required this.bottom,
required this.thickness,
required this.child,
super.key,
});
final TimelineViewController controller;
final TimelineViewportRect viewport;
final bool horizontal, vertical;
final int end;
final double top, bottom, thickness;
final Widget child;
@override
Widget build(BuildContext context) {
final theme = TimelineThemeData.of(context);
return Stack(
fit: StackFit.expand,
children: [
Positioned(
left: 0,
top: 0,
width: viewport.width,
height: viewport.height,
child: child,
),
if (horizontal)
Positioned(
left: 0,
top: viewport.height - thickness,
width: math.max(0.0, viewport.width - (vertical ? thickness : 0)),
height: thickness,
child: _CameraScrollbar(
key: const ValueKey('timeline-horizontal-scrollbar'),
controller: controller,
axis: Axis.horizontal,
viewport: viewport,
minimum: controller.camera.screenXForTick(0, viewport),
maximum: controller.camera.screenXForTick(end, viewport),
theme: theme,
),
),
if (vertical)
Positioned(
left: viewport.width - thickness,
top: 0,
width: thickness,
height: math.max(
0.0,
viewport.height - (horizontal ? thickness : 0),
),
child: _CameraScrollbar(
key: const ValueKey('timeline-vertical-scrollbar'),
controller: controller,
axis: Axis.vertical,
viewport: viewport,
minimum: top - controller.camera.verticalOffset,
maximum: bottom - controller.camera.verticalOffset,
theme: theme,
),
),
],
);
}
}
final class _CameraScrollbar extends StatefulWidget {
const _CameraScrollbar({
super.key,
required this.controller,
required this.axis,
required this.viewport,
required this.minimum,
required this.maximum,
required this.theme,
});
final TimelineViewController controller;
final Axis axis;
final TimelineViewportRect viewport;
final double minimum, maximum;
final TimelineThemeData theme;
@override
State<_CameraScrollbar> createState() => _CameraScrollbarState();
}
final class _CameraScrollbarState extends State<_CameraScrollbar> {
({
TimelineCamera camera,
LayoutVersion version,
double pointer,
TimelineViewportGeometry geometry,
Object storyline,
double thumb,
double offset,
double travel,
double range,
})?
_drag;
bool _hovered = false;
bool _recentlyScrolled = false;
Timer? _fadeTimer;
late TimelineCamera _lastCamera;
@override
void initState() {
super.initState();
_lastCamera = widget.controller.camera;
}
@override
void dispose() {
_fadeTimer?.cancel();
super.dispose();
}
double _dragOffset = 0;
TimelineCamera? _expectedCamera;
double _coordinate(Offset point) =>
widget.axis == Axis.horizontal ? point.dx : point.dy;
double get _viewportLength => widget.axis == Axis.horizontal
? widget.viewport.width
: widget.viewport.height;
@override
void didUpdateWidget(_CameraScrollbar oldWidget) {
super.didUpdateWidget(oldWidget);
final camera = widget.controller.camera;
if (!identical(camera, _lastCamera)) {
_lastCamera = camera;
_recentlyScrolled = true;
_fadeTimer?.cancel();
_fadeTimer = Timer(const Duration(milliseconds: 900), () {
if (mounted) setState(() => _recentlyScrolled = false);
});
}
if (widget.controller.isDragging) _drag = null;
if (oldWidget.controller != widget.controller ||
oldWidget.axis != widget.axis ||
oldWidget.viewport.width != widget.viewport.width ||
oldWidget.viewport.height != widget.viewport.height ||
(_drag != null &&
(!identical(_drag!.version, widget.controller.version) ||
_drag!.geometry != widget.controller.geometry ||
_drag!.storyline != widget.controller.storyline ||
!identical(_expectedCamera, widget.controller.camera) ||
_drag!.camera.pixelsPerTick !=
widget.controller.camera.pixelsPerTick))) {
_drag = null;
}
}
void _pan(TimelineCamera camera, double delta) => widget.controller.setCamera(
camera.panBy(
horizontalPixels: widget.axis == Axis.horizontal ? delta : 0,
verticalPixels: widget.axis == Axis.vertical ? delta : 0,
),
);
void _updateDrag(Offset position) {
final drag = _drag;
if (drag == null) return;
final c = widget.controller;
if (!identical(drag.version, c.version) ||
!identical(_expectedCamera, c.camera) ||
drag.geometry != c.geometry ||
drag.storyline != c.storyline) {
setState(() => _drag = null);
return;
}
final next = (drag.offset + _coordinate(position) - drag.pointer).clamp(
0.0,
drag.travel,
);
_dragOffset = next;
_pan(drag.camera, (next - drag.offset) / drag.travel * drag.range);
_expectedCamera = c.camera;
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, box) {
final length = widget.axis == Axis.horizontal
? box.maxWidth
: box.maxHeight;
final low = math.min(0.0, widget.minimum);
final high = math.max(0.0, widget.maximum - _viewportLength);
final range = high - low;
final thumb =
_drag?.thumb ??
(length <= 0
? 0.0
: (length * _viewportLength / (_viewportLength + range)).clamp(
math.min(24.0, length),
length,
));
final travel = math.max(0.0, length - thumb);
final offset = _drag != null
? _dragOffset
: (range == 0 ? 0.0 : -low / range * travel);
void page(double direction) {
final delta = (direction * _viewportLength * 0.9).clamp(low, high);
_pan(widget.controller.camera, delta);
}
return IgnorePointer(
ignoring: widget.controller.isDragging,
child: ExcludeSemantics(
excluding: widget.controller.isDragging,
child: MouseRegion(
onEnter: (_) => setState(() => _hovered = true),
onExit: (_) => setState(() => _hovered = false),
child: AnimatedOpacity(
duration: const Duration(milliseconds: 160),
opacity: widget.controller.isDragging
? 0
: _hovered || _recentlyScrolled || _drag != null
? 1
: 0.25,
child: Semantics(
label: widget.axis == Axis.horizontal
? 'Timeline horizontal scroll'
: 'Timeline vertical scroll',
onIncrease: range == 0 ? null : () => page(1),
onDecrease: range == 0 ? null : () => page(-1),
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTapUp: (details) {
setState(() => _drag = null);
final point = _coordinate(details.localPosition);
if (point < offset) page(-1);
if (point > offset + thumb) page(1);
},
// Down records the grab point before gesture slop is consumed.
onPanDown: (details) {
final point = _coordinate(details.localPosition);
if (range == 0 ||
travel == 0 ||
point < offset ||
point > offset + thumb) {
return;
}
widget.controller.cancelDrag();
_dragOffset = offset;
_expectedCamera = widget.controller.camera;
setState(
() => _drag = (
camera: widget.controller.camera,
version: widget.controller.version,
geometry: widget.controller.geometry,
storyline: widget.controller.storyline,
thumb: thumb,
pointer: point,
offset: offset,
travel: travel,
range: range,
),
);
},
onPanStart: (details) => _updateDrag(details.localPosition),
onPanUpdate: (details) => _updateDrag(details.localPosition),
onPanEnd: (_) => setState(() => _drag = null),
onPanCancel: () => setState(() => _drag = null),
child: Stack(
children: [
Positioned(
left: widget.axis == Axis.horizontal
? offset
: math.max(0.0, box.maxWidth - 8),
top: widget.axis == Axis.vertical
? offset
: math.max(0.0, box.maxHeight - 8),
width: widget.axis == Axis.horizontal
? thumb
: math.min(6.0, box.maxWidth),
height: widget.axis == Axis.vertical
? thumb
: math.min(6.0, box.maxHeight),
child: DecoratedBox(
key: ValueKey('timeline-${widget.axis.name}-thumb'),
decoration: BoxDecoration(
color:
ScrollbarTheme.of(context).thumbColor?.resolve({
if (_hovered) WidgetState.hovered,
if (_drag != null) WidgetState.dragged,
}) ??
widget.theme.scrollbarThumbColor,
borderRadius: BorderRadius.circular(
widget.theme.scrollbarThickness / 2,
),
),
),
),
],
),
),
),
),
),
),
);
},
);
}
@@ -0,0 +1,501 @@
import 'dart:ui' as ui;
import 'package:flutter/material.dart';
/// Visual tokens shared by every timeline painter and viewport overlay.
///
/// Install this extension in [ThemeData.extensions] for an application-wide
/// theme. Individual timeline surfaces may override it without introducing a
/// second styling model.
@immutable
final class TimelineThemeData extends ThemeExtension<TimelineThemeData> {
const TimelineThemeData({
required this.backgroundColor,
this.primaryLaneBackgroundColor = const Color(0xff202328),
required this.visualClipColor,
required this.audioClipColor,
required this.audioAccentColor,
required this.gapColor,
required this.gapBorderColor,
required this.containerAccentColor,
required this.transitionColor,
required this.connectionLineColor,
required this.clipBorderColor,
required this.selectionOutlineColor,
this.keyframeColor = const Color(0xffa3a3a3),
this.keyframeBorderColor = const Color(0xff171717),
this.keyframeInvalidColor = const Color(0xffff6467),
required this.disabledOverlayColor,
required this.clipCornerRadius,
required this.clipBorderWidth,
required this.selectionOutlineWidth,
required this.audioAccentWidth,
required this.containerAccentWidth,
required this.transitionStrokeWidth,
required this.connectionLineWidth,
this.dragGhostOpacity = 1,
this.outsideSourceRangeOverlayColor = const Color(0x88000000),
this.trimHandleWidth = 2,
this.trimHitExtent = 6,
this.clipHeaderHeight = 18,
this.clipHeaderPadding = 2,
this.clipNameTextStyle = const TextStyle(
color: Color(0xffffffff),
fontSize: 11,
),
this.rulerHeight = 32,
this.rulerBackgroundColor = const Color(0xff202328),
this.rulerTickColor = const Color(0xff7d8694),
this.rulerTextStyle = const TextStyle(
color: Color(0xffc8cdd5),
fontSize: 11,
),
this.playheadColor = const Color(0xffef6558),
this.playheadWidth = 1,
this.scrollbarThickness = 12,
this.scrollbarTrackColor = const Color(0xff202328),
this.scrollbarThumbColor = const Color(0xff707986),
}) : assert(trimHandleWidth >= 0 && trimHandleWidth < double.infinity),
assert(trimHitExtent >= 0 && trimHitExtent < double.infinity),
assert(clipHeaderHeight > 0 && clipHeaderHeight < double.infinity),
assert(clipHeaderPadding >= 0 && clipHeaderPadding < double.infinity),
assert(clipCornerRadius >= 0),
assert(clipBorderWidth >= 0),
assert(selectionOutlineWidth >= 0),
assert(audioAccentWidth >= 0),
assert(containerAccentWidth >= 0),
assert(transitionStrokeWidth >= 0),
assert(connectionLineWidth >= 0),
assert(dragGhostOpacity >= 0 && dragGhostOpacity <= 1),
assert(rulerHeight > 0),
assert(playheadWidth >= 0),
assert(scrollbarThickness >= 4 && scrollbarThickness < double.infinity);
const TimelineThemeData.dark()
: backgroundColor = const Color(0xff15171a),
primaryLaneBackgroundColor = const Color(0xff202328),
visualClipColor = const Color(0xff4e82d8),
audioClipColor = const Color(0xff3f9068),
audioAccentColor = const Color(0xff8dd7ae),
gapColor = const Color(0xff404040),
gapBorderColor = const Color(0xff656b75),
containerAccentColor = const Color(0xffb9d1fa),
transitionColor = const Color(0xccd0a84b),
connectionLineColor = const Color(0xff202b3f),
clipBorderColor = const Color(0x66000000),
selectionOutlineColor = const Color(0xffffffff),
keyframeColor = const Color(0xffa3a3a3),
keyframeBorderColor = const Color(0xff171717),
keyframeInvalidColor = const Color(0xffff6467),
disabledOverlayColor = const Color(0x66000000),
outsideSourceRangeOverlayColor = const Color(0x88000000),
clipCornerRadius = 3,
clipBorderWidth = 1,
selectionOutlineWidth = 2,
audioAccentWidth = 1,
containerAccentWidth = 2,
transitionStrokeWidth = 1,
connectionLineWidth = 3,
dragGhostOpacity = 1,
trimHandleWidth = 2,
trimHitExtent = 6,
clipHeaderHeight = 18,
clipHeaderPadding = 2,
clipNameTextStyle = const TextStyle(
color: Color(0xffffffff),
fontSize: 11,
),
rulerHeight = 32,
rulerBackgroundColor = const Color(0xff202328),
rulerTickColor = const Color(0xff7d8694),
rulerTextStyle = const TextStyle(color: Color(0xffc8cdd5), fontSize: 11),
playheadColor = const Color(0xffef6558),
playheadWidth = 1,
scrollbarThickness = 12,
scrollbarTrackColor = const Color(0xff202328),
scrollbarThumbColor = const Color(0xff707986);
final Color backgroundColor;
final Color primaryLaneBackgroundColor;
final Color visualClipColor;
final Color audioClipColor;
final Color audioAccentColor;
final Color gapColor;
final Color gapBorderColor;
final Color containerAccentColor;
final Color transitionColor;
final Color connectionLineColor;
final Color clipBorderColor;
final Color selectionOutlineColor;
final Color keyframeColor;
final Color keyframeBorderColor;
final Color keyframeInvalidColor;
final Color disabledOverlayColor;
/// Dims content outside the opened compound's declared source envelope.
/// Selection and hit testing remain unchanged.
final Color outsideSourceRangeOverlayColor;
final double clipCornerRadius;
final double clipBorderWidth;
final double selectionOutlineWidth;
final double audioAccentWidth;
final double containerAccentWidth;
final double transitionStrokeWidth;
final double connectionLineWidth;
final double dragGhostOpacity;
/// Stroke width of the open rounded edge shown during a trim gesture.
final double trimHandleWidth;
/// Inner hit band in logical pixels; zero disables edge gestures.
final double trimHitExtent;
/// Header lives inside the existing clip rectangle; it never changes lanes.
final double clipHeaderHeight;
final double clipHeaderPadding;
final TextStyle clipNameTextStyle;
final double rulerHeight;
final Color rulerBackgroundColor;
final Color rulerTickColor;
final TextStyle rulerTextStyle;
final Color playheadColor;
final double playheadWidth;
final double scrollbarThickness;
final Color scrollbarTrackColor;
final Color scrollbarThumbColor;
/// Resolves the nearest Flutter theme, falling back to the built-in dark
/// timeline palette when the host application does not install one.
static TimelineThemeData of(BuildContext context) =>
Theme.of(context).extension<TimelineThemeData>() ??
const TimelineThemeData.dark();
@override
TimelineThemeData copyWith({
Color? backgroundColor,
Color? primaryLaneBackgroundColor,
Color? visualClipColor,
Color? audioClipColor,
Color? audioAccentColor,
Color? gapColor,
Color? gapBorderColor,
Color? containerAccentColor,
Color? transitionColor,
Color? connectionLineColor,
Color? clipBorderColor,
Color? selectionOutlineColor,
Color? keyframeColor,
Color? keyframeBorderColor,
Color? keyframeInvalidColor,
Color? disabledOverlayColor,
Color? outsideSourceRangeOverlayColor,
double? clipCornerRadius,
double? clipBorderWidth,
double? selectionOutlineWidth,
double? audioAccentWidth,
double? containerAccentWidth,
double? transitionStrokeWidth,
double? connectionLineWidth,
double? dragGhostOpacity,
double? trimHandleWidth,
double? trimHitExtent,
double? clipHeaderHeight,
double? clipHeaderPadding,
TextStyle? clipNameTextStyle,
double? rulerHeight,
Color? rulerBackgroundColor,
Color? rulerTickColor,
TextStyle? rulerTextStyle,
Color? playheadColor,
double? playheadWidth,
double? scrollbarThickness,
Color? scrollbarTrackColor,
Color? scrollbarThumbColor,
}) => TimelineThemeData(
backgroundColor: backgroundColor ?? this.backgroundColor,
primaryLaneBackgroundColor:
primaryLaneBackgroundColor ?? this.primaryLaneBackgroundColor,
visualClipColor: visualClipColor ?? this.visualClipColor,
audioClipColor: audioClipColor ?? this.audioClipColor,
audioAccentColor: audioAccentColor ?? this.audioAccentColor,
gapColor: gapColor ?? this.gapColor,
gapBorderColor: gapBorderColor ?? this.gapBorderColor,
containerAccentColor: containerAccentColor ?? this.containerAccentColor,
transitionColor: transitionColor ?? this.transitionColor,
connectionLineColor: connectionLineColor ?? this.connectionLineColor,
clipBorderColor: clipBorderColor ?? this.clipBorderColor,
selectionOutlineColor: selectionOutlineColor ?? this.selectionOutlineColor,
keyframeColor: keyframeColor ?? this.keyframeColor,
keyframeBorderColor: keyframeBorderColor ?? this.keyframeBorderColor,
keyframeInvalidColor: keyframeInvalidColor ?? this.keyframeInvalidColor,
disabledOverlayColor: disabledOverlayColor ?? this.disabledOverlayColor,
outsideSourceRangeOverlayColor:
outsideSourceRangeOverlayColor ?? this.outsideSourceRangeOverlayColor,
clipCornerRadius: clipCornerRadius ?? this.clipCornerRadius,
clipBorderWidth: clipBorderWidth ?? this.clipBorderWidth,
selectionOutlineWidth: selectionOutlineWidth ?? this.selectionOutlineWidth,
audioAccentWidth: audioAccentWidth ?? this.audioAccentWidth,
containerAccentWidth: containerAccentWidth ?? this.containerAccentWidth,
transitionStrokeWidth: transitionStrokeWidth ?? this.transitionStrokeWidth,
connectionLineWidth: connectionLineWidth ?? this.connectionLineWidth,
dragGhostOpacity: dragGhostOpacity ?? this.dragGhostOpacity,
trimHandleWidth: trimHandleWidth ?? this.trimHandleWidth,
trimHitExtent: trimHitExtent ?? this.trimHitExtent,
clipHeaderHeight: clipHeaderHeight ?? this.clipHeaderHeight,
clipHeaderPadding: clipHeaderPadding ?? this.clipHeaderPadding,
clipNameTextStyle: clipNameTextStyle ?? this.clipNameTextStyle,
rulerHeight: rulerHeight ?? this.rulerHeight,
rulerBackgroundColor: rulerBackgroundColor ?? this.rulerBackgroundColor,
rulerTickColor: rulerTickColor ?? this.rulerTickColor,
rulerTextStyle: rulerTextStyle ?? this.rulerTextStyle,
playheadColor: playheadColor ?? this.playheadColor,
playheadWidth: playheadWidth ?? this.playheadWidth,
scrollbarThickness: scrollbarThickness ?? this.scrollbarThickness,
scrollbarTrackColor: scrollbarTrackColor ?? this.scrollbarTrackColor,
scrollbarThumbColor: scrollbarThumbColor ?? this.scrollbarThumbColor,
);
@override
TimelineThemeData lerp(covariant TimelineThemeData? other, double t) {
if (other == null) return this;
if (t == 0) return this;
if (t == 1) return other;
return TimelineThemeData(
clipHeaderHeight: ui.lerpDouble(
clipHeaderHeight,
other.clipHeaderHeight,
t,
)!,
clipHeaderPadding: ui.lerpDouble(
clipHeaderPadding,
other.clipHeaderPadding,
t,
)!,
clipNameTextStyle: TextStyle.lerp(
clipNameTextStyle,
other.clipNameTextStyle,
t,
)!,
outsideSourceRangeOverlayColor: Color.lerp(
outsideSourceRangeOverlayColor,
other.outsideSourceRangeOverlayColor,
t,
)!,
trimHandleWidth: ui.lerpDouble(
trimHandleWidth,
other.trimHandleWidth,
t,
)!,
trimHitExtent: ui.lerpDouble(trimHitExtent, other.trimHitExtent, t)!,
backgroundColor: Color.lerp(backgroundColor, other.backgroundColor, t)!,
primaryLaneBackgroundColor: Color.lerp(
primaryLaneBackgroundColor,
other.primaryLaneBackgroundColor,
t,
)!,
visualClipColor: Color.lerp(visualClipColor, other.visualClipColor, t)!,
audioClipColor: Color.lerp(audioClipColor, other.audioClipColor, t)!,
audioAccentColor: Color.lerp(
audioAccentColor,
other.audioAccentColor,
t,
)!,
gapColor: Color.lerp(gapColor, other.gapColor, t)!,
gapBorderColor: Color.lerp(gapBorderColor, other.gapBorderColor, t)!,
containerAccentColor: Color.lerp(
containerAccentColor,
other.containerAccentColor,
t,
)!,
transitionColor: Color.lerp(transitionColor, other.transitionColor, t)!,
connectionLineColor: Color.lerp(
connectionLineColor,
other.connectionLineColor,
t,
)!,
clipBorderColor: Color.lerp(clipBorderColor, other.clipBorderColor, t)!,
selectionOutlineColor: Color.lerp(
selectionOutlineColor,
other.selectionOutlineColor,
t,
)!,
keyframeColor: Color.lerp(keyframeColor, other.keyframeColor, t)!,
keyframeBorderColor: Color.lerp(
keyframeBorderColor,
other.keyframeBorderColor,
t,
)!,
keyframeInvalidColor: Color.lerp(
keyframeInvalidColor,
other.keyframeInvalidColor,
t,
)!,
disabledOverlayColor: Color.lerp(
disabledOverlayColor,
other.disabledOverlayColor,
t,
)!,
clipCornerRadius: ui.lerpDouble(
clipCornerRadius,
other.clipCornerRadius,
t,
)!,
clipBorderWidth: ui.lerpDouble(
clipBorderWidth,
other.clipBorderWidth,
t,
)!,
selectionOutlineWidth: ui.lerpDouble(
selectionOutlineWidth,
other.selectionOutlineWidth,
t,
)!,
audioAccentWidth: ui.lerpDouble(
audioAccentWidth,
other.audioAccentWidth,
t,
)!,
containerAccentWidth: ui.lerpDouble(
containerAccentWidth,
other.containerAccentWidth,
t,
)!,
transitionStrokeWidth: ui.lerpDouble(
transitionStrokeWidth,
other.transitionStrokeWidth,
t,
)!,
connectionLineWidth: ui.lerpDouble(
connectionLineWidth,
other.connectionLineWidth,
t,
)!,
dragGhostOpacity: ui.lerpDouble(
dragGhostOpacity,
other.dragGhostOpacity,
t,
)!,
rulerHeight: ui.lerpDouble(rulerHeight, other.rulerHeight, t)!,
rulerBackgroundColor: Color.lerp(
rulerBackgroundColor,
other.rulerBackgroundColor,
t,
)!,
rulerTickColor: Color.lerp(rulerTickColor, other.rulerTickColor, t)!,
rulerTextStyle: TextStyle.lerp(rulerTextStyle, other.rulerTextStyle, t)!,
playheadColor: Color.lerp(playheadColor, other.playheadColor, t)!,
playheadWidth: ui.lerpDouble(playheadWidth, other.playheadWidth, t)!,
scrollbarThickness: ui.lerpDouble(
scrollbarThickness,
other.scrollbarThickness,
t,
)!,
scrollbarTrackColor: Color.lerp(
scrollbarTrackColor,
other.scrollbarTrackColor,
t,
)!,
scrollbarThumbColor: Color.lerp(
scrollbarThumbColor,
other.scrollbarThumbColor,
t,
)!,
);
}
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TimelineThemeData &&
backgroundColor == other.backgroundColor &&
primaryLaneBackgroundColor == other.primaryLaneBackgroundColor &&
visualClipColor == other.visualClipColor &&
audioClipColor == other.audioClipColor &&
audioAccentColor == other.audioAccentColor &&
gapColor == other.gapColor &&
gapBorderColor == other.gapBorderColor &&
containerAccentColor == other.containerAccentColor &&
transitionColor == other.transitionColor &&
connectionLineColor == other.connectionLineColor &&
clipBorderColor == other.clipBorderColor &&
selectionOutlineColor == other.selectionOutlineColor &&
keyframeColor == other.keyframeColor &&
keyframeBorderColor == other.keyframeBorderColor &&
keyframeInvalidColor == other.keyframeInvalidColor &&
disabledOverlayColor == other.disabledOverlayColor &&
outsideSourceRangeOverlayColor ==
other.outsideSourceRangeOverlayColor &&
clipCornerRadius == other.clipCornerRadius &&
clipBorderWidth == other.clipBorderWidth &&
selectionOutlineWidth == other.selectionOutlineWidth &&
audioAccentWidth == other.audioAccentWidth &&
containerAccentWidth == other.containerAccentWidth &&
transitionStrokeWidth == other.transitionStrokeWidth &&
connectionLineWidth == other.connectionLineWidth &&
dragGhostOpacity == other.dragGhostOpacity &&
trimHandleWidth == other.trimHandleWidth &&
trimHitExtent == other.trimHitExtent &&
clipHeaderHeight == other.clipHeaderHeight &&
clipHeaderPadding == other.clipHeaderPadding &&
clipNameTextStyle == other.clipNameTextStyle &&
rulerHeight == other.rulerHeight &&
rulerBackgroundColor == other.rulerBackgroundColor &&
rulerTickColor == other.rulerTickColor &&
rulerTextStyle == other.rulerTextStyle &&
playheadColor == other.playheadColor &&
playheadWidth == other.playheadWidth &&
scrollbarThickness == other.scrollbarThickness &&
scrollbarTrackColor == other.scrollbarTrackColor &&
scrollbarThumbColor == other.scrollbarThumbColor;
@override
int get hashCode => Object.hash(
clipHeaderHeight,
clipHeaderPadding,
clipNameTextStyle,
trimHandleWidth,
trimHitExtent,
scrollbarThickness,
scrollbarTrackColor,
scrollbarThumbColor,
Object.hash(
rulerHeight,
rulerBackgroundColor,
rulerTickColor,
rulerTextStyle,
playheadColor,
playheadWidth,
),
Object.hash(
backgroundColor,
primaryLaneBackgroundColor,
visualClipColor,
audioClipColor,
audioAccentColor,
gapColor,
gapBorderColor,
containerAccentColor,
transitionColor,
connectionLineColor,
clipBorderColor,
),
Object.hash(
Object.hash(
selectionOutlineColor,
keyframeColor,
keyframeBorderColor,
keyframeInvalidColor,
),
disabledOverlayColor,
outsideSourceRangeOverlayColor,
clipCornerRadius,
clipBorderWidth,
selectionOutlineWidth,
audioAccentWidth,
containerAccentWidth,
transitionStrokeWidth,
connectionLineWidth,
dragGhostOpacity,
),
);
}
@@ -0,0 +1,34 @@
import 'dart:ui' as ui;
import 'package:cutdex_core/timeline/engine.dart';
import 'package:flutter/foundation.dart';
/// Host-owned decoded frames. Each instance serves one timeline surface.
///
/// Painting only looks up images and declares demand. Implementations schedule
/// asynchronous work after painting, notify when frames are ready, bound memory,
/// and dispose their images. Source ticks come from the authoritative Kernel.
abstract class TimelineThumbnails implements Listenable {
void beginFrame();
/// The source display aspect ratio when known. Returning null keeps the
/// surface on a temporary 16:9 layout until media metadata is available.
double? aspectRatioFor(ElementRecord element);
/// Returns the best decoded frame currently available and declares the
/// resolution needed by this paint. Implementations may return a lower
/// resolution or nearby-time fallback while asynchronously loading the
/// requested one. [sourceSpanTicks] is the approximate source-time coverage
/// of the complete tile and lets the host select a stable sampling pyramid
/// level. Cropping a tile at an edit boundary retains its center and span;
/// samples are bounded by the media asset rather than the edit window.
ui.Image? imageFor(
ElementRecord element,
int sourceTick, {
required int sourceSpanTicks,
required ui.Size logicalSize,
required double devicePixelRatio,
});
void endFrame();
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,533 @@
part of 'timeline_view_controller.dart';
/// Only pointer bookkeeping and dispatch live here. The canonical Layout edit
/// preview supplies both the invisible occupancy and the exact commit result.
final class _TimelineDrag {
_TimelineDrag({
required this.engine,
required this.components,
this.source,
this.primarySource,
required this.movement,
required this.geometry,
required TimelineCamera camera,
required this.viewport,
required this.position,
required this.createConnectionId,
required this.createElementId,
}) : base = engine.current!,
preview = TimelineLayoutPreview(
base: engine.current!,
policy: engine.current!.policy,
components: components,
),
anchor = TimelineViewportDragAnchor.capture(
camera: camera,
viewport: viewport,
screenX: position.dx,
screenY: position.dy,
sourceStart:
source?.start ??
engine.current!.kernelVersion
.query()
.positionOf(primarySource!)
.position,
sourceTop: source == null
? geometry.primaryClipTopFor(primarySource!)
: engine.current!.placementOf(source.id).top,
) {
// UI supplies an explicit chronological sequence; Layout never infers one.
orderedRoots =
List.of(
primarySource != null
? movement.primaryRoots
: selection!.movementRoots,
)..sort((a, b) {
if (primarySource != null) {
final q = base.kernelVersion.query();
return q
.positionOf(a.owner)
.index
.compareTo(q.positionOf(b.owner).index);
}
final byTime = base.scene.bodies[a]!.start.compareTo(
base.scene.bodies[b]!.start,
);
return byTime != 0
? byTime
: base.orderRankRoot[a]!.compareTo(base.orderRankRoot[b]!);
});
}
final TimelineLayoutEngine engine;
final TimelineLayoutComponents components;
final LayoutVersion base;
final LayoutBody? source;
final ElementHandle? primarySource;
LayoutBodyId get sourceId =>
source?.id ?? LayoutBodyId.element(primarySource!);
final TimelineViewportGeometry geometry;
final LayoutMovementPlan movement;
LayoutConnectionSelection? get selection => movement.connectionSelection;
List<LayoutBodyId> get accompanyingRoots => movement.accompanyingRoots;
List<LayoutBodyId> get carried => movement.carried;
int? get minimumTargetStart =>
movement.bounds.minimumTargetStart(anchor.sourceStart);
late final List<LayoutBodyId> orderedRoots;
Map<LayoutBodyId, LayoutBodyId> get rootForBody => movement.rootForBody;
late final List<LayoutBodyId> primaryInsertionRoots =
[...orderedRoots, ...accompanyingRoots]..sort((a, b) {
final q = base.kernelVersion.query();
final time = q
.localContext(a.owner)
.start
.compareTo(q.localContext(b.owner).start);
if (time != 0) return time;
final order = [...orderedRoots, ...accompanyingRoots];
return order.indexOf(a).compareTo(order.indexOf(b));
});
bool get hasAmbiguousPrimaryOrder {
for (var i = 1; i < orderedRoots.length; i++) {
final a = base.scene.bodies[orderedRoots[i - 1]]!;
final b = base.scene.bodies[orderedRoots[i]]!;
if (a.start == b.start && a.partition.stack != b.partition.stack) {
return true;
}
}
return false;
}
final TimelineLayoutPreview preview;
final TimelineViewportDragAnchor anchor;
final ConnectionId Function() createConnectionId;
final ElementId Function() createElementId;
ElementId? _gapId;
ConnectionId? _connectionId;
TimelineViewportRect viewport;
Offset position;
TimelineCamera? _lastCamera;
LayoutConnectionEditPreview? _connection;
LayoutConnectionEditPreview? _tailEdit;
final ghostById = <LayoutBodyId, LayoutGhost>{};
LayoutGhost? get ghost => ghostById[sourceId];
LayoutPreviewMode mode = LayoutPreviewMode.invalid;
String? rejection;
({Object error, StackTrace stack})? failure;
LayoutVersion get displayVersion => _connection?.result.version ?? base;
bool get isPrimaryGap =>
primarySource != null &&
base.kernelVersion.query().element(primarySource!).structure ==
ElementStructure.gap;
late final bool primaryOnly =
primarySource != null &&
(orderedRoots.length > 1 ||
accompanyingRoots.isNotEmpty ||
isPrimaryGap ||
base.kernelVersion.query().hasConnectedClips(primarySource!));
void _clearPrepared() {
if (_connection?.hasTailGap ?? false) _tailEdit = _connection;
_connection?.cancel();
_connection = null;
ghostById.clear();
rejection = null;
failure = null;
mode = LayoutPreviewMode.invalid;
}
void update({
required TimelineCamera camera,
required TimelineViewportRect viewport,
required Offset position,
}) {
final lastCamera = _lastCamera;
if (lastCamera != null &&
_sameCamera(lastCamera, camera) &&
this.position == position &&
this.viewport.left == viewport.left &&
this.viewport.top == viewport.top &&
this.viewport.width == viewport.width &&
this.viewport.height == viewport.height) {
return;
}
_lastCamera = camera;
this.viewport = viewport;
this.position = position;
final previousEdit = _connection ?? _tailEdit;
_clearPrepared();
if (viewport.width <= 0 || viewport.height <= 0) {
preview.invalid();
rejection = 'Outside timeline / 已离开时间线';
return;
}
// Overshoot remains a valid drag on both axes. The interaction region pans
// the camera at the edge; resolving against the clamped pointer lets that
// camera movement keep advancing the target and makes an outside release
// commit the final preview instead of snapping back.
final targetX = position.dx
.clamp(
viewport.left,
math.max(viewport.left, viewport.right - 0.000001),
)
.toDouble();
final targetY = position.dy
.clamp(viewport.top, math.max(viewport.top, viewport.bottom - 0.000001))
.toDouble();
final pointerCoordinates = anchor.resolve(
camera: camera,
viewport: viewport,
screenX: targetX,
screenY: targetY,
timeRounding: TimelineTickRounding.nearest,
verticalRounding: TimelineTickRounding.nearest,
);
final coordinates = anchor.resolve(
camera: camera,
viewport: viewport,
screenX: targetX,
screenY: targetY,
timeRounding: TimelineTickRounding.nearest,
verticalRounding: TimelineTickRounding.nearest,
minimumTargetStart: minimumTargetStart,
);
if (pointerCoordinates.timeDelta == 0 &&
coordinates.depthDelta == 0 &&
_tailEdit == null &&
accompanyingRoots.isEmpty) {
preview.cancel();
return;
}
final targetPolicy = LayoutTargetPolicy(
primaryTop: geometry.primaryTop,
primaryBottom: geometry.primaryTop + geometry.primaryHeight,
);
try {
if (targetPolicy.containsPrimary(coordinates.pointerY)) {
preview.cancel();
if (primarySource == null && hasAmbiguousPrimaryOrder) {
throw const LayoutStructuralError(
'same-time roots on different sides require an explicit serial order',
);
}
final target = const TimelineLayoutTargetResolver()
.resolveOpenedPrimaryDropTarget(
projection: components.semanticProjection,
pointerTick: camera.tickAtScreenX(
targetX,
viewport,
rounding: TimelineTickRounding.nearest,
),
);
_connection =
LayoutPrimaryDropEdit(
target: target,
orderedRoots: orderedRoots.map((id) => id.owner),
accompanyingRoots: accompanyingRoots.map((id) => id.owner),
movementReference: primarySource,
serialInsertionOrder: accompanyingRoots.isEmpty
? null
: primaryInsertionRoots.map((id) => id.owner),
).preview(
kernel: engine.kernel,
engine: engine,
projection: components.semanticProjection,
primaryTop: geometry.primaryTop,
previousEdit: previousEdit,
);
if (_connection == null) {
if (primarySource != null) _primaryGhosts(coordinates);
return;
}
mode = LayoutPreviewMode.primaryInsert;
_primaryGhosts(coordinates);
return;
}
if (primarySource != null && accompanyingRoots.isNotEmpty) {
preview.cancel();
final q = base.kernelVersion.query();
final referenceTick = checkedLayoutAdd(
q.localContext(primarySource!).start,
coordinates.timeDelta,
'mixed reference tick',
);
final target = const TimelineLayoutTargetResolver()
.resolveOpenedPrimaryDropTarget(
projection: components.semanticProjection,
pointerTick: checkedLayoutAdd(
referenceTick,
q.element(primarySource!).duration ~/ 2,
'mixed boundary tick',
),
);
_connection =
LayoutPrimaryDropEdit(
target: target,
orderedRoots: orderedRoots.map((id) => id.owner),
accompanyingRoots: accompanyingRoots.map((id) => id.owner),
movementReference: primarySource,
).preview(
kernel: engine.kernel,
engine: engine,
projection: components.semanticProjection,
primaryTop: geometry.primaryTop,
);
mode = LayoutPreviewMode.connected;
_primaryGhosts(coordinates, originalGeometry: true);
return;
}
if (primarySource != null) {
if (primaryOnly) {
// Keep the original authoritative occupancy until another valid
// Primary preview replaces it. An off-axis release cannot publish.
preview.invalid();
rejection = orderedRoots.length > 1 || accompanyingRoots.isNotEmpty
? 'Primary groups can only be placed on Primary / 主轴多选只能放置在主轴'
: isPrimaryGap
? 'Gaps can only be placed on Primary / gap 只能放置在主轴'
: 'Clips with connected clips can only be placed on Primary / '
'带连接片段的主片段只能放置在主轴';
_primaryGhosts(coordinates);
return;
}
_connection = const LayoutPrimaryDetachEdit().preview(
previousEdit: previousEdit,
kernel: engine.kernel,
engine: engine,
projection: components.semanticProjection,
source: primarySource!,
connectionId: _connectionId ??= createConnectionId(),
start: coordinates.primaryPosition,
side: coordinates.pointerY < targetPolicy.primaryTop
? ConnectionSide.above
: ConnectionSide.below,
requestedTop: coordinates.requestedTop,
createGapId: () => _gapId ??= createElementId(),
);
mode = LayoutPreviewMode.connected;
final prepared = displayVersion;
ghostById[sourceId] = LayoutGhost(
source: sourceId,
body: prepared.scene.bodies[sourceId]!,
top: coordinates.requestedTop,
);
return;
}
final source = this.source!;
final selection = this.selection!;
_connection = const LayoutTailConnectionMove().previewIfNeeded(
originSide: source.partition.stack.side,
kernel: engine.kernel,
engine: engine,
selection: selection,
timeDelta: coordinates.timeDelta,
topDelta: coordinates.depthDelta,
destinationSide: coordinates.pointerY < targetPolicy.primaryTop
? ConnectionSide.above
: ConnectionSide.below,
createGapId: () => _gapId ??= createElementId(),
previousEdit: previousEdit,
);
if (_connection != null) {
preview.cancel();
mode = LayoutPreviewMode.connected;
_primaryGhosts(coordinates, connectedGroup: true);
return;
}
{
final side = coordinates.pointerY < targetPolicy.primaryTop
? ConnectionSide.above
: ConnectionSide.below;
final oldSide = source.partition.stack.side;
final audioAbove =
oldSide == ConnectionSide.below &&
side == ConnectionSide.above &&
source.placementClass == LayoutPlacementClass.audioOnly;
if (side == oldSide || audioAbove) {
final frame = preview.connectedSelection(
selection: selection,
timeDelta: coordinates.timeDelta,
depthDelta: oldSide == ConnectionSide.above
? -coordinates.depthDelta
: coordinates.depthDelta,
reservationOrdinal: 0,
audioOutsideOverlaps: audioAbove,
);
mode = frame.mode;
if (mode != LayoutPreviewMode.connected) {
rejection = 'Placement blocked / 放置位置无效';
return;
}
_connection = const LayoutRigidConnectionMove().previewResolved(
kernel: engine.kernel,
engine: engine,
selection: selection,
target: frame.groupTarget!,
timeDelta: coordinates.timeDelta,
);
for (final ghost in frame.ghosts) {
ghostById[ghost.source] = ghost;
}
} else {
preview.cancel();
final oldPlacement = base.placementOf(source.id);
final oldBoundary =
base.policy.stacks[source.partition.stack]!.primaryBoundary;
final newStack = LayoutStackKey(
scope: source.partition.stack.scope,
side: side,
);
final newBoundary = base.policy.stacks[newStack]!.primaryBoundary;
final oldInner = oldSide == ConnectionSide.above
? oldBoundary - oldPlacement.bottom
: oldPlacement.top - oldBoundary;
final newInner = side == ConnectionSide.above
? newBoundary - coordinates.requestedTop - source.height
: coordinates.requestedTop - newBoundary;
_connection = const LayoutConnectedSideMove().preview(
previousEdit: previousEdit,
kernel: engine.kernel,
engine: engine,
selection: selection,
destinationSide: side,
timeDelta: coordinates.timeDelta,
depthDelta: newInner - oldInner,
);
mode = LayoutPreviewMode.connected;
}
}
if (ghostById.isEmpty) {
final prepared = displayVersion;
final query = prepared.kernelVersion.query();
for (final id in carried) {
final original = base.scene.bodies[id]!;
final start = query.absoluteStart(id.owner);
final top =
coordinates.requestedTop +
prepared.placementOf(id).top -
prepared.placementOf(source.id).top;
ghostById[id] = LayoutGhost(
source: id,
body: original.copyWith(
start: start,
end: checkedLayoutAdd(
start,
original.end - original.start,
'ghost end',
),
),
top: top,
);
}
}
} on LayoutPolicyViolation catch (error, stack) {
_reject(error, stack);
// A rejected placement is not a rejected pointer movement. Keep Primary
// sources visible over their original reservation until a valid target.
if (primarySource != null) {
_primaryGhosts(
coordinates,
originalGeometry: accompanyingRoots.isNotEmpty,
);
}
} on LayoutStructuralError catch (error, stack) {
_reject(error, stack);
} on TimelineModelException catch (error, stack) {
// A pointer may enter a boundary rejected by Kernel, such as transition
// overlap. Keep the gesture alive so it can return to a valid target.
_reject(error, stack);
}
}
void _primaryGhosts(
TimelineViewportDragCoordinates coordinates, {
bool connectedGroup = false,
bool originalGeometry = false,
}) {
final q = (originalGeometry ? base : displayVersion).kernelVersion.query();
final captureMixed =
!originalGeometry &&
accompanyingRoots.isNotEmpty &&
mode == LayoutPreviewMode.primaryInsert;
int oldTop(LayoutBodyId id) =>
primarySource != null && orderedRoots.contains(id)
? geometry.primaryClipTopFor(id.owner)
: base.placementOf(id).top;
final sourceRoot = rootForBody[sourceId]!;
final top =
coordinates.requestedTop - (oldTop(sourceId) - oldTop(sourceRoot));
final shift = connectedGroup
? 0
: checkedLayoutSubtract(
coordinates.targetStart,
q.localContext(sourceId.owner).start,
'pointer ghost shift',
);
for (final id in carried) {
final original = base.scene.bodies[id];
final start = checkedLayoutAdd(
q.localContext(id.owner).start,
shift,
'pointer ghost start',
);
final end = checkedLayoutAdd(
start,
q.element(id.owner).duration,
'pointer ghost end',
);
// Primary is not a connected scene body. This record is display-only;
// it is never supplied to a Layout solver or a Kernel edit.
final body =
(captureMixed && accompanyingRoots.contains(id) ? null : original)
?.copyWith(start: start, end: end) ??
LayoutBody(
id: id,
start: start,
end: end,
height: geometry.primaryClipHeightFor(id.owner),
partition: LayoutPartition(
stack: base.policy.stacks.keys.first,
domain: base.policy.stacks.values.first.domains.first,
),
placementClass:
components.semanticProjection.media
?.forElement(id.owner)
.placementClass ??
LayoutPlacementClass.visualLike,
);
ghostById[id] = LayoutGhost(
source: id,
body: body,
// Connected roots retain their group geometry. Only a serial landing
// aligns independent roots on Primary while retaining child offsets.
top: connectedGroup
? coordinates.requestedTop + oldTop(id) - oldTop(sourceId)
: top +
oldTop(id) -
(captureMixed
? oldTop(rootForBody[id]!)
: primarySource != null
? oldTop(sourceRoot)
: oldTop(rootForBody[id]!)),
);
}
}
void _reject(Object error, StackTrace stack) {
_clearPrepared();
failure = (error: error, stack: stack);
preview.invalid();
rejection = error.toString();
}
LayoutApplyResult? commit() {
final result = _connection?.commit();
_connection = null;
return result;
}
void cancel() {
_clearPrepared();
preview.cancel();
}
}
@@ -0,0 +1,174 @@
part of 'timeline_view_controller.dart';
final class TimelineKeyframeHit {
const TimelineKeyframeHit({
required this.identity,
required this.element,
required this.offset,
required this.start,
});
final Object identity;
final ElementHandle element;
final int offset;
final int start;
}
extension _KeyframeHitGeometry on TimelineViewController {
TimelineKeyframeHit? _keyframeAt({
required TimelineViewportRect viewport,
required Offset position,
required double headerHeight,
}) {
final hit = hitTest(viewport: viewport, position: position);
if (hit == null ||
!canTrim(hit.identity) ||
hit.bounds.height < headerHeight + 14) {
return null;
}
final element = switch (hit.identity) {
ElementHandle id => id,
LayoutBodyId id when id.context == null && id.isSemantic => id.owner,
_ => null,
};
if (element == null) return null;
final layout = clipLayout(
hit.bounds,
owner: element,
nameHeight: headerHeight,
);
if (layout.body.height < headerHeight + 14) return null;
final markerY = layout.bounds.top + layout.keyframeCenter.dy;
final q = _version.kernelVersion.query();
final record = q.element(element);
if (record.duration <= 0 || hit.bounds.width < 2) return null;
final curves = <ParameterCurveRecord>[];
record.parameters?.forEach((_, curve) => curves.add(curve));
final ticksPerPixel = record.duration / hit.bounds.width;
final local = (position.dx - hit.bounds.left) * ticksPerPixel;
final offsets = TimelineSourceClock(record).keyframeOffsets(
curves,
start: (local - 10 * ticksPerPixel).floor(),
end: (local + 10 * ticksPerPixel).ceil() + 1,
);
int? nearest;
var distance = double.infinity;
for (final offset in offsets) {
final x = hit.bounds.left + offset / ticksPerPixel;
final d = (position.dx - x).abs() + (position.dy - markerY).abs();
if (d <= 10 && d < distance) {
nearest = offset;
distance = d;
}
}
return nearest == null
? null
: TimelineKeyframeHit(
identity: hit.identity,
element: element,
offset: nearest,
start: q.localContext(element).start,
);
}
}
final class _TimelineKeyframeDrag {
_TimelineKeyframeDrag({
required this.engine,
required TimelineKeyframeHit hit,
required TimelineCamera camera,
required this.viewport,
required this.position,
}) : base = engine.current!,
move = LayoutKeyframeMove.capture(
projection: engine.currentComponents!.semanticProjection,
element: hit.element,
offset: hit.offset,
),
anchor = TimelineViewportDragAnchor.capture(
camera: camera,
viewport: viewport,
screenX: position.dx,
screenY: position.dy,
sourceStart: hit.start + hit.offset,
sourceTop: 0,
),
displayOffset = hit.offset;
final TimelineLayoutEngine engine;
final LayoutVersion base;
final LayoutKeyframeMove move;
final TimelineViewportDragAnchor anchor;
TimelineViewportRect viewport;
Offset position;
LayoutConnectionEditPreview? _prepared;
int displayOffset;
String? rejection;
({Object error, StackTrace stack})? failure;
TimelineCamera? _lastCamera;
LayoutPreviewMode get mode => rejection == null
? LayoutPreviewMode.connected
: LayoutPreviewMode.invalid;
LayoutVersion get displayVersion => _prepared?.result.version ?? base;
void update({
required TimelineCamera camera,
required TimelineViewportRect viewport,
required Offset position,
required int frameTicks,
}) {
if (_lastCamera case final last?) {
if (_sameCamera(last, camera) &&
this.position == position &&
this.viewport.left == viewport.left &&
this.viewport.top == viewport.top &&
this.viewport.width == viewport.width &&
this.viewport.height == viewport.height) {
return;
}
}
_lastCamera = camera;
this.viewport = viewport;
this.position = position;
cancel();
rejection = null;
failure = null;
displayOffset = move.offset;
try {
final delta = anchor
.resolve(
camera: camera,
viewport: viewport,
screenX: position.dx,
screenY: position.dy,
timeRounding: TimelineTickRounding.nearest,
verticalRounding: TimelineTickRounding.nearest,
)
.timeDelta;
if (delta == 0) return;
final target = move.constrainOffset(
checkedLayoutAdd(move.offset, delta, 'keyframe drag'),
frameTicks: frameTicks,
);
_prepared = move.preview(engine: engine, targetOffset: target);
displayOffset = target;
} on LayoutException catch (error, stack) {
failure = (error: error, stack: stack);
rejection = error.toString();
} on ArgumentError catch (error, stack) {
failure = (error: error, stack: stack);
rejection = error.toString();
}
}
LayoutApplyResult? commit() {
final prepared = _prepared;
if (prepared == null) return null;
final result = prepared.commit();
_prepared = null;
return result;
}
void cancel() {
_prepared?.cancel();
_prepared = null;
}
}
@@ -0,0 +1,138 @@
part of 'timeline_view_controller.dart';
/// Pointer intent only: every frame is a fresh Kernel edit from the same base,
/// resolved and prepared by LayoutIntervalEdit. No mutable DTO or UI history.
final class _TimelineTrim {
_TimelineTrim({
required this.engine,
required this.identity,
required this.edge,
required this.createElementId,
required TimelineCamera camera,
required this.viewport,
required this.position,
}) : base = engine.current!,
projection = engine.currentComponents!.semanticProjection,
anchor = TimelineViewportDragAnchor.capture(
camera: camera,
viewport: viewport,
screenX: position.dx,
screenY: position.dy,
sourceStart: 0,
sourceTop: 0,
);
final TimelineLayoutEngine engine;
final LayoutVersion base;
final TimelineLayoutSceneProjection projection;
final Object identity;
final TimelineTrimEdge edge;
final ElementId Function() createElementId;
final TimelineViewportDragAnchor anchor;
ElementHandle get element => switch (identity) {
ElementHandle h => h,
LayoutBodyId id => id.owner,
_ => throw StateError('trim requires an element'),
};
TimelineViewportRect viewport;
Offset position;
TimelineCamera? _lastCamera;
LayoutConnectionEditPreview? _prepared;
String? rejection;
({Object error, StackTrace stack})? failure;
LayoutPreviewMode get mode => rejection == null
? LayoutPreviewMode.connected
: LayoutPreviewMode.invalid;
LayoutVersion get displayVersion => _prepared?.result.version ?? base;
void update({
required TimelineCamera camera,
required TimelineViewportRect viewport,
required Offset position,
}) {
if (_lastCamera case final last?) {
if (_sameCamera(last, camera) &&
this.position == position &&
this.viewport.left == viewport.left &&
this.viewport.top == viewport.top &&
this.viewport.width == viewport.width &&
this.viewport.height == viewport.height) {
return;
}
}
_lastCamera = camera;
this.viewport = viewport;
this.position = position;
cancel();
rejection = null;
failure = null;
if (viewport.width <= 0 ||
viewport.height <= 0 ||
position.dy < viewport.top ||
position.dy >= viewport.bottom) {
rejection = 'Outside timeline / 已离开时间线';
return;
}
// Keep an outside horizontal pointer pinned to the visible edge. Camera
// edge scrolling then advances that edge through the source without
// discarding the prepared trim on release.
final targetX = position.dx
.clamp(viewport.left, viewport.right - 0.000001)
.toDouble();
try {
final delta = anchor
.resolve(
camera: camera,
viewport: viewport,
screenX: targetX,
screenY: position.dy,
timeRounding: TimelineTickRounding.nearest,
verticalRounding: TimelineTickRounding.nearest,
)
.timeDelta;
if (delta == 0) return;
final record = base.kernelVersion.query().element(element);
final ticks = checkedLayoutAdd(
record.duration,
edge == TimelineTrimEdge.leading ? -delta : delta,
'trim duration',
);
_prepared = const LayoutIntervalEdit().previewTrim(
kernel: engine.kernel,
engine: engine,
projection: projection,
element: element,
edge: edge == TimelineTrimEdge.leading
? LayoutTrimEdge.leading
: LayoutTrimEdge.trailing,
duration: ticks,
createElementId: createElementId,
);
} on TimelineModelException catch (error, stack) {
failure = (error: error, stack: stack);
rejection = error.toString();
} on LayoutPolicyViolation catch (error, stack) {
failure = (error: error, stack: stack);
rejection = error.toString();
} on LayoutStructuralError catch (error, stack) {
failure = (error: error, stack: stack);
rejection = error.toString();
} on ArgumentError catch (error, stack) {
failure = (error: error, stack: stack);
rejection = error.toString();
}
}
LayoutApplyResult? commit() {
final prepared = _prepared;
if (prepared == null) return null;
final result = prepared.commit();
_prepared = null;
return result;
}
void cancel() {
_prepared?.cancel();
_prepared = null;
}
}
@@ -0,0 +1,392 @@
import 'dart:math' as math;
import 'package:cutdex_core/timeline/layout.dart';
import 'package:flutter/scheduler.dart';
import 'package:flutter/widgets.dart';
import 'timeline_edge_scroll.dart';
import 'timeline_ruler.dart';
import 'timeline_scrollbars.dart';
import 'timeline_theme.dart';
import 'timeline_view_controller.dart';
/// Owns effective viewport dimensions, content bounds and camera reconciliation.
final class TimelineViewport extends StatefulWidget {
const TimelineViewport({
required this.controller,
required this.child,
this.showRuler = true,
this.rulerStyle = TimelineRulerStyle.elapsed,
this.rulerTimecodeLayout = TimelineRulerTimecodeLayout.inline,
this.leadingPadding = 0,
super.key,
});
final TimelineViewController controller;
final Widget child;
final bool showRuler;
final TimelineRulerStyle rulerStyle;
/// The label and mark arrangement for the full timecode ruler.
final TimelineRulerTimecodeLayout rulerTimecodeLayout;
/// Layout space outside the time domain, available to the playhead handle.
final double leadingPadding;
@override
State<TimelineViewport> createState() => _TimelineViewportState();
}
final class _TimelineViewportState extends State<TimelineViewport>
with SingleTickerProviderStateMixin {
LayoutVersion? _version;
Object? _storyline;
TimelineViewportGeometry? _geometry;
double _top = 0, _bottom = 0;
bool _hasConnectedContent = false;
TimelineViewController? _pendingReconcile;
double _playheadDragX = 0;
bool _playheadDragging = false;
TimelineViewportRect? _dragViewport;
late final Ticker _edgeTicker = createTicker(_edgeTick);
Duration _lastEdgeElapsed = Duration.zero;
void _stopPlayheadDrag() {
_edgeTicker.stop();
_lastEdgeElapsed = Duration.zero;
_dragViewport = null;
if (_playheadDragging) {
setState(() => _playheadDragging = false);
}
widget.controller.endScrubbing();
}
void _syncEdgeScroll() {
final viewport = _dragViewport;
if (!_playheadDragging ||
viewport == null ||
timelineEdgeVelocity(
_playheadDragX,
viewport.width,
extent: 48,
maxSpeed: 600,
) ==
0) {
_edgeTicker.stop();
_lastEdgeElapsed = Duration.zero;
} else if (!_edgeTicker.isActive) {
_lastEdgeElapsed = Duration.zero;
_edgeTicker.start();
}
}
void _edgeTick(Duration elapsed) {
final viewport = _dragViewport;
if (!_playheadDragging || viewport == null) {
_edgeTicker.stop();
return;
}
final velocity = timelineEdgeVelocity(
_playheadDragX,
viewport.width,
extent: 48,
maxSpeed: 600,
);
final seconds = ((elapsed - _lastEdgeElapsed).inMicroseconds / 1000000)
.clamp(0.0, 0.05);
_lastEdgeElapsed = elapsed;
if (velocity == 0 || seconds == 0) return;
final before = widget.controller.camera;
widget.controller.panBy(horizontalPixels: velocity * seconds);
widget.controller.seekAt(
screenX: _playheadDragX.clamp(0.0, viewport.width),
viewport: viewport,
);
if (widget.controller.camera == before) _edgeTicker.stop();
}
@override
void didUpdateWidget(TimelineViewport oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.controller != widget.controller) {
_edgeTicker.stop();
_lastEdgeElapsed = Duration.zero;
_dragViewport = null;
_playheadDragging = false;
oldWidget.controller.endScrubbing();
}
}
@override
void dispose() {
_edgeTicker.dispose();
widget.controller.endScrubbing();
super.dispose();
}
void _readBounds() {
final c = widget.controller;
final version = c.version;
if (identical(version, _version) &&
c.storyline == _storyline &&
c.geometry == _geometry) {
return;
}
_version = version;
_storyline = c.storyline;
_geometry = c.geometry;
_hasConnectedContent = version.scene.bodies.isNotEmpty;
_top = math.min(c.geometry.primaryTop, c.geometry.transitionTop).toDouble();
_bottom = math
.max(
c.geometry.primaryTop + c.geometry.primaryHeight,
c.geometry.transitionTop + c.geometry.transitionHeight,
)
.toDouble();
for (final entry in version.domainRoot.entries) {
if (entry.key.scope != c.storyline) continue;
final outer = entry.value.outerBoundary.toDouble();
_top = math.min(_top, outer);
_bottom = math.max(_bottom, outer);
}
}
@override
Widget build(BuildContext context) => LayoutBuilder(
builder: (context, box) {
final inset = widget.leadingPadding.clamp(0.0, box.maxWidth);
final contentWidth = box.maxWidth - inset;
final theme = TimelineThemeData.of(context);
final rulerHeight = widget.showRuler
? math.min(
TimelineRuler.heightFor(
theme,
MediaQuery.textScalerOf(context),
style: widget.rulerStyle,
),
box.maxHeight,
)
: 0.0;
final availableHeight = math.max(0.0, box.maxHeight - rulerHeight);
final thickness = math.min(
math.max(16.0, theme.scrollbarThickness),
math.min(contentWidth, availableHeight),
);
return ListenableBuilder(
listenable: Listenable.merge([
widget.controller.contentChanges,
widget.controller.playheadChanges,
]),
child: widget.child,
builder: (context, child) {
_readBounds();
final c = widget.controller;
final end = c.navigationContentEndTick;
final primaryCenter =
c.geometry.primaryTop + c.geometry.primaryHeight / 2;
final restingVerticalPadding = _hasConnectedContent
? c.geometry.primaryHeight.toDouble()
: 0.0;
final viewport = TimelineViewportRect(
width: contentWidth,
height: availableHeight,
);
final scrollTop = math.min(
_top - restingVerticalPadding,
primaryCenter - viewport.height / 2,
);
final scrollBottom = math.max(
_bottom + restingVerticalPadding,
primaryCenter + viewport.height / 2,
);
c.configureViewport(
width: viewport.width,
height: viewport.height,
end: end,
top: scrollTop,
bottom: scrollBottom,
);
c.prepareViewport();
final horizontal =
end > 0 &&
end * c.camera.pixelsPerTick > viewport.width / 2 + 0.001;
final vertical = scrollBottom - scrollTop > viewport.height + 0.001;
if (!identical(_pendingReconcile, c)) {
final controller = c;
_pendingReconcile = controller;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!identical(_pendingReconcile, controller)) return;
_pendingReconcile = null;
if (mounted && identical(widget.controller, controller)) {
controller.reconcileViewport();
}
});
}
final content = Column(
children: [
if (widget.showRuler)
Align(
alignment: Alignment.centerLeft,
child: SizedBox(
width: viewport.width,
height: rulerHeight,
child: TimelineRuler(
controller: c,
showPlayhead: false,
style: widget.rulerStyle,
timecodeLayout: widget.rulerTimecodeLayout,
),
),
),
Expanded(
child: TimelineScrollbars(
controller: c,
viewport: viewport,
horizontal: horizontal,
vertical: vertical,
end: c.navigationEnd(
contentEnd: end,
width: viewport.width,
camera: c.camera,
),
top: scrollTop,
bottom: scrollBottom,
thickness: thickness,
child: child!,
),
),
],
);
final x = c.camera.screenXForTick(c.playheadTick, viewport);
return Stack(
fit: StackFit.expand,
children: [
Padding(
padding: EdgeInsets.only(left: inset),
child: content,
),
Positioned.fill(
child: IgnorePointer(
child: CustomPaint(
key: const ValueKey('timeline-playhead-overlay'),
painter: _PlayheadPainter(
c,
theme,
viewport,
inset,
rulerHeight,
),
),
),
),
if (widget.showRuler &&
(x >= -1 && x <= viewport.width + 1 || _playheadDragging))
Positioned(
left: inset + x.clamp(0.0, viewport.width) - 8,
top: 0,
width: 16,
height: rulerHeight,
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onHorizontalDragStart: (_) {
_playheadDragX = x;
_dragViewport = viewport;
setState(() => _playheadDragging = true);
c.beginScrubbing();
},
onHorizontalDragUpdate: (details) {
_playheadDragX += details.delta.dx;
c.seekAt(
screenX: _playheadDragX.clamp(0.0, viewport.width),
viewport: viewport,
);
_syncEdgeScroll();
},
onHorizontalDragEnd: (_) => _stopPlayheadDrag(),
onHorizontalDragCancel: _stopPlayheadDrag,
),
),
],
);
},
);
},
);
}
final class _PlayheadPainter extends CustomPainter {
_PlayheadPainter(
this.controller,
this.theme,
this.viewport,
this.inset,
this.rulerHeight,
) : super(
repaint: Listenable.merge([
controller.contentChanges,
controller.playheadChanges,
]),
);
final TimelineViewController controller;
final TimelineThemeData theme;
final TimelineViewportRect viewport;
final double inset, rulerHeight;
@override
void paint(Canvas canvas, Size size) {
final localX = controller.camera.screenXForTick(
controller.playheadTick,
viewport,
);
// Seeking snaps to timeline ticks. At an edge, rounding can put the
// projected position just beyond the viewport for alternating frames.
// Keep the dragged marker visible at that edge instead of dropping it.
if (!controller.isScrubbing &&
(localX < -1 || localX > viewport.width + 1)) {
return;
}
final x = inset + localX.clamp(0.0, viewport.width);
final paint = Paint()
..color = theme.playheadColor
..style = PaintingStyle.stroke
..strokeWidth = 1;
canvas.save();
canvas.clipRect(
Rect.fromLTWH(
0,
0,
inset + viewport.width,
rulerHeight + viewport.height,
),
);
if (rulerHeight > 0) {
canvas.drawPath(
Path()
..moveTo(x - 3.5, 0)
..lineTo(x + 3.5, 0)
..lineTo(x + 4.5, 1)
..lineTo(x + 4.5, 7)
..lineTo(x, 12)
..lineTo(x - 4.5, 7)
..lineTo(x - 4.5, 1)
..close(),
paint,
);
}
if (theme.playheadWidth > 0) {
canvas.drawLine(
Offset(x, rulerHeight > 0 ? 12 : 0),
Offset(x, rulerHeight + viewport.height),
paint..strokeWidth = theme.playheadWidth,
);
}
canvas.restore();
}
@override
bool shouldRepaint(_PlayheadPainter old) =>
old.controller != controller ||
old.theme != theme ||
old.viewport != viewport ||
old.inset != inset ||
old.rulerHeight != rulerHeight;
}
@@ -0,0 +1,91 @@
import 'dart:math' as math;
import 'package:cutdex_core/timeline/engine.dart';
import 'package:cutdex_core/timeline/model.dart';
import 'package:flutter/foundation.dart';
/// Host-owned source envelopes, requested during paint and loaded afterwards.
abstract class TimelineWaveforms implements Listenable {
void beginFrame();
/// Whether the clip has a bound audio source, independent of envelope loading.
bool hasAudioFor(ElementRecord element);
TimelineWaveform? waveformFor(ElementRecord element);
void endFrame();
}
final class TimelineWaveformLevel {
const TimelineWaveformLevel({
required this.samplesPerBucket,
required this.channels,
});
final int samplesPerBucket;
/// Immutable packed minimum, maximum, RMS triples per source channel.
final List<List<double>> channels;
}
final class TimelineWaveform {
const TimelineWaveform({
required this.sampleRate,
this.sourceStartSeconds = 0,
required this.frameCount,
required this.levels,
this.amplitudeScale = 1,
});
final double sampleRate;
final double sourceStartSeconds;
final int frameCount;
final List<TimelineWaveformLevel> levels;
/// Display gain only; source envelopes and cached levels remain unchanged.
final double amplitudeScale;
/// Union of channel peaks, avoiding cancellation when channels are out of phase.
({double minimum, double maximum}) envelope(int sourceStart, int sourceEnd) {
final first =
(math.min(sourceStart, sourceEnd) / TimelineClock.ticksPerSecond -
sourceStartSeconds) *
sampleRate;
final last =
(math.max(sourceStart, sourceEnd) / TimelineClock.ticksPerSecond -
sourceStartSeconds) *
sampleRate;
if (levels.isEmpty ||
last <= 0 && first < 0 ||
first >= frameCount ||
frameCount == 0) {
return (minimum: 0, maximum: 0);
}
final start = first.clamp(0.0, frameCount.toDouble());
final end = last.clamp(0.0, frameCount.toDouble());
final base = levels.first.samplesPerBucket;
var cursor = (start / base).floor() * base;
final limit = math.max(cursor + base, (end / base).ceil() * base);
var minimum = 0.0;
var maximum = 0.0;
// Coarse buckets must be fully inside the requested base-bucket range.
// Decompose its edges at finer levels instead of importing adjacent peaks.
while (cursor < limit) {
var level = levels.first;
for (final candidate in levels.reversed) {
final span = candidate.samplesPerBucket;
if (span % base == 0 && cursor % span == 0 && cursor + span <= limit) {
level = candidate;
break;
}
}
final index = cursor ~/ level.samplesPerBucket * 3;
for (final channel in level.channels) {
if (index + 1 >= channel.length) continue;
minimum = math.min(minimum, channel[index]);
maximum = math.max(maximum, channel[index + 1]);
}
cursor += level.samplesPerBucket;
}
return (
minimum: minimum.clamp(-1.0, 1.0),
maximum: maximum.clamp(-1.0, 1.0),
);
}
}
+21
View File
@@ -0,0 +1,21 @@
name: cutdex_timeline_ui
description: Viewport-rendered Flutter UI for the Cutdex timeline.
version: 0.1.0
publish_to: none
environment:
sdk: ^3.12.0
flutter: ">=1.17.0"
resolution: workspace
dependencies:
cutdex_core:
path: ../../.dependencies/cutdex_core
flutter:
sdk: flutter
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^6.0.0
Loaded 100 of 452 files, more files were not shown because too many files have changed in this diff. Show more