import 'package:cutdex_core/timeline/engine.dart'; import 'package:cutdex_core/timeline/layout.dart'; import 'package:cutdex_core/timeline/model.dart'; import 'package:cutdex_timeline_ui/cutdex_timeline_ui.dart'; import 'package:flutter/material.dart'; import 'package:flutter/scheduler.dart'; import 'demo_timeline.dart'; void main() => runApp(const TimelineExampleApp()); class TimelineExampleApp extends StatefulWidget { const TimelineExampleApp({super.key}); @override State createState() => _TimelineExampleAppState(); } class _TimelineExampleAppState extends State with SingleTickerProviderStateMixin, WidgetsBindingObserver { late final TimelineViewController _shortController = createDemoController(); TimelineViewController? _longController; bool _longScene = false; TimelineViewController get _controller => _longScene ? (_longController ??= createDemoController(longTimeline: true)) : _shortController; bool _light = false; late final Ticker _ticker; Duration _elapsed = Duration.zero; Duration _anchorElapsed = Duration.zero; int _anchorTick = 0; bool _updatingPlayhead = false; @override void initState() { super.initState(); _ticker = createTicker(_advancePlayback); _controller.addListener(_timelineChanged); WidgetsBinding.instance.addObserver(this); } int get _duration => _controller.version.kernelVersion.query().storylineSpan( _controller.storyline, ); void _pause() { if (!_ticker.isActive) return; _ticker.stop(); setState(() {}); } void _togglePlayback() { if (_ticker.isActive) { _pause(); return; } if (_duration <= 0 || _controller.isDragging) return; if (_controller.playheadTick >= _duration) _controller.seekTo(0); _anchorTick = _controller.playheadTick; _elapsed = _anchorElapsed = Duration.zero; _ticker.start(); setState(() {}); } void _advancePlayback(Duration elapsed) { _elapsed = elapsed; final tick = _anchorTick + (elapsed - _anchorElapsed).inMicroseconds * TimelineClock.ticksPerSecond ~/ Duration.microsecondsPerSecond; final end = _duration; _updatingPlayhead = true; try { _controller.seekTo(tick.clamp(0, end)); } finally { _updatingPlayhead = false; } if (tick >= end) _pause(); } void _timelineChanged() { if (!_ticker.isActive || _updatingPlayhead) return; // Seeking rebases the clock; editing gestures pause playback. _anchorTick = _controller.playheadTick; _anchorElapsed = _elapsed; if (_controller.isDragging || _anchorTick >= _duration) _pause(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state != AppLifecycleState.resumed) _pause(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); _controller.removeListener(_timelineChanged); _ticker.dispose(); _shortController.dispose(); _longController?.dispose(); super.dispose(); } @override Widget build(BuildContext context) { const dark = TimelineThemeData.dark(); final timelineTheme = _light ? dark.copyWith( backgroundColor: const Color(0xfff1f3f6), gapColor: const Color(0xffdce1e8), connectionLineColor: const Color(0xff505966), selectionOutlineColor: const Color(0xff111827), rulerBackgroundColor: const Color(0xffe2e6ec), rulerTickColor: const Color(0xff505966), scrollbarTrackColor: const Color(0xffe2e6ec), scrollbarThumbColor: const Color(0xff707986), rulerTextStyle: dark.rulerTextStyle.copyWith( color: const Color(0xff374151), ), ) : dark; return MaterialApp( debugShowCheckedModeBanner: false, title: 'Cutdex Timeline Example', theme: ThemeData( brightness: _light ? Brightness.light : Brightness.dark, colorSchemeSeed: const Color(0xff4e82d8), extensions: [timelineTheme], ), home: Scaffold( appBar: AppBar( title: const Text('Timeline · 示例 / Example'), actions: [ PopupMenuButton( tooltip: '切换场景 / Switch scene', icon: const Icon(Icons.video_library_outlined), initialValue: _longScene, onSelected: (value) { _pause(); _controller.cancelDrag(); _controller.removeListener(_timelineChanged); setState(() => _longScene = value); _controller.addListener(_timelineChanged); }, itemBuilder: (_) => const [ PopupMenuItem(value: false, child: Text('短场景 / Short scene')), PopupMenuItem(value: true, child: Text('3 小时 / 3 hours')), ], ), IconButton( tooltip: '切换主题 / Toggle theme', onPressed: () => setState(() => _light = !_light), icon: Icon(_light ? Icons.dark_mode : Icons.light_mode), ), ], ), body: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ const Padding( padding: EdgeInsets.all(12), child: Text( '空白左键框选 · 标尺定位 · 滚动平移 · Ctrl/Cmd+滚轮缩放 · 空格拖动/中键平移\n' 'Blank mouse drag to select · Ruler to seek · Scroll to pan · Ctrl/Cmd+wheel to zoom · Space/middle to pan', ), ), Expanded( child: LayoutBuilder( builder: (context, constraints) => Column( children: [ Wrap( alignment: WrapAlignment.center, children: [ IconButton( key: const Key('playback-toggle'), tooltip: _ticker.isActive ? '暂停 / Pause' : '播放 / Play', onPressed: _togglePlayback, icon: Icon( _ticker.isActive ? Icons.pause : Icons.play_arrow, ), ), IconButton( tooltip: '向左 / Pan left', onPressed: () => _controller.panBy(horizontalPixels: -120), icon: const Icon(Icons.arrow_back), ), IconButton( tooltip: '向右 / Pan right', onPressed: () => _controller.panBy(horizontalPixels: 120), icon: const Icon(Icons.arrow_forward), ), IconButton( tooltip: '缩小 / Zoom out', onPressed: () => _zoom(constraints.maxWidth, 1 / 1.25), icon: const Icon(Icons.zoom_out), ), IconButton( tooltip: '放大 / Zoom in', onPressed: () => _zoom(constraints.maxWidth, 1.25), icon: const Icon(Icons.zoom_in), ), TextButton.icon( onPressed: () { _controller.cancelDrag(); _pause(); _controller.seekTo(0); _controller.setCamera(initialDemoCamera()); _controller.clearSelection(); _controller.setHoveredIdentity(null); }, icon: const Icon(Icons.restart_alt), label: const Text('重置 / Reset'), ), TextButton( onPressed: () { _controller.cancelDrag(); final q = _controller.version.kernelVersion.query(); _controller.setCamera( TimelineCamera( baseTick: q.storylineSpan( _controller.storyline, ), pixelsPerTick: _controller.camera.pixelsPerTick, verticalOffset: _controller.camera.verticalOffset, ).panBy( horizontalPixels: -constraints.maxWidth * 0.75, ), ); }, child: const Text('末尾 / End'), ), ListenableBuilder( listenable: _controller, builder: (context, _) => Row( mainAxisSize: MainAxisSize.min, children: [ IconButton( tooltip: '切割 / Blade (Ctrl/Cmd+B)', icon: const Icon(Icons.content_cut), onPressed: _controller.canCutSelection ? _controller.cutSelectionAtPlayhead : null, ), IconButton( tooltip: '删除 / Delete', icon: const Icon(Icons.delete_outline), onPressed: _controller.canDeleteSelection ? _controller.deleteSelection : null, ), IconButton( tooltip: '撤销 / Undo', icon: const Icon(Icons.undo), onPressed: _controller.canUndo ? _controller.undo : null, ), IconButton( tooltip: '重做 / Redo', icon: const Icon(Icons.redo), onPressed: _controller.canRedo ? _controller.redo : null, ), ], ), ), ], ), Expanded( child: TimelineViewport( controller: _controller, child: TimelineInteractionRegion( controller: _controller, child: TimelineView( key: const Key('timeline-surface'), controller: _controller, classifyContent: classifyDemoMedia, ), ), ), ), ], ), ), ), ListenableBuilder( listenable: _controller, builder: (context, _) => Padding( padding: const EdgeInsets.all(12), child: SizedBox( height: 40, child: Text( '选中 / Selected: ${_selectionLabel()} · ' '${(_controller.camera.pixelsPerTick * TimelineClock.ticksPerSecond).toStringAsFixed(1)} px/s\n' '${_controller.commandRejection ?? _controller.dragRejection ?? (_controller.isDragging ? '预览中,靠边自动滚动 / Preview, hold at edge to scroll' : (_longScene ? '3 小时合成场景 / 3-hour synthetic scene' : '片段拖拽 / Clip drag'))}', maxLines: 2, overflow: TextOverflow.ellipsis, ), ), ), ), ], ), ), ); } void _zoom(double width, double factor) { _controller.zoomBy( scale: factor, viewport: TimelineViewportRect(width: width, height: 0), ); } String _selectionLabel() { if (_controller.selectedIdentities.isEmpty) return '—'; final identity = _controller.selectedIdentities.first; final handle = switch (identity) { ElementHandle value => value, LayoutBodyId value => value.owner, _ => null, }; if (handle == null) { return identity is TransitionId ? identity.value : '$identity'; } final record = _controller.version.kernelVersion.query().element(handle); return record.name ?? record.id.value; } }