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

@@ -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),
);
}
}