From 4f746be301029d6e090839e73994a8f890e44e64 Mon Sep 17 00:00:00 2001 From: lingjhf Date: Wed, 7 Oct 2026 16:03:52 +0800 Subject: [PATCH] perf(editor): integrate native preview and prioritize timeline interaction --- lib/diagnostics/full_app_viewport_bench.dart | 24 + .../full_app_viewport_bench/README.md | 71 ++ .../full_app_viewport_bench/capture.dart | 62 ++ .../full_app_viewport_bench/config.dart | 89 ++ .../full_app_viewport_bench/diagnostics.dart | 70 ++ .../full_app_viewport_bench/drag.dart | 138 +++ .../full_app_viewport_bench/records.dart | 64 ++ .../full_app_viewport_bench/runner.dart | 259 +++++ .../full_app_viewport_bench/workload.dart | 96 ++ lib/diagnostics/timeline_gesture_bench.dart | 220 +++++ lib/diagnostics/timeline_switch_bench.dart | 311 ++++++ lib/features/editor/editor_page.dart | 12 +- lib/features/preview/preview_fullscreen.dart | 3 +- lib/features/preview/preview_panel.dart | 75 +- lib/features/projects/projects_page.dart | 4 +- .../color_interpretation_properties.dart | 7 +- .../properties/picture_properties.dart | 61 +- .../properties_inspector_controller.dart | 33 +- lib/features/timeline/timeline_panel.dart | 28 +- lib/main.dart | 6 + lib/workspace/project_state.dart | 5 + lib/workspace/projects.dart | 140 ++- lib/workspace/timeline_view_state.dart | 29 +- lib/workspace/workspace_session_scope.dart | 4 +- .../windows/cutdex_native_plugin.cpp | 33 +- .../windows/cutdex_native_plugin.h | 5 +- .../windows/cutdex_native_plugin_c_api.cpp | 2 +- pubspec.lock | 40 +- pubspec.yaml | 4 +- .../workload_test.dart | 109 +++ test/properties_preview_updates_test.dart | 146 +++ test/workspace/timeline_navigation_test.dart | 372 ++++++++ tool/windows/native_preview_bench.dart | 883 ++++++++++++++++++ windows/runner/main.cpp.in | 18 +- 34 files changed, 3278 insertions(+), 145 deletions(-) create mode 100644 lib/diagnostics/full_app_viewport_bench.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/README.md create mode 100644 lib/diagnostics/full_app_viewport_bench/capture.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/config.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/diagnostics.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/drag.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/records.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/runner.dart create mode 100644 lib/diagnostics/full_app_viewport_bench/workload.dart create mode 100644 lib/diagnostics/timeline_gesture_bench.dart create mode 100644 lib/diagnostics/timeline_switch_bench.dart create mode 100644 test/diagnostics/full_app_viewport_bench/workload_test.dart create mode 100644 test/properties_preview_updates_test.dart create mode 100644 test/workspace/timeline_navigation_test.dart create mode 100644 tool/windows/native_preview_bench.dart diff --git a/lib/diagnostics/full_app_viewport_bench.dart b/lib/diagnostics/full_app_viewport_bench.dart new file mode 100644 index 0000000..77eb5ee --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench.dart @@ -0,0 +1,24 @@ +// Opt-in profiler of the existing full app; normal launches do no benchmark work. +import 'dart:async'; +import 'dart:io'; + +import 'full_app_viewport_bench/config.dart'; +import 'full_app_viewport_bench/runner.dart'; + +void startFullAppViewportBenchFromEnvironment() { + final output = Platform.environment['CUTDEX_FULL_APP_VIEWPORT_BENCH']; + if (output == null || output.isEmpty) return; + unawaited(_start(output)); +} + +Future _start(String output) async { + try { + await runFullAppViewportBench( + ViewportBenchConfig.fromEnvironment(Platform.environment), + ); + } catch (error, stack) { + final directory = Directory(output); + await directory.create(recursive: true); + await File('${directory.path}/error.txt').writeAsString('$error\n$stack'); + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/README.md b/lib/diagnostics/full_app_viewport_bench/README.md new file mode 100644 index 0000000..508cc30 --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/README.md @@ -0,0 +1,71 @@ +# 完整编辑器拖拽实测 + +没有 `CUTDEX_FULL_APP_VIEWPORT_BENCH` 时入口立即返回。启用后使用正常持久化项目和时间线,通过真实播放头手势进入生产预览链路;不会加载素材夹具或替换页面。请先在正常编辑器打开待测素材所在的时间线并暂停播放。 + +代码职责:`config.dart` 校验配置,`workload.dart` 生成目标轨迹,`drag.dart` 投递实际手势并验证播放头,`diagnostics.dart` 校准 QPC/采样,`records.dart` 写出证据,`capture.dart` 管理可选捕获进程,`runner.dart` 编排和验证停止。 + +以下变量统一加 `CUTDEX_FULL_APP_VIEWPORT_` 前缀: + +| 后缀 | 默认/含义 | +|---|---| +| `BENCH` | 必填输出目录;每次使用新目录 | +| `START_GATE` | 可选门文件路径;正常项目加载后创建文件,最多等待120秒 | +| `EXPECTED_FRAMES` | 可选预期时间线长度,容差2帧;未指定时从实际时间线读取 | +| `TIMELINE_FPS` | 30;目标坐标的时间基准,不是源视频帧率 | +| `ROUNDS` | 5 | +| `PAIRED` | 0;设为1比较全片5%–95%往返和局部往返 | +| `INPUT_HZ` / `INPUT_COUNT` | 60 / 360;配对模式每场景6秒,输入数量必须是至少6的偶数 | +| `LOCAL_START_FRAME` | 实际时间线长度的28%;可指定复现旧测试位置 | +| `LOCAL_SPAN_FRAMES` / `LOCAL_PIXELS_PER_FRAME` | 20 / 4 | +| `EDGE_MARGIN_FRAMES` | 900;旧五场景模式首尾边距,也用于检查时间线足够长;短素材需缩小 | +| `SAMPLE_INTERVAL_MS` | 16 | +| `NATIVE_ONLY` | 1;采样原生提交,不捕获桌面 | +| `CAPTURE_HELPER` | `NATIVE_ONLY=0` 时必填捕获工具绝对路径 | +| `SILENT` | 0;保持生产 audible policy,设为1仅用于明确要求的静音对照 | + +MIDE旧测试配置:`PAIRED=1`、`ROUNDS=3`、`EXPECTED_FRAMES=214073.82`、`LOCAL_START_FRAME=60137`、`NATIVE_ONLY=1`,其余保持默认。 + +输出保留 `inputs.csv`、`phases.csv`、`native-samples.jsonl`、`meta.json` 和 `progress.json` 的既有字段,`meta.json.configuration` 增加实际配置。停止仅等待已有请求完成,不发出额外定位;最终时钟必须命中最后目标,之后观察冻结窗口。通过状态在采样与文件流完成后写出,异常写入 `error.txt`。 + +输入/阶段CSV里的帧数使用配置的时间基准。兼容元数据中名字含 `At30Hz` 的字段仍换算为30Hz。原生提交数不能当作DWM屏幕扫描帧数;正式分析还须校验GPU、输出尺寸、冻结期间源帧计数和最终提交相对松手的时刻。 + +## 时间线切换实测 + +`main.dart` 提供独立、默认关闭的完整应用切换测试,实现在 +`../timeline_switch_bench.dart`。启动正常 Profile 程序前,将 +`CUTDEX_TIMELINE_SWITCH_BENCH` 设置为新的输出目录。测试保持生产 provider +和编辑页面,通过 `GestureBinding` 点击真实时间线标签,输出 +`results.json` 和 `done.json`。 + +初始时间线必须不同于 `CUTDEX_TIMELINE_SWITCH_TARGET`;不设置时选择项目中 +第一个非当前时间线,因此项目至少需要两条时间线。测试等待初始预览控制器 +完成初始化。可选的 `CUTDEX_TIMELINE_SWITCH_GATE` 文件允许先检查正常工作区, +创建该文件后才开始测量。`CUTDEX_TIMELINE_SWITCH_RAPID=1` 改为连续点击五次, +每次计划间隔 16 ms,并在最后一次点击后观察五秒,验证最新选择不被旧请求覆盖; +输出为 `rapid.json`。 + +UI 耗时记录到目标工作区的 post-frame 回调,数据耗时记录到 `Projects` 发布 +准备好的文档。原生首帧采用异步 20 ms 诊断轮询,因此记录的是首次观察耗时; +缓存时间线的原生计数表示复用已有帧。首次打开对照必须使用新进程和未缓存的 +目标会话。启动出错或正常切换测试缺少原生帧均判失败;`startup.json` 记录 +初始状态。快速切换模式验证状态一致性,未单独计时原生首帧。普通启动应清除 +上述测试环境变量。 + +## 触摸板缩放回放与驱动事件 + +`../timeline_gesture_bench.dart` 提供默认关闭的完整应用手势回放。启动正常 +Profile 程序前设置 `CUTDEX_TIMELINE_GESTURE_BENCH` 为新输出目录,测试等待 +六秒后向当前时间线发送原生 pan/zoom 协议及 Ctrl+滚轮输入。播放头应在 +viewport 内,键盘修饰键应松开。输入走正常命中测试和手势识别路径,输出 +`results.json`、`done.json`;异常输出 `error.txt`。回放结束恢复原相机, +不定位播放头、不修改时间线文档。回放不等同于物理触摸板操作。 + +可独立设置 `CUTDEX_TIMELINE_GESTURE_TRACE` 为 JSONL 文件路径,记录实际 +`PointerPanZoom` 与 `PointerScroll` 事件以及 Ctrl/Meta 状态。`source` 区分 +`protocol-replay` 与 `driver`,回放使用 device 7200。记录默认关闭,启用时 +每秒刷新文件,可用于确认驱动是发送合并的 pan/scale,还是兼容滚轮输入。 +普通启动应清除这两个环境变量。 + +独立测试入口 `tool/windows/native_preview_bench.dart` 要求显式设置 +`CUTDEX_BENCH_SOURCE`、`CUTDEX_BENCH_DURATION_FRAMES`(30 Hz 时基下的正整数 +时长)和 `CUTDEX_BENCH_CAPTURE_HELPER`;素材及桌面捕获工具保留在仓库外。 diff --git a/lib/diagnostics/full_app_viewport_bench/capture.dart b/lib/diagnostics/full_app_viewport_bench/capture.dart new file mode 100644 index 0000000..0e0c01f --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/capture.dart @@ -0,0 +1,62 @@ +import 'dart:async'; +import 'dart:io'; + +import 'config.dart'; + +/// Optional desktop capture process; its path is supplied explicitly. +class BenchCapture { + BenchCapture._(this.output, this.process); + final Directory output; + final Process process; + + static Future start( + ViewportBenchConfig config, + Directory output, + ) async { + if (config.nativeOnly) return null; + final helper = config.captureHelper!; + final probe = await Process.run(helper, ['$pid']); + if (probe.exitCode != 0) { + throw StateError('Capture probe failed: ${probe.stderr}'); + } + final line = probe.stdout + .toString() + .split('\n') + .singleWhere((s) => s.startsWith('CutdexD3D11Preview 1 ')); + final rect = line.trim().split(' ').skip(2).map(int.parse).toList(); + final process = await Process.start(helper, [ + output.path, + '$pid', + '${rect[0] + 8}', + '${rect[1] + 8}', + '${rect[2] - 8}', + '${rect[3] - 8}', + ]); + unawaited(process.stdout.drain()); + unawaited(process.stderr.drain()); + final capture = BenchCapture._(output, process); + for ( + var i = 0; + !await File('${output.path}/capture-ready').exists() && i < 500; + i++ + ) { + await Future.delayed(const Duration(milliseconds: 10)); + } + if (!await File('${output.path}/capture-ready').exists()) { + await capture.stop(); + throw StateError('Capture not ready'); + } + return capture; + } + + Future stop() async { + await File('${output.path}/capture-stop').writeAsString('stop'); + try { + final code = await process.exitCode.timeout(const Duration(seconds: 10)); + if (code != 0) throw StateError('Capture exit $code'); + } on TimeoutException { + process.kill(); + rethrow; + } + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/config.dart b/lib/diagnostics/full_app_viewport_bench/config.dart new file mode 100644 index 0000000..53fc9e0 --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/config.dart @@ -0,0 +1,89 @@ +/// Explicit inputs for the opt-in full-editor benchmark. +class ViewportBenchConfig { + ViewportBenchConfig.fromEnvironment(Map environment) + : outputPath = environment['CUTDEX_FULL_APP_VIEWPORT_BENCH']!, + startGate = environment['CUTDEX_FULL_APP_VIEWPORT_START_GATE'], + expectedFrames = _number(environment, 'EXPECTED_FRAMES'), + rounds = _integer(environment, 'ROUNDS', 5), + paired = _flag(environment, 'PAIRED', false), + silent = _flag(environment, 'SILENT', false), + nativeOnly = _flag(environment, 'NATIVE_ONLY', true), + captureHelper = environment['CUTDEX_FULL_APP_VIEWPORT_CAPTURE_HELPER'], + timelineFps = _integer(environment, 'TIMELINE_FPS', 30), + inputHz = _integer(environment, 'INPUT_HZ', 60), + inputCount = _integer(environment, 'INPUT_COUNT', 360), + localStartFrame = _optionalInteger(environment, 'LOCAL_START_FRAME'), + localSpanFrames = _integer(environment, 'LOCAL_SPAN_FRAMES', 20), + localPixelsPerFrame = _number(environment, 'LOCAL_PIXELS_PER_FRAME') ?? 4, + edgeMarginFrames = _integer(environment, 'EDGE_MARGIN_FRAMES', 900), + sampleIntervalMs = _integer(environment, 'SAMPLE_INTERVAL_MS', 16) { + if (outputPath.isEmpty || + rounds < 1 || + timelineFps < 1 || + inputHz < 1 || + inputCount < 6 || + inputCount.isOdd || + localSpanFrames < 1 || + localPixelsPerFrame <= 0 || + edgeMarginFrames < 1 || + sampleIntervalMs < 1 || + (expectedFrames != null && expectedFrames! <= 0)) { + throw ArgumentError('Invalid viewport benchmark configuration'); + } + if (!nativeOnly && (captureHelper == null || captureHelper!.isEmpty)) { + throw ArgumentError('CAPTURE_HELPER is required when NATIVE_ONLY=0'); + } + } + + final String outputPath; + final String? startGate; + final double? expectedFrames; + final int rounds, timelineFps, inputHz, inputCount, localSpanFrames; + final int edgeMarginFrames, sampleIntervalMs; + final int? localStartFrame; + final double localPixelsPerFrame; + final bool paired, silent, nativeOnly; + final String? captureHelper; + + Map toJson() => { + 'expectedFrames': expectedFrames, + 'rounds': rounds, + 'paired': paired, + 'timelineFps': timelineFps, + 'inputHz': inputHz, + 'inputCount': inputCount, + 'localStartFrame': localStartFrame, + 'localSpanFrames': localSpanFrames, + 'localPixelsPerFrame': localPixelsPerFrame, + 'edgeMarginFrames': edgeMarginFrames, + 'sampleIntervalMs': sampleIntervalMs, + 'nativeOnly': nativeOnly, + 'captureHelper': captureHelper, + 'silent': silent, + }; + + static int _integer(Map env, String key, int fallback) => + _optionalInteger(env, key) ?? fallback; + static int? _optionalInteger(Map env, String key) { + final value = env['CUTDEX_FULL_APP_VIEWPORT_$key']; + return value == null ? null : int.parse(value); + } + + static double? _number(Map env, String key) { + final value = env['CUTDEX_FULL_APP_VIEWPORT_$key']; + if (value == null) return null; + final number = double.parse(value); + if (!number.isFinite) throw ArgumentError('Non-finite $key'); + return number; + } + + static bool _flag(Map env, String key, bool fallback) { + final value = env['CUTDEX_FULL_APP_VIEWPORT_$key']; + return switch (value) { + null => fallback, + '1' => true, + '0' => false, + _ => throw ArgumentError('$key must be 0 or 1'), + }; + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/diagnostics.dart b/lib/diagnostics/full_app_viewport_bench/diagnostics.dart new file mode 100644 index 0000000..58c9f16 --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/diagnostics.dart @@ -0,0 +1,70 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/services.dart'; + +/// Native QPC clock calibration and bounded asynchronous diagnostics sampling. +class BenchDiagnostics { + BenchDiagnostics(this.sessionId, this.clock); + final String sessionId; + final Stopwatch clock; + static const _channel = MethodChannel('cutdex_runtime'); + double uncertaintyMs = double.infinity, _offset = 0; + Timer? _timer; + Future? _pending; + Object? _sampleError; + + double now() => _offset + clock.elapsedMicroseconds / 1000; + Future> read() async => + (await _channel.invokeMapMethod('previewDiagnostics', { + 'sessionId': sessionId, + }))!; + + Future calibrate() async { + for (var i = 0; i < 20; i++) { + final begin = clock.elapsedMicroseconds / 1000; + final diagnostic = await read(); + final end = clock.elapsedMicroseconds / 1000; + if (end - begin < uncertaintyMs) { + uncertaintyMs = end - begin; + _offset = (diagnostic['qpcMs'] as num).toDouble() - (begin + end) / 2; + } + } + } + + Future until(double due) async { + while (now() < due) { + await Future.delayed( + Duration(microseconds: ((due - now()) * 1000).ceil().clamp(1, 1000000)), + ); + } + } + + void startSamples(IOSink sink, int intervalMs) { + _timer = Timer.periodic(Duration(milliseconds: intervalMs), (_) { + if (_pending != null || _sampleError != null) return; + _pending = _sample(sink).whenComplete(() => _pending = null); + }); + } + + Future _sample(IOSink sink) async { + try { + sink.writeln(jsonEncode(await read())); + } catch (error) { + _sampleError = error; + } + } + + void check() { + if (_sampleError != null) { + throw StateError('Native sampler failed: $_sampleError'); + } + } + + Future stopSamples() async { + _timer?.cancel(); + await _pending; + check(); + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/drag.dart b/lib/diagnostics/full_app_viewport_bench/drag.dart new file mode 100644 index 0000000..de8ef7a --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/drag.dart @@ -0,0 +1,138 @@ +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/rendering.dart'; + +/// Real playhead gesture input, quantized to physical pixels like desktop input. +class BenchPlayheadDrag { + BenchPlayheadDrag({ + required this.view, + required this.ruler, + required this.viewport, + required this.scale, + required this.clock, + required this.pointer, + required this.warmFrame, + required this.fps, + }) : camera = view.camera; + final TimelineViewController view; + final RenderBox ruler; + final TimelineViewportRect viewport; + final TimelineCamera camera; + final double scale; + final Stopwatch clock; + final int pointer, warmFrame, fps; + Offset _position = Offset.zero, _origin = Offset.zero; + bool _active = false; + + int tick(int frame) => + TimelineClock.standard.toTicks(RationalTime(frame, fps)); + double get _pixelsPerFrame => camera.pixelsPerTick * tick(1); + int _delta(int frame) => + ((frame - warmFrame) * _pixelsPerFrame * scale).round(); + int target(int frame) => + (warmFrame + _delta(frame) / (_pixelsPerFrame * scale)).round(); + + Future begin() async { + final point = ruler.localToGlobal( + Offset( + camera.screenXForTick(tick(warmFrame), viewport), + ruler.size.height / 2, + ), + ); + _position = Offset( + (point.dx * scale).round() / scale, + (point.dy * scale).round() / scale, + ); + GestureBinding.instance.handlePointerEvent( + PointerAddedEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: _position, + ), + ); + GestureBinding.instance.handlePointerEvent( + PointerDownEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + buttons: kPrimaryButton, + position: _position, + timeStamp: clock.elapsed, + ), + ); + _active = true; + _move(_position + const Offset(40, 0)); + await Future.delayed(const Duration(milliseconds: 20)); + if (!view.isScrubbing || view.playheadTick != tick(warmFrame)) { + throw StateError('Playhead drag warmup failed'); + } + _origin = _position; + } + + void moveTo(int frame) { + _move(_origin + Offset(_delta(frame) / scale, 0)); + if (!view.isScrubbing || view.playheadTick != tick(target(frame))) { + throw StateError('Real playhead mismatch at input frame $frame'); + } + } + + void _move(Offset next) { + GestureBinding.instance.handlePointerEvent( + PointerMoveEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + buttons: kPrimaryButton, + position: next, + delta: next - _position, + timeStamp: clock.elapsed, + ), + ); + _position = next; + } + + void end() { + GestureBinding.instance.handlePointerEvent( + PointerUpEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: _position, + timeStamp: clock.elapsed, + ), + ); + _remove(); + if (view.isScrubbing || !identical(camera, view.camera)) { + throw StateError('Release/camera failure'); + } + } + + void cancel() { + if (!_active) return; + GestureBinding.instance.handlePointerEvent( + PointerCancelEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: _position, + timeStamp: clock.elapsed, + ), + ); + _remove(); + } + + void _remove() { + GestureBinding.instance.handlePointerEvent( + PointerRemovedEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: _position, + ), + ); + _active = false; + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/records.dart b/lib/diagnostics/full_app_viewport_bench/records.dart new file mode 100644 index 0000000..27ed918 --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/records.dart @@ -0,0 +1,64 @@ +import 'dart:convert'; +import 'dart:io'; + +/// Owns benchmark output streams and metadata, preserving the existing CSV schema. +class BenchRecords { + BenchRecords(this.output) + : inputs = File('${output.path}/inputs.csv').openWrite(), + phases = File('${output.path}/phases.csv').openWrite(), + samples = File('${output.path}/native-samples.jsonl').openWrite() { + inputs.writeln( + 'round,scenario,index,target,qpc_ms,scheduled_ms,request_ms', + ); + phases.writeln( + 'round,scenario,start_ms,end_ms,release_begin_ms,final_frame,final_clock_frame,freeze_begin_ms,freeze_end_ms', + ); + } + final Directory output; + final IOSink inputs, phases, samples; + Future? _closing; + final stages = >[], checks = >[]; + + void input( + int round, + int scenario, + int index, + int target, + double begin, + double due, + double returned, + ) => inputs.writeln( + '$round,$scenario,$index,$target,$begin,$due,${returned - begin}', + ); + void phase( + int round, + int scenario, + double start, + double end, + double release, + int finalFrame, + double actual, + double frozenBegin, + double frozenEnd, + ) => phases.writeln( + '$round,$scenario,$start,$end,$release,$finalFrame,$actual,$frozenBegin,$frozenEnd', + ); + Future progress(int round) => + File('${output.path}/progress.json') + .writeAsString(jsonEncode({'completedRounds': round})); + Future complete(Map metadata) => + File('${output.path}/meta.json').writeAsString( + jsonEncode({ + ...metadata, + 'nativeDiagnostics': stages, + 'checks': checks, + }), + ); + Future close() => _closing ??= _close(); + + Future _close() async { + await samples.close(); + await inputs.close(); + await phases.close(); + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/runner.dart b/lib/diagnostics/full_app_viewport_bench/runner.dart new file mode 100644 index 0000000..df504a5 --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/runner.dart @@ -0,0 +1,259 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import 'capture.dart'; +import 'config.dart'; +import 'diagnostics.dart'; +import 'drag.dart'; +import 'records.dart'; +import 'workload.dart'; + +Future _sleep(int ms) => Future.delayed(Duration(milliseconds: ms)); + +/// Orchestrates existing editor state, real input, exact-stop validation and output. +Future runFullAppViewportBench(ViewportBenchConfig config) async { + final output = Directory(config.outputPath); + final clock = Stopwatch()..start(); + BenchCapture? capture; + BenchDiagnostics? diagnostics; + BenchRecords? records; + BenchPlayheadDrag? activeDrag; + await output.create(recursive: true); + try { + await _sleep(6000); + if (config.startGate case final gatePath?) { + final gate = File(gatePath); + for (var i = 0; !await gate.exists() && i < 240; i++) { + await _sleep(500); + } + if (!await gate.exists()) { + throw StateError('Benchmark start gate timed out'); + } + } + Element? previewElement; + TimelineViewport? timeline; + RenderBox? ruler; + void visit(Element element) { + if (element.widget is EditorPreviewPanel) previewElement = element; + if (element.widget is TimelineViewport) { + timeline = element.widget as TimelineViewport; + } + if (element.widget is TimelineRuler) { + ruler = element.findRenderObject() as RenderBox?; + } + element.visitChildElements(visit); + } + + WidgetsBinding.instance.rootElement!.visitChildElements(visit); + if (previewElement == null || timeline == null || ruler == null) { + throw StateError('Full normal editor is not open'); + } + final panel = previewElement!.widget as EditorPreviewPanel; + final container = ProviderScope.containerOf(previewElement!); + final preview = container + .read(editorPreviewProvider(panel.projectId, panel.timelineId)) + .asData + ?.value; + if (preview?.session == null || preview!.error != null) { + throw StateError('Normal preview unavailable'); + } + final sequence = preview.activeSequence()!; + final view = timeline!.controller; + final endTime = TimelineClock.standard.fromTicks(view.contentEndTick); + final endFrame = + endTime.numerator * config.timelineFps / endTime.denominator; + final workloads = ViewportBenchWorkload.forTimeline(config, endFrame); + view.fitTimeline(); + await _sleep(500); + final viewport = TimelineViewportRect( + width: ruler!.size.width, + height: ruler!.size.height, + ); + final scale = View.of(previewElement!).devicePixelRatio; + final clipStart = view.camera.screenXForTick(0, viewport); + final clipEnd = view.camera.screenXForTick(view.contentEndTick, viewport); + if (clipStart < 0 || clipEnd > viewport.width) { + throw StateError('Clip outside viewport'); + } + final native = diagnostics = BenchDiagnostics(preview.session!.id, clock); + await native.calibrate(); + capture = await BenchCapture.start(config, output); + final record = records = BenchRecords(output); + native.startSamples(record.samples, config.sampleIntervalMs); + int tick(int frame) => + TimelineClock.standard.toTicks(RationalTime(frame, config.timelineFps)); + + for (var round = 1; round <= config.rounds; round++) { + for (final workload in workloads) { + final scenario = workload.scenario; + if (config.paired) { + if (workload.local) { + view.setCamera( + TimelineCamera( + baseTick: tick(workload.cameraBaseFrame), + pixelsPerTick: config.localPixelsPerFrame / tick(1), + verticalOffset: view.camera.verticalOffset, + ), + ); + } else { + view.fitTimeline(); + } + await _sleep(100); + } + final warm = workload.warmFrame; + final drag = activeDrag = BenchPlayheadDrag( + view: view, + ruler: ruler!, + viewport: viewport, + scale: scale, + clock: clock, + pointer: 100 + round * 10 + scenario, + warmFrame: warm, + fps: config.timelineFps, + ); + await preview.controlPreview( + sequence, + PreviewAction.seek, + at: CommandTime(warm, config.timelineFps), + ); + await _sleep(80); + if (config.silent) { + await preview.session!.beginSkimming(mode: SkimmingMode.silent); + } + await drag.begin(); + drag.moveTo(workload.idealFrame(0)); + await _sleep(350); + final before = await native.read(); + final start = native.now(); + for (var i = 0; i < workload.count; i++) { + final due = start + 1000 * i / workload.hz; + await native.until(due); + final begin = native.now(); + final ideal = workload.idealFrame(i); + drag.moveTo(ideal); + record.input( + round, + scenario, + i, + drag.target(ideal), + begin, + due, + native.now(), + ); + } + await native.until(start + workload.durationMs); + final end = native.now(); + final release = native.now(); + drag.end(); + activeDrag = null; + await preview.waitForPendingPreview(); + final settled = await preview.session!.refresh(); + final settledAt = native.now(); + await _sleep(350); + final frozenBegin = native.now(); + await _sleep(350); + final snapshot = await preview.session!.refresh(); + final after = await native.read(); + record.stages.add({ + 'round': round, + 'scenario': scenario, + 'before': before, + 'after': after, + 'settledAtMs': settledAt, + 'settledClock': + '${settled.position.numerator}/${settled.position.denominator}', + }); + final actual = + snapshot.position.numerator * + config.timelineFps / + snapshot.position.denominator; + final finalTarget = drag.target( + workload.idealFrame(workload.count - 1), + ); + if ((actual - finalTarget).abs() > .01 || preview.error != null) { + throw StateError('Final precision failure $actual'); + } + native.check(); + record.checks.add({ + 'round': round, + 'scenario': scenario, + 'finalClockFrame': actual, + 'target': finalTarget, + 'state': snapshot.state.name, + }); + record.phase( + round, + scenario, + start, + end, + release, + finalTarget, + actual, + frozenBegin, + native.now(), + ); + } + await record.progress(round); + } + await capture?.stop(); + capture = null; + await native.stopSamples(); + await record.close(); + await record.complete({ + 'status': 'passed', + 'entrypoint': 'lib/main.dart', + 'fullApp': true, + 'startGateUsed': config.startGate != null, + 'configuration': config.toJson(), + 'projectId': panel.projectId, + 'timelineId': panel.timelineId, + 'sequenceId': sequence.value, + 'timelineEndFramesAt30Hz': endFrame * 30 / config.timelineFps, + 'firstSampleFrameAt30Hz': + config.edgeMarginFrames * 30 / config.timelineFps, + 'lastSampleFrameAt30Hz': + (endFrame.round() - config.edgeMarginFrames - 1) * + 30 / + config.timelineFps, + 'clipStartX': clipStart, + 'clipEndX': clipEnd, + 'viewportWidth': viewport.width, + 'devicePixelRatio': scale, + 'qpcCalibrationRoundTripMs': native.uncertaintyMs, + 'inputRoute': 'GestureBinding -> real normal TimelineViewport playhead handle -> production preview/runtime/native presenter', + 'physicalPixelInput': true, + 'rounds': config.rounds, + 'pairedWideLocal': config.paired, + 'nativeOnly': config.nativeOnly, + 'silentOverride': config.silent, + 'skimmingPolicy': preview.policy.skimmingMode.name, + 'canvas': { + 'width': preview.canvas.width, + 'height': preview.canvas.height, + }, + 'timelineSettings': preview.timeline.settings, + }); + // Leave the normal editor paused with the complete clip visible. + view.fitTimeline(); + } finally { + activeDrag?.cancel(); + try { + await capture?.stop(); + } finally { + try { + await diagnostics?.stopSamples(); + } finally { + await records?.close(); + } + } + } +} diff --git a/lib/diagnostics/full_app_viewport_bench/workload.dart b/lib/diagnostics/full_app_viewport_bench/workload.dart new file mode 100644 index 0000000..8426e54 --- /dev/null +++ b/lib/diagnostics/full_app_viewport_bench/workload.dart @@ -0,0 +1,96 @@ +import 'config.dart'; + +/// A deterministic input sequence; independent of Flutter, decoding and sampling. +class ViewportBenchWorkload { + const ViewportBenchWorkload({ + required this.scenario, + required this.hz, + required this.count, + required this.firstFrame, + required this.lastFrame, + required this.steps, + required this.paired, + required this.localSpanFrames, + required this.timelineEndFrame, + }); + + final int scenario, hz, count, firstFrame, lastFrame, steps, localSpanFrames; + final bool paired; + final double timelineEndFrame; + bool get local => paired && scenario == 1; + double get durationMs => 1000 * count / hz; + int get warmFrame => idealFrame(0) - 1; + int get cameraBaseFrame => firstFrame - 17; + + int idealFrame(int i) { + if (local) { + final phase = i % (2 * localSpanFrames); + return firstFrame + + (phase <= localSpanFrames ? phase : 2 * localSpanFrames - phase); + } + if (paired) { + final half = count ~/ 2; + final phase = i % count; + final index = phase < half ? phase : count - 1 - phase; + return (timelineEndFrame * (.05 + .9 * index / (half - 1))).round(); + } + final period = 2 * (steps - 1); + final phase = i % period; + final index = switch (scenario) { + 0 => i, + 1 => steps - 1 - i, + _ => phase < steps ? phase : period - phase, + }; + return (firstFrame * (steps - 1) + + (lastFrame - firstFrame) * index + + (steps - 1) ~/ 2) ~/ + (steps - 1); + } + + static List forTimeline( + ViewportBenchConfig config, + double endFrame, + ) { + if (!endFrame.isFinite || + endFrame < 2 * config.edgeMarginFrames + 2 || + (config.expectedFrames != null && + (endFrame - config.expectedFrames!).abs() > 2)) { + throw StateError('Unexpected normal timeline length: $endFrame'); + } + final localStart = config.localStartFrame ?? (endFrame * .28).round(); + if (config.paired && + (localStart < 18 || localStart + config.localSpanFrames >= endFrame)) { + throw StateError('Local benchmark range falls outside the timeline'); + } + final steps = config.inputCount ~/ 3; + return List.generate(config.paired ? 2 : 5, (scenario) { + final hz = config.paired + ? config.inputHz + : config.inputHz * [1, 2, 1, 2, 4][scenario]; + final count = config.paired + ? config.inputCount + : [ + steps, + steps, + config.inputCount, + config.inputCount * 2, + config.inputCount * 4, + ][scenario]; + return ViewportBenchWorkload( + scenario: scenario, + hz: hz, + count: count, + firstFrame: config.paired + ? (scenario == 0 ? (endFrame * .05).round() : localStart) + : config.edgeMarginFrames, + lastFrame: config.paired + ? (endFrame * .95).round() + : endFrame.round() - config.edgeMarginFrames - 1, + steps: steps, + paired: config.paired, + localSpanFrames: config.localSpanFrames, + timelineEndFrame: endFrame, + ); + }); + } +} diff --git a/lib/diagnostics/timeline_gesture_bench.dart b/lib/diagnostics/timeline_gesture_bench.dart new file mode 100644 index 0000000..342d7d0 --- /dev/null +++ b/lib/diagnostics/timeline_gesture_bench.dart @@ -0,0 +1,220 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +bool _replayActive = false; + +/// Replays trackpad input through the normal full-app timeline hit-test path. +/// An independent opt-in trace can also record physical driver events. +void startTimelineGestureBenchFromEnvironment() { + final trace = Platform.environment['CUTDEX_TIMELINE_GESTURE_TRACE']; + if (trace != null && trace.isNotEmpty) { + final file = File(trace)..parent.createSync(recursive: true); + final sink = file.openWrite(mode: FileMode.append); + Timer.periodic(const Duration(seconds: 1), (_) => unawaited(sink.flush())); + GestureBinding.instance.pointerRouter.addGlobalRoute((event) { + if (event is! PointerPanZoomStartEvent && + event is! PointerPanZoomUpdateEvent && + event is! PointerPanZoomEndEvent && + event is! PointerScrollEvent) { + return; + } + sink.writeln( + jsonEncode({ + 'at': DateTime.now().toUtc().toIso8601String(), + 'type': event.runtimeType.toString(), + 'source': _replayActive ? 'protocol-replay' : 'driver', + 'device': event.device, + 'kind': event.kind.name, + 'control': HardwareKeyboard.instance.isControlPressed, + 'meta': HardwareKeyboard.instance.isMetaPressed, + if (event is PointerPanZoomUpdateEvent) ...{ + 'pan': [event.pan.dx, event.pan.dy], + 'scale': event.scale, + }, + if (event is PointerScrollEvent) + 'scroll': [event.scrollDelta.dx, event.scrollDelta.dy], + }), + ); + }); + } + final output = Platform.environment['CUTDEX_TIMELINE_GESTURE_BENCH']; + if (output == null || output.isEmpty) return; + unawaited( + _run(output).catchError((Object error, StackTrace stack) async { + await Directory(output).create(recursive: true); + await File('$output/error.txt').writeAsString('$error\n$stack'); + }), + ); +} + +Element? _surface() { + Element? result; + void visit(Element element) { + if (element.widget case TimelineInteractionRegion(ruler: false)) { + result = element; + } + element.visitChildElements(visit); + } + + WidgetsBinding.instance.rootElement?.visitChildElements(visit); + return result; +} + +Future _run(String output) async { + await Directory(output).create(recursive: true); + await Future.delayed(const Duration(seconds: 6)); + final element = _surface(); + if (element == null) throw StateError('Normal timeline surface is not open'); + if (HardwareKeyboard.instance.logicalKeysPressed.isNotEmpty) { + throw StateError('Release keyboard modifiers before replay'); + } + final region = element.widget as TimelineInteractionRegion; + final c = region.controller; + final box = element.findRenderObject()! as RenderBox; + final viewport = TimelineViewportRect( + width: box.size.width, + height: box.size.height, + ); + final position = box.localToGlobal( + Offset(box.size.width * .8, box.size.height * .5), + ); + final saved = c.camera; + final playhead = c.playheadTick; + final version = c.version; + final x = saved.screenXForTick(playhead, viewport); + if (x < 0 || x > viewport.width) throw StateError('Playhead must be visible'); + final rows = >[]; + const device = 7200; + void send(PointerEvent event) => + GestureBinding.instance.handlePointerEvent(event); + void start(int pointer) => send( + PointerPanZoomStartEvent( + pointer: pointer, + device: device, + position: position, + ), + ); + void update(int pointer, Offset pan, double scale) => send( + PointerPanZoomUpdateEvent( + pointer: pointer, + device: device, + position: position, + pan: pan, + scale: scale, + ), + ); + void end(int pointer) => send( + PointerPanZoomEndEvent( + pointer: pointer, + device: device, + position: position, + ), + ); + void record(String name, {bool anchor = true}) { + final drift = c.camera.screenXForTick(playhead, viewport) - x; + final unchanged = + c.playheadTick == playhead && identical(c.version, version); + rows.add({ + 'scenario': name, + 'playheadPixelDrift': drift, + 'scaleRatio': c.camera.pixelsPerTick / saved.pixelsPerTick, + 'verticalDrift': c.camera.verticalOffset - saved.verticalOffset, + 'timelineUnchanged': unchanged, + 'cameraBaseTick': c.camera.baseTick, + 'savedCameraBaseTick': saved.baseTick, + }); + File('$output/progress.json').writeAsStringSync(jsonEncode(rows)); + if (!unchanged || (anchor && drift.abs() > .001)) { + throw StateError('$name changed the timeline or moved the zoom anchor'); + } + } + + try { + _replayActive = true; + send( + PointerAddedEvent( + device: device, + kind: PointerDeviceKind.trackpad, + position: position, + ), + ); + start(7201); + update(7201, const Offset(50, 30), 1.2); + await Future.delayed(const Duration(milliseconds: 16)); + update(7201, const Offset(100, 60), 1.5); + await WidgetsBinding.instance.endOfFrame; + record('native-pinch-with-translation'); + final pinchCamera = c.camera; + update(7201, const Offset(140, 90), 1.5); + await WidgetsBinding.instance.endOfFrame; + record('pinch-scale-pauses'); + if (c.camera != pinchCamera) throw StateError('Pinch tail became a pan'); + end(7201); + c.setCamera(saved); + HardwareKeyboard.instance.handleKeyEvent( + const KeyDownEvent( + physicalKey: PhysicalKeyboardKey.controlLeft, + logicalKey: LogicalKeyboardKey.controlLeft, + timeStamp: Duration.zero, + ), + ); + try { + send( + PointerScrollEvent( + position: position, + scrollDelta: const Offset(0, -120), + ), + ); + } finally { + HardwareKeyboard.instance.handleKeyEvent( + const KeyUpEvent( + physicalKey: PhysicalKeyboardKey.controlLeft, + logicalKey: LogicalKeyboardKey.controlLeft, + timeStamp: Duration(milliseconds: 1), + ), + ); + } + await WidgetsBinding.instance.endOfFrame; + record('control-scroll-zoom'); + c.setCamera(saved); + start(7202); + update(7202, const Offset(-30, 0), 1); + await Future.delayed(const Duration(milliseconds: 16)); + update(7202, const Offset(-70, 0), 1); + await WidgetsBinding.instance.endOfFrame; + record('plain-two-finger-pan', anchor: false); + end(7202); + if ((c.camera.screenXForTick(playhead, viewport) - x).abs() < 1 || + c.camera.pixelsPerTick != saved.pixelsPerTick) { + throw StateError('Ordinary pan stopped working'); + } + await File('$output/results.json').writeAsString( + jsonEncode({ + 'inputRoute': + 'GestureBinding -> normal full-app TimelineInteractionRegion', + 'inputKind': 'synthetic driver-protocol replay; not physical fingers', + 'playheadTick': playhead, + 'playheadScreenX': x, + 'rows': rows, + }), + ); + } finally { + send( + PointerRemovedEvent( + device: device, + kind: PointerDeviceKind.trackpad, + position: position, + ), + ); + c.setCamera(saved); + _replayActive = false; + } + await File('$output/done.json').writeAsString(jsonEncode({'complete': true})); +} diff --git a/lib/diagnostics/timeline_switch_bench.dart b/lib/diagnostics/timeline_switch_bench.dart new file mode 100644 index 0000000..9a3bbc8 --- /dev/null +++ b/lib/diagnostics/timeline_switch_bench.dart @@ -0,0 +1,311 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../features/editor/editor_page.dart'; +import '../features/preview/preview_panel.dart'; +import '../workspace/timeline_provider.dart'; +import '../workspace/projects.dart'; +import '../workspace/project_state.dart'; +import '../workspace/preview_controller_registry.dart'; +import 'full_app_viewport_bench/diagnostics.dart'; +import 'app_diagnostics.dart'; + +/// Opt-in measurements through normal timeline tabs in the complete application. +void startTimelineSwitchBenchFromEnvironment() { + final output = Platform.environment['CUTDEX_TIMELINE_SWITCH_BENCH']; + if (output == null || output.isEmpty) return; + unawaited( + _run(output).catchError((Object error, StackTrace stack) async { + await Directory(output).create(recursive: true); + await File('$output/error.txt').writeAsString('$error\n$stack'); + }), + ); +} + +Element? _find(bool Function(Widget) matches) { + Element? result; + void visit(Element element) { + if (matches(element.widget)) result = element; + element.visitChildElements(visit); + } + + WidgetsBinding.instance.rootElement?.visitChildElements(visit); + return result; +} + +Future _run(String output) async { + await Directory(output).create(recursive: true); + final gate = Platform.environment['CUTDEX_TIMELINE_SWITCH_GATE']; + await Future.delayed(const Duration(seconds: 6)); + if (gate != null) { + for (var i = 0; !await File(gate).exists() && i < 600; i++) { + await Future.delayed(const Duration(milliseconds: 200)); + } + if (!await File(gate).exists()) throw StateError('Start gate timed out'); + } + final element = _find((widget) => widget is EditorWorkspace); + if (element == null) throw StateError('Normal editor is not open'); + final container = ProviderScope.containerOf(element); + final initial = container.read(projectsProvider).requireValue; + final projectId = initial.activeProject!.id; + final target = + Platform.environment['CUTDEX_TIMELINE_SWITCH_TARGET'] ?? + initial.timelines.firstWhere((t) => t.id != initial.timeline!.id).id; + if (initial.timeline!.id == target) throw StateError('Target already active'); + final initialSession = container + .read(projectsProvider.notifier) + .cachedTimelineSession(projectId, initial.timeline!.id)!; + final initialSequence = initialSession.activeSequenceId; + File('$output/startup.json').writeAsStringSync( + jsonEncode({ + 'initialTimelineId': initial.timeline!.id, + 'editorError': container + .read(editorTimelineProvider(projectId, initial.timeline!.id)) + .error + ?.toString(), + 'previewError': container + .read(editorPreviewProvider(projectId, initial.timeline!.id)) + .error + ?.toString(), + 'diagnosticsDirectory': AppDiagnostics.instance?.store.directory.path, + }), + ); + if (initialSequence != null && + initialSession.sequenceDurationTicks(initialSequence) > 0) { + var ready = false; + for (var i = 0; i < 3000; i++) { + final editing = container.read( + editorTimelineProvider(projectId, initial.timeline!.id), + ); + if (editing.hasError) { + throw StateError( + 'Initial editor failed: ${editing.error}\n${editing.stackTrace}', + ); + } + final previewState = container.read( + editorPreviewProvider(projectId, initial.timeline!.id), + ); + if (previewState.hasError) { + throw StateError( + 'Initial preview failed: ${previewState.error}\n${previewState.stackTrace}', + ); + } + final preview = container.read(previewControllerRegistryProvider).cached(( + projectId, + initial.timeline!.id, + )); + if (preview?.session != null) { + ready = true; + break; + } + await Future.delayed(const Duration(milliseconds: 20)); + } + if (!ready) throw StateError('Initial preview is not ready'); + } + final rows = >[]; + var pointer = 500; + + void tap(String id, Stopwatch clock) { + final button = _find( + (widget) => widget.key == ValueKey('timeline-tab-$id'), + ); + final box = button?.findRenderObject() as RenderBox?; + if (box == null || !box.hasSize) throw StateError('Tab not laid out: $id'); + final position = box.localToGlobal(box.size.center(Offset.zero)); + final input = ++pointer; + GestureBinding.instance.handlePointerEvent( + PointerAddedEvent( + pointer: input, + device: 51, + kind: PointerDeviceKind.mouse, + position: position, + ), + ); + GestureBinding.instance.handlePointerEvent( + PointerDownEvent( + pointer: input, + device: 51, + kind: PointerDeviceKind.mouse, + buttons: kPrimaryButton, + position: position, + timeStamp: clock.elapsed, + ), + ); + GestureBinding.instance.handlePointerEvent( + PointerUpEvent( + pointer: input, + device: 51, + kind: PointerDeviceKind.mouse, + position: position, + timeStamp: clock.elapsed, + ), + ); + GestureBinding.instance.handlePointerEvent( + PointerRemovedEvent( + pointer: input, + device: 51, + kind: PointerDeviceKind.mouse, + position: position, + ), + ); + } + + Future measure(String id, String scenario) async { + final cached = + container + .read(projectsProvider.notifier) + .cachedTimelineSession(projectId, id) != + null; + final clock = Stopwatch()..start(); + double? dataMs, uiMs, firstFrameObservedMs; + final subscription = container.listen(projectsProvider, (_, next) { + if (next.value?.timeline?.id == id && + next.value?.openingTimelineId == null) { + dataMs ??= clock.elapsedMicroseconds / 1000; + } + }); + void observeFrame(Duration _) { + final workspace = + _find((w) => w is EditorWorkspace)?.widget as EditorWorkspace?; + if (workspace?.timelineId == id) { + uiMs ??= clock.elapsedMicroseconds / 1000; + } + if (uiMs == null && clock.elapsedMilliseconds < 60000) { + SchedulerBinding.instance.addPostFrameCallback(observeFrame); + SchedulerBinding.instance.scheduleFrame(); + } + } + + SchedulerBinding.instance.addPostFrameCallback(observeFrame); + tap(id, clock); + try { + for (var i = 0; i < 3000; i++) { + final preview = container + .read(previewControllerRegistryProvider) + .cached((projectId, id)); + if (preview?.session != null && uiMs != null && dataMs != null) { + final diagnostic = await BenchDiagnostics( + preview!.session!.id, + clock, + ).read().timeout(const Duration(seconds: 2)); + if ((diagnostic['sourceSubmitted'] as num?) != null && + (diagnostic['sourceSubmitted'] as num) > 0 && + (diagnostic['presented'] as num?) != null && + (diagnostic['presented'] as num) > 0) { + firstFrameObservedMs = clock.elapsedMicroseconds / 1000; + break; + } + } + await Future.delayed(const Duration(milliseconds: 20)); + } + if (uiMs == null || dataMs == null) { + throw StateError('Switch timed out: $scenario'); + } + if (firstFrameObservedMs == null) { + final previewState = container.read( + editorPreviewProvider(projectId, id), + ); + throw StateError( + 'Native frame timed out: $scenario; ${previewState.error}\n${previewState.stackTrace}', + ); + } + rows.add({ + 'scenario': scenario, + 'timelineId': id, + 'sessionCachedBeforeClick': cached, + 'clickToUiPostFrameMs': uiMs, + 'clickToDataMs': dataMs, + 'clickToNativeFrameObservedMs': firstFrameObservedMs, + }); + await File('$output/results.json').writeAsString( + jsonEncode({ + 'projectId': projectId, + 'initialTimelineId': initial.timeline!.id, + 'inputRoute': + 'GestureBinding -> real timeline TextButton -> Projects', + 'uiClock': 'Stopwatch until target EditorWorkspace post-frame', + 'nativeClock': + '20 ms polling; cached frames are reuse, not new decode', + 'rows': rows, + }), + ); + } finally { + subscription.close(); + } + } + + if (Platform.environment['CUTDEX_TIMELINE_SWITCH_RAPID'] == '1') { + final third = initial.timelines + .firstWhere((t) => t.id != target && t.id != initial.timeline!.id) + .id; + final clock = Stopwatch()..start(); + final inputs = >[]; + final states = >[]; + var latest = initial.timeline!.id; + final subscription = container.listen(projectsProvider, (_, next) { + final value = next.value!; + states.add({ + 'ms': clock.elapsedMicroseconds / 1000, + 'latestInput': latest, + 'visible': value.visibleTimelineId, + 'loaded': value.timeline?.id, + 'pending': value.openingTimelineId, + 'error': value.error?.toString(), + }); + }); + try { + for (final id in [ + target, + initial.timeline!.id, + third, + initial.timeline!.id, + target, + ]) { + latest = id; + inputs.add({'ms': clock.elapsedMicroseconds / 1000, 'timelineId': id}); + tap(id, clock); + await Future.delayed(const Duration(milliseconds: 16)); + } + await Future.delayed(const Duration(seconds: 5)); + final finalState = container.read(projectsProvider).requireValue; + if (finalState.timeline?.id != target || + finalState.openingTimelineId != null || + finalState.error != null || + states.any((s) => s['visible'] != s['latestInput'])) { + throw StateError( + 'Rapid navigation did not preserve the latest request', + ); + } + await File('$output/rapid.json').writeAsString( + jsonEncode({ + 'inputRoute': 'GestureBinding -> real timeline tabs', + 'inputs': inputs, + 'states': states, + 'finalTimelineId': finalState.timeline!.id, + 'latestWins': true, + 'stabilityWindowMs': 5000, + }), + ); + await File('$output/done.json') + .writeAsString(jsonEncode({'complete': true})); + return; + } finally { + subscription.close(); + } + } + + await measure(target, 'cold-target'); + for (var round = 1; round <= 3; round++) { + await Future.delayed(const Duration(milliseconds: 200)); + await measure(initial.timeline!.id, 'warm-return-$round'); + await Future.delayed(const Duration(milliseconds: 200)); + await measure(target, 'warm-target-$round'); + } + await File('$output/done.json').writeAsString(jsonEncode({'complete': true})); +} diff --git a/lib/features/editor/editor_page.dart b/lib/features/editor/editor_page.dart index 0064896..7ef3ab6 100644 --- a/lib/features/editor/editor_page.dart +++ b/lib/features/editor/editor_page.dart @@ -36,11 +36,13 @@ class EditorWorkspace extends ConsumerStatefulWidget { required this.integratedTitlebar, required this.headerLeading, this.projectLoading = false, + this.timelineLoading = false, this.showProjectName = true, this.experience = DeviceExperience.desktop, }); final bool projectLoading; + final bool timelineLoading; final String projectId; final String timelineId; final String projectName; @@ -55,6 +57,7 @@ class EditorWorkspace extends ConsumerStatefulWidget { class _EditorWorkspaceState extends ConsumerState { final _previewKey = GlobalKey(); + bool get _timelinePending => widget.projectLoading || widget.timelineLoading; EditorPresentationController get _presentation => ref.read(editorPresentationProvider(widget.projectId)); ProjectViewSettingsData get _viewSettings => @@ -82,15 +85,16 @@ class _EditorWorkspaceState extends ConsumerState { child: EditorPreviewPanel( projectId: widget.projectId, timelineId: widget.timelineId, - pending: widget.projectLoading, + pending: _timelinePending, ), ); final timeline = EditorTimelinePanel( projectId: widget.projectId, timelineId: widget.timelineId, pending: widget.projectLoading, + timelineLoading: widget.timelineLoading, ); - final properties = widget.projectLoading + final properties = _timelinePending ? const EditorEmptyPanel() : EditorPropertiesPanel( projectId: widget.projectId, @@ -153,7 +157,7 @@ class _EditorWorkspaceState extends ConsumerState { ), Flexible( fit: FlexFit.loose, - child: widget.projectLoading + child: _timelinePending ? const SizedBox.shrink() : _TimelineSaveStatus( projectId: widget.projectId, @@ -288,7 +292,7 @@ class _EditorWorkspaceState extends ConsumerState { projectId: widget.projectId, ), }, - properties: widget.projectLoading + properties: _timelinePending ? properties : switch (widget.experience) { DeviceExperience.desktop => properties, diff --git a/lib/features/preview/preview_fullscreen.dart b/lib/features/preview/preview_fullscreen.dart index 9634467..16c7fb4 100644 --- a/lib/features/preview/preview_fullscreen.dart +++ b/lib/features/preview/preview_fullscreen.dart @@ -6,6 +6,7 @@ import 'package:flutter/services.dart'; import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_native/cutdex_native.dart'; +import 'package:cutdex_sdk/runtime.dart'; /// Moves the existing preview into the root overlay, retaining its native view. class PreviewFullscreenHost extends StatefulWidget { @@ -158,7 +159,7 @@ class PreviewFullscreenLayout extends StatelessWidget { borderRadius: BorderRadius.circular(AppRadius.large), ) : null, - child: toolbar, + child: NativePreviewOcclusion(child: toolbar), ), ), ], diff --git a/lib/features/preview/preview_panel.dart b/lib/features/preview/preview_panel.dart index bc4f422..14baeaa 100644 --- a/lib/features/preview/preview_panel.dart +++ b/lib/features/preview/preview_panel.dart @@ -225,29 +225,38 @@ class _EditorPreviewContent extends ConsumerWidget { listenable: activeController.positionChanges, builder: (context, _) => Theme( data: AppTheme.previewCanvasTheme, - child: - activeController.maskEditingElement != null || - activeController.obscureEditingElement != null - ? MaskInteractionOverlay( - controller: activeController, - canvasRect: rect, - obscure: - activeController.obscureEditingElement != - null, - ) - : PreviewInteractionOverlay( - onError: (error) => - ErrorNotificationHost.maybeOf(context)?.show( - ErrorNotification( - content: Text( - context.l10n.canvasTransformFailed, + child: NativePreviewOverlay( + session: activeController.session!, + enabled: + activeController.selectedVisualIds.isNotEmpty || + activeController.maskEditingElement != null || + activeController.obscureEditingElement != null, + child: + activeController.maskEditingElement != null || + activeController.obscureEditingElement != null + ? MaskInteractionOverlay( + controller: activeController, + canvasRect: rect, + obscure: + activeController.obscureEditingElement != + null, + ) + : PreviewInteractionOverlay( + onError: (error) => + ErrorNotificationHost.maybeOf( + context, + )?.show( + ErrorNotification( + content: Text( + context.l10n.canvasTransformFailed, + ), + details: error.toString(), ), - details: error.toString(), ), - ), - controller: activeController, - canvasRect: rect, - ), + controller: activeController, + canvasRect: rect, + ), + ), ), ) : null; @@ -339,7 +348,9 @@ class _EditorPreviewContent extends ConsumerWidget { return Stack( fit: StackFit.expand, children: [ - if (preview.session case final session?) + if (preview.session case final session? + when preview.error == null && + preview.durationTick > 0) RuntimePreview(session: session), ListenableSelector( listenable: Listenable.merge([ @@ -367,14 +378,17 @@ class _EditorPreviewContent extends ConsumerWidget { padding: const EdgeInsets.all( AppSpacing.medium, ), - child: Text( - context.l10n.mediaOffline( - unavailable.join(', '), + child: NativePreviewOcclusion( + child: Text( + context.l10n.mediaOffline( + unavailable.join(', '), + ), + maxLines: 2, + overflow: + TextOverflow.ellipsis, + textAlign: + TextAlign.center, ), - maxLines: 2, - overflow: - TextOverflow.ellipsis, - textAlign: TextAlign.center, ), ), ), @@ -559,7 +573,8 @@ class _SourcePreviewPanel extends ConsumerWidget { return Stack( fit: StackFit.expand, children: [ - RuntimePreview(session: session), + if (!source.audioOnly) + RuntimePreview(session: session), if (source.audioOnly) IgnorePointer( child: AudioAssetTile( diff --git a/lib/features/projects/projects_page.dart b/lib/features/projects/projects_page.dart index ff2c842..fb03e7d 100644 --- a/lib/features/projects/projects_page.dart +++ b/lib/features/projects/projects_page.dart @@ -467,9 +467,11 @@ class _EditingPageState extends ConsumerState { projectId: visibleProject.id, timelineId: displayDefaults ? '' - : state.timeline!.id, + : state.visibleTimelineId!, projectName: visibleProject.name, projectLoading: displayDefaults, + timelineLoading: + state.openingTimelineId != null, showProjectName: desktop && _mode == WorkspaceMode.cut, diff --git a/lib/features/properties/color_interpretation_properties.dart b/lib/features/properties/color_interpretation_properties.dart index 4c9314d..d973909 100644 --- a/lib/features/properties/color_interpretation_properties.dart +++ b/lib/features/properties/color_interpretation_properties.dart @@ -8,6 +8,7 @@ import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../workspace/media_color_interpretation.dart'; +import '../../shared/widgets/listenable_selector.dart'; import '../../workspace/timeline_session.dart'; import '../preview/preview_panel.dart'; @@ -95,8 +96,12 @@ class ColorInterpretationProperties extends ConsumerWidget { ); } - return ListenableBuilder( + return ListenableSelector( listenable: Listenable.merge([session, ?preview]), + select: () => ( + session.mediaColorInterpretation(assetId, trackIndex), + preview?.videoColorSpaces(assetId), + ), builder: (_, _) => contents(), ); } diff --git a/lib/features/properties/picture_properties.dart b/lib/features/properties/picture_properties.dart index f9c3284..1d0b167 100644 --- a/lib/features/properties/picture_properties.dart +++ b/lib/features/properties/picture_properties.dart @@ -16,6 +16,7 @@ import 'package:cutdex_ui/theme.dart'; import 'package:cutdex_ui/widgets.dart'; import '../../workspace/timeline_session.dart'; +import '../../shared/widgets/listenable_selector.dart'; import '../preview/preview_panel.dart'; import 'property_number_input.dart'; import 'picture_edits.dart'; @@ -43,6 +44,7 @@ class PictureProperties extends ConsumerStatefulWidget { class _PicturePropertiesState extends ConsumerState { bool _locked = true; + bool _hasFocusedControl = false; PictureEditsProvider get _editProvider => pictureEditsProvider(widget.session, widget.sequence, widget.clip.id); PictureEdits get _edits => ref.read(_editProvider.notifier); @@ -177,6 +179,43 @@ class _PicturePropertiesState extends ConsumerState { ClipAnimation? _animation() => _edits.animation(); ClipTransform? _current() => _animation()?.value; + + Object _presentation(PreviewController? preview) { + final view = widget.session.view(widget.sequence); + final animation = _animation(); + final live = preview?.activeSequence() == widget.sequence + ? preview?.transforms.valueFor(widget.clip.id) + : null; + final value = + (_scrubValid ? _scrubTimeline : null) ?? + live ?? + animation?.value ?? + ClipTransform.fromRecord(widget.clip); + final timeDependent = + widget.animationView || + TransformChannel.values.any( + (channel) => animation?.animated(channel) == true, + ); + return ( + widget.session.activeSequenceId, + view.version.kernelVersion, + widget.session.canvas, + animation?.containsPlayhead, + timeDependent || _hasFocusedControl ? animation?.playhead : null, + value.x, + value.y, + value.scale, + value.scaleY, + value.rotation, + _scrubValid, + _scrubBase != null, + _saving, + _error, + preview?.aspectRatioLocked ?? _locked, + preview?.transforms.hasPending == true && _scrubEdit == null, + ); + } + Future _editKeys( PreviewController? preview, TransformChannel channel, { @@ -216,7 +255,7 @@ class _PicturePropertiesState extends ConsumerState { final value = (_scrubValid ? _scrubTimeline : null) ?? live ?? - _current() ?? + animation?.value ?? ClipTransform.fromRecord(widget.clip); final locked = preview?.aspectRatioLocked ?? _locked; final canvas = widget.session.canvas; @@ -627,12 +666,20 @@ class _PicturePropertiesState extends ConsumerState { ); } - return ListenableBuilder( - listenable: Listenable.merge([ - widget.session.view(widget.sequence), - if (preview != null) ...[preview, preview.transforms], - ]), - builder: (_, _) => contents(), + return Focus( + onFocusChange: (focused) { + if (mounted && focused != _hasFocusedControl) { + setState(() => _hasFocusedControl = focused); + } + }, + child: ListenableSelector( + listenable: Listenable.merge([ + widget.session.view(widget.sequence), + if (preview != null) ...[preview, preview.transforms], + ]), + select: () => _presentation(preview), + builder: (_, _) => contents(), + ), ); } } diff --git a/lib/features/properties/properties_inspector_controller.dart b/lib/features/properties/properties_inspector_controller.dart index 1778735..524ef9a 100644 --- a/lib/features/properties/properties_inspector_controller.dart +++ b/lib/features/properties/properties_inspector_controller.dart @@ -24,22 +24,49 @@ class PropertiesInspectorController extends ChangeNotifier { PropertiesInspectorController(this.session) { session.addListener(_sessionChanged); _bindView(); + _captureSelection(); } final EditorTimelineSession session; Listenable? _editingChanges; + SequenceId? _lastSequence; + Object? _lastVersion; + Set _lastSelection = {}; SequenceId? get sequence => session.activeSequenceId; void _bindView() { final id = sequence; final next = id == null ? null : session.view(id).editingChanges; if (identical(next, _editingChanges)) return; - _editingChanges?.removeListener(notifyListeners); + _editingChanges?.removeListener(_viewChanged); _editingChanges = next; - _editingChanges?.addListener(notifyListeners); + _editingChanges?.addListener(_viewChanged); + } + + bool _captureSelection() { + final id = sequence; + final view = id == null ? null : session.view(id); + final version = view?.version.kernelVersion; + final selected = view?.selectedIdentities ?? const {}; + if (id == _lastSequence && + identical(version, _lastVersion) && + setEquals(selected, _lastSelection)) { + return false; + } + _lastSequence = id; + _lastVersion = version; + _lastSelection = selected.toSet(); + return true; + } + + void _viewChanged() { + // The inspector's selection shell does not depend on the playhead. Its + // property editors subscribe separately to position and live edit changes. + if (_captureSelection()) notifyListeners(); } void _sessionChanged() { _bindView(); + _captureSelection(); notifyListeners(); } @@ -66,7 +93,7 @@ class PropertiesInspectorController extends ChangeNotifier { @override void dispose() { session.removeListener(_sessionChanged); - _editingChanges?.removeListener(notifyListeners); + _editingChanges?.removeListener(_viewChanged); super.dispose(); } } diff --git a/lib/features/timeline/timeline_panel.dart b/lib/features/timeline/timeline_panel.dart index 2ca2cb9..fc30d0a 100644 --- a/lib/features/timeline/timeline_panel.dart +++ b/lib/features/timeline/timeline_panel.dart @@ -37,10 +37,12 @@ class EditorTimelinePanel extends StatelessWidget { required this.projectId, required this.timelineId, this.pending = false, + this.timelineLoading = false, }); final String projectId; final String timelineId; final bool pending; + final bool timelineLoading; @override Widget build(BuildContext context) => Theme( @@ -56,10 +58,15 @@ class EditorTimelinePanel extends StatelessWidget { ), const Divider(height: 1), Expanded( - child: _TimelineSessionContent( - projectId: projectId, - timelineId: timelineId, - ), + child: timelineLoading + ? const EditorTimelineDefaults( + key: Key('timeline-pending'), + showTabs: false, + ) + : _TimelineSessionContent( + projectId: projectId, + timelineId: timelineId, + ), ), ], ), @@ -183,7 +190,11 @@ class _TimelineTabsBarState extends ConsumerState<_TimelineTabsBar> { (ref.read(projectsProvider).value?.projectBusy ?? false); Future _openTimeline(TimelineSummary timeline) async { - if (_operationsBusy || timeline.id == widget.timelineId) return; + if (widget.creating || + (ref.read(projectsProvider).value?.projectBusy ?? false) || + timeline.id == widget.timelineId) { + return; + } await ref .read(projectsProvider.notifier) .openTimeline(widget.projectId, timeline.id); @@ -798,6 +809,13 @@ class _TimelineEditorState extends State<_TimelineEditor> { ], ), const Spacer(), + _toolbarButton( + key: const ValueKey('timeline-fit'), + tooltip: context.l10n.fitTimeline, + semanticLabel: context.l10n.fitTimeline, + onPressed: controller.fitTimeline, + icon: Icons.fit_screen, + ), if (controller.commandRejection != null) Tooltip( message: controller.commandRejection!, diff --git a/lib/main.dart b/lib/main.dart index 1eebd31..20de216 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -7,6 +7,9 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'app/app.dart'; import 'diagnostics/frame_timings.dart'; +import 'diagnostics/full_app_viewport_bench.dart'; +import 'diagnostics/timeline_switch_bench.dart'; +import 'diagnostics/timeline_gesture_bench.dart'; import 'diagnostics/app_diagnostics.dart'; import 'integrations/platform/device_experience.dart'; @@ -29,4 +32,7 @@ Future main() async { child: const CutdexApp(), ), ); + startFullAppViewportBenchFromEnvironment(); + startTimelineSwitchBenchFromEnvironment(); + startTimelineGestureBenchFromEnvironment(); } diff --git a/lib/workspace/project_state.dart b/lib/workspace/project_state.dart index c93b512..0108298 100644 --- a/lib/workspace/project_state.dart +++ b/lib/workspace/project_state.dart @@ -39,3 +39,8 @@ abstract class ProjectState with _$ProjectState { AppFailure? error, }) = _ProjectState; } + +extension ProjectTimelineSelection on ProjectState { + /// Navigation intent is visible before its editing session is ready. + String? get visibleTimelineId => openingTimelineId ?? timeline?.id; +} diff --git a/lib/workspace/projects.dart b/lib/workspace/projects.dart index 9ff098f..4739948 100644 --- a/lib/workspace/projects.dart +++ b/lib/workspace/projects.dart @@ -43,6 +43,10 @@ class Projects extends _$Projects { late ProjectWorkspace _workspace; bool _workspaceReady = false; + int _timelineNavigation = 0; + (String, String)? _pendingTimelineIds; + Future? _pendingTimeline; + Future _rememberTimelineTail = Future.value(); AppLocalizations get _localizations { final configured = ref.read(languageSettingsProvider).asData?.value; @@ -169,8 +173,13 @@ class Projects extends _$Projects { Future _perform(Future Function() action) async { await future; if (!ref.mounted || state.requireValue.projectBusy) return false; + _timelineNavigation++; state = AsyncData( - state.requireValue.copyWith(projectBusy: true, error: null), + state.requireValue.copyWith( + projectBusy: true, + openingTimelineId: null, + error: null, + ), ); try { await action(); @@ -267,11 +276,7 @@ class Projects extends _$Projects { } checkCurrent(); if (selectedDocument != null) { - await _prepareTimeline( - active.id, - selectedDocument, - preparePreview: false, - ); + await _prepareTimeline(active.id, selectedDocument); } checkCurrent(); await ref @@ -657,9 +662,8 @@ class Projects extends _$Projects { Future _prepareTimeline( String projectId, - TimelineDocument document, { - bool preparePreview = true, - }) async { + TimelineDocument document, + ) async { final session = await _workspace.openTimelineSession(projectId, document); await TimelineViewStateBinding.prepare( projectId: projectId, @@ -667,17 +671,8 @@ class Projects extends _$Projects { session: session, repository: ref.read(timelineViewSettingsRepositoryProvider), ); - // The preview panel owns asynchronous startup after project publication. - // Cached controllers still bind synchronously when revisiting a project. - if (!preparePreview) return session; - try { - await ref.read(previewControllerRegistryProvider).prepare(( - projectId, - document.id, - ), session); - } catch (error, stackTrace) { - AppDiagnostics.failure('preview', 'prepare', error, stackTrace); - } + // The preview panel starts decoding after publication. Editing and + // navigation must never wait for native preview initialization. return session; } @@ -689,16 +684,52 @@ class Projects extends _$Projects { return _workspace.leaseTimeline(projectId, timelineId); } - Future openTimeline(String projectId, String timelineId) async { - await future; - final current = state.requireValue; + Future openTimeline(String projectId, String timelineId) { + final ids = (projectId, timelineId); + if (_pendingTimelineIds == ids && + _pendingTimeline != null && + state.value?.openingTimelineId == timelineId) { + return _pendingTimeline!; + } + final pending = _openTimeline(projectId, timelineId); + _pendingTimelineIds = ids; + _pendingTimeline = pending; + void clearPending() { + if (identical(_pendingTimeline, pending)) { + _pendingTimeline = null; + _pendingTimelineIds = null; + } + } + + unawaited( + pending.then( + (_) => clearPending(), + onError: (Object _, StackTrace _) => clearPending(), + ), + ); + return pending; + } + + bool _isTimelineNavigationCurrent(int navigation, String projectId) => + ref.mounted && + navigation == _timelineNavigation && + state.value?.activeProject?.id == projectId; + + Future _openTimeline(String projectId, String timelineId) async { + final current = state.value ?? await future; if (current.projectBusy || current.creatingTimeline || - current.openingTimelineId != null || current.activeProject?.id != projectId) { return false; } - if (current.timeline?.id == timelineId) return true; + if (!current.timelines.any((timeline) => timeline.id == timelineId)) { + return false; + } + if (current.timeline?.id == timelineId && + current.openingTimelineId == null) { + return true; + } + final navigation = ++_timelineNavigation; final cachedTimeline = _workspace.cachedTimelineDocument( projectId, timelineId, @@ -707,11 +738,17 @@ class Projects extends _$Projects { projectId, timelineId, ); - if (cachedTimeline != null && cachedSession != null) { + if (cachedTimeline != null && + cachedSession != null && + TimelineViewStateBinding.isPrepared(cachedSession)) { state = AsyncData( - current.copyWith(timeline: cachedTimeline, error: null), + current.copyWith( + timeline: cachedTimeline, + openingTimelineId: null, + error: null, + ), ); - await _rememberTimeline(projectId, timelineId); + await _rememberTimeline(projectId, timelineId, navigation: navigation); return true; } state = AsyncData( @@ -719,18 +756,19 @@ class Projects extends _$Projects { ); try { final timeline = await _workspace.loadTimeline(projectId, timelineId); + if (!_isTimelineNavigationCurrent(navigation, projectId)) return false; await _prepareTimeline(projectId, timeline); - if (!ref.mounted) return true; + if (!_isTimelineNavigationCurrent(navigation, projectId)) return false; state = AsyncData( state.requireValue.copyWith( timeline: timeline, openingTimelineId: null, ), ); - await _rememberTimeline(projectId, timelineId); + await _rememberTimeline(projectId, timelineId, navigation: navigation); return true; } catch (error) { - if (ref.mounted) { + if (_isTimelineNavigationCurrent(navigation, projectId)) { state = AsyncData( state.requireValue.copyWith( openingTimelineId: null, @@ -742,20 +780,34 @@ class Projects extends _$Projects { } } - Future _rememberTimeline(String projectId, String timelineId) async { - try { - await ref - .read(recentProjectsProvider) - .rememberTimeline(projectId, timelineId); - } catch (_) { - if (ref.mounted) { - state = AsyncData( - state.requireValue.copyWith( - error: const AppFailure(AppErrorCode.lastProjectSaveFailed), - ), - ); + Future _rememberTimeline( + String projectId, + String timelineId, { + int? navigation, + }) { + bool isCurrent() => + ref.mounted && + state.value?.activeProject?.id == projectId && + state.value?.timeline?.id == timelineId && + state.value?.openingTimelineId == null && + (navigation == null || navigation == _timelineNavigation); + // Serialize preferences so an older in-flight write cannot finish last. + return _rememberTimelineTail = _rememberTimelineTail.then((_) async { + if (!isCurrent()) return; + try { + await ref + .read(recentProjectsProvider) + .rememberTimeline(projectId, timelineId); + } catch (_) { + if (isCurrent()) { + state = AsyncData( + state.requireValue.copyWith( + error: const AppFailure(AppErrorCode.lastProjectSaveFailed), + ), + ); + } } - } + }); } AppFailure _failureFor(Object error) => projectFailureFromError(error); diff --git a/lib/workspace/timeline_view_state.dart b/lib/workspace/timeline_view_state.dart index 43c52a4..0d5a5b1 100644 --- a/lib/workspace/timeline_view_state.dart +++ b/lib/workspace/timeline_view_state.dart @@ -8,6 +8,10 @@ import 'timeline_session.dart'; /// Keeps local timeline navigation out of the authored project document. final class TimelineViewStateBinding { static final _initialized = Expando(); + static final _preparing = Expando>(); + + static bool isPrepared(EditorTimelineSession session) => + _initialized[session] == true; TimelineViewStateBinding._( this.projectId, @@ -21,16 +25,21 @@ final class TimelineViewStateBinding { required String timelineId, required EditorTimelineSession session, required TimelineViewSettingsRepository repository, - }) async { - if (_initialized[session] == true) return; - var saved = const TimelineViewState(); - try { - saved = await repository.load(projectId, timelineId); - } catch (_) { - // Corrupt or unavailable local UI state must not block the timeline. - } - _restore(session, saved); - _initialized[session] = true; + }) { + if (isPrepared(session)) return Future.value(); + final pending = _preparing[session]; + if (pending != null) return pending; + return _preparing[session] = () async { + var saved = const TimelineViewState(); + try { + saved = await repository.load(projectId, timelineId); + } catch (_) { + // Corrupt or unavailable local UI state must not block the timeline. + } + _restore(session, saved); + _initialized[session] = true; + _preparing[session] = null; + }(); } static FutureOr attach({ diff --git a/lib/workspace/workspace_session_scope.dart b/lib/workspace/workspace_session_scope.dart index 77e8ccd..b85cea2 100644 --- a/lib/workspace/workspace_session_scope.dart +++ b/lib/workspace/workspace_session_scope.dart @@ -22,7 +22,9 @@ class WorkspaceSessionScope extends ConsumerWidget { Widget build(BuildContext context, WidgetRef ref) { final projectId = state.activeProject?.id; final timelineId = state.timeline?.id; - if (projectId != null && timelineId != null) { + if (projectId != null && + timelineId != null && + state.openingTimelineId == null) { ref.watch(editorTimelineProvider(projectId, timelineId)); } final selection = ref.watch(conversationSelectionProvider(projectId)); diff --git a/packages/cutdex_native/windows/cutdex_native_plugin.cpp b/packages/cutdex_native/windows/cutdex_native_plugin.cpp index 8197c53..f77f309 100644 --- a/packages/cutdex_native/windows/cutdex_native_plugin.cpp +++ b/packages/cutdex_native/windows/cutdex_native_plugin.cpp @@ -2,15 +2,36 @@ #include namespace cutdex_native { +namespace { +class LiveMessenger final : public flutter::BinaryMessenger { + public: + explicit LiveMessenger(flutter::PluginRegistrarWindows* registrar, FlutterDesktopMessengerRef core) + : messenger_(registrar->messenger()), + core_(FlutterDesktopMessengerAddRef(core)) {} + ~LiveMessenger() override { FlutterDesktopMessengerRelease(core_); } + void Send(const std::string& channel, const uint8_t* message, size_t size, + flutter::BinaryReply reply = nullptr) const override { + if (FlutterDesktopMessengerIsAvailable(core_)) messenger_->Send(channel, message, size, std::move(reply)); + else if (reply) reply(nullptr, 0); + } + void SetMessageHandler(const std::string& channel, flutter::BinaryMessageHandler handler) override { + if (FlutterDesktopMessengerIsAvailable(core_)) messenger_->SetMessageHandler(channel, std::move(handler)); + } + private: + flutter::BinaryMessenger* messenger_; + FlutterDesktopMessengerRef core_; +}; +} void CutdexNativePlugin::RegisterWithRegistrar( - flutter::PluginRegistrarWindows* registrar) { - registrar->AddPlugin(std::make_unique(registrar)); + flutter::PluginRegistrarWindows* registrar, FlutterDesktopMessengerRef core) { + registrar->AddPlugin(std::make_unique(registrar, core)); } -CutdexNativePlugin::CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar) +CutdexNativePlugin::CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar, FlutterDesktopMessengerRef core) : registrar_(registrar) { + messenger_ = std::make_unique(registrar, core); device_info_ = std::make_unique>( - registrar->messenger(), "cutdex_native/device_info", + messenger_.get(), "cutdex_native/device_info", &flutter::StandardMethodCodec::GetInstance()); device_info_->SetMethodCallHandler([](const auto& call, auto result) { if (call.method_name() != "getApplicationInfo") { @@ -23,8 +44,8 @@ CutdexNativePlugin::CutdexNativePlugin(flutter::PluginRegistrarWindows* registra }); const HWND view = registrar->GetView()->GetNativeWindow(); chrome_ = std::make_unique( - GetAncestor(view, GA_ROOT), view, registrar->messenger()); - drop_ = std::make_unique(view, registrar->messenger()); + GetAncestor(view, GA_ROOT), view, messenger_.get()); + drop_ = std::make_unique(view, messenger_.get()); delegate_id_ = registrar->RegisterTopLevelWindowProcDelegate( [this](HWND, UINT message, WPARAM wparam, LPARAM lparam) -> std::optional { diff --git a/packages/cutdex_native/windows/cutdex_native_plugin.h b/packages/cutdex_native/windows/cutdex_native_plugin.h index 1bbcc74..4b1d7a8 100644 --- a/packages/cutdex_native/windows/cutdex_native_plugin.h +++ b/packages/cutdex_native/windows/cutdex_native_plugin.h @@ -9,14 +9,15 @@ namespace cutdex_native { class CutdexNativePlugin : public flutter::Plugin { public: - static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar); - explicit CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar); + static void RegisterWithRegistrar(flutter::PluginRegistrarWindows* registrar, FlutterDesktopMessengerRef core); + explicit CutdexNativePlugin(flutter::PluginRegistrarWindows* registrar, FlutterDesktopMessengerRef core); ~CutdexNativePlugin() override; CutdexNativePlugin(const CutdexNativePlugin&) = delete; CutdexNativePlugin& operator=(const CutdexNativePlugin&) = delete; private: flutter::PluginRegistrarWindows* registrar_; int delegate_id_; + std::unique_ptr messenger_; std::unique_ptr chrome_; std::unique_ptr drop_; std::unique_ptr> device_info_; diff --git a/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp b/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp index de3a45f..c03e01e 100644 --- a/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp +++ b/packages/cutdex_native/windows/cutdex_native_plugin_c_api.cpp @@ -8,5 +8,5 @@ void CutdexNativePluginCApiRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { cutdex_native::CutdexNativePlugin::RegisterWithRegistrar( flutter::PluginRegistrarManager::GetInstance() - ->GetRegistrar(registrar)); + ->GetRegistrar(registrar), FlutterDesktopPluginRegistrarGetMessenger(registrar)); } diff --git a/pubspec.lock b/pubspec.lock index f37b818..1c6f846 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -214,8 +214,8 @@ packages: dependency: transitive description: path: "packages/editor" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -223,8 +223,8 @@ packages: dependency: transitive description: path: "packages/mcp" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -232,8 +232,8 @@ packages: dependency: transitive description: path: "packages/preview" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -241,8 +241,8 @@ packages: dependency: transitive description: path: "packages/project" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -250,8 +250,8 @@ packages: dependency: transitive description: path: "packages/runtime" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.0.1" @@ -259,8 +259,8 @@ packages: dependency: "direct main" description: path: "." - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -268,8 +268,8 @@ packages: dependency: transitive description: path: "packages/timeline" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.2.0" @@ -277,8 +277,8 @@ packages: dependency: transitive description: path: "packages/timeline_ui" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -286,8 +286,8 @@ packages: dependency: transitive description: path: "packages/tools" - ref: de676503a60fb276bc645da89d0b1e8369d2d434 - resolved-ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" + resolved-ref: "650b8c73a9424c8f1ce3a6fd8235af93a8698401" url: "ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git" source: git version: "0.1.0" @@ -303,8 +303,8 @@ packages: dependency: "direct main" description: path: "." - ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd - resolved-ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd + ref: "0190a19a11c0ed60914dd993d0483950efb07e45" + resolved-ref: "0190a19a11c0ed60914dd993d0483950efb07e45" url: "https://github.com/lingjhf/deskup.git" source: git version: "0.3.0" diff --git a/pubspec.yaml b/pubspec.yaml index 08149cb..1ae7980 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -16,7 +16,7 @@ dependencies: deskup: git: url: https://github.com/lingjhf/deskup.git - ref: ccbeb02ed1bbf6b4388981a0e641aff7404637bd + ref: 0190a19a11c0ed60914dd993d0483950efb07e45 flutter: sdk: flutter @@ -28,7 +28,7 @@ dependencies: cutdex_sdk: git: url: ssh://git@git.orangraph.com:2222/lingjhf/cutdex_sdk.git - ref: de676503a60fb276bc645da89d0b1e8369d2d434 + ref: 650b8c73a9424c8f1ce3a6fd8235af93a8698401 cutdex_agent: git: url: https://github.com/cutdex-ai/cutdex_agent.git diff --git a/test/diagnostics/full_app_viewport_bench/workload_test.dart b/test/diagnostics/full_app_viewport_bench/workload_test.dart new file mode 100644 index 0000000..43fde12 --- /dev/null +++ b/test/diagnostics/full_app_viewport_bench/workload_test.dart @@ -0,0 +1,109 @@ +import 'package:cutdex/diagnostics/full_app_viewport_bench/config.dart'; +import 'package:cutdex/diagnostics/full_app_viewport_bench/workload.dart'; +import 'package:flutter_test/flutter_test.dart'; + +ViewportBenchConfig config([Map values = const {}]) => + ViewportBenchConfig.fromEnvironment({ + 'CUTDEX_FULL_APP_VIEWPORT_BENCH': 'benchmark-output', + 'CUTDEX_FULL_APP_VIEWPORT_PAIRED': '1', + ...values.map( + (key, value) => MapEntry('CUTDEX_FULL_APP_VIEWPORT_$key', value), + ), + }); + +void main() { + group('Full editor benchmark inputs', () { + test('existing MIDE trajectory and six-second schedule stay unchanged', () { + final workloads = ViewportBenchWorkload.forTimeline( + config({'LOCAL_START_FRAME': '60137', 'EXPECTED_FRAMES': '214073.82'}), + 214073.82, + ); + final wide = workloads[0], local = workloads[1]; + expect(wide.count, 360); + expect(wide.hz, 60); + expect(wide.durationMs, 6000); + expect( + [ + wide.idealFrame(0), + wide.idealFrame(179), + wide.idealFrame(180), + wide.idealFrame(359), + ], + [10704, 203370, 203370, 10704], + ); + expect( + [ + local.idealFrame(0), + local.idealFrame(20), + local.idealFrame(21), + local.idealFrame(39), + local.idealFrame(359), + ], + [60137, 60157, 60156, 60138, 60138], + ); + expect(local.cameraBaseFrame, 60120); + expect(local.warmFrame, 60136); + }); + + test( + 'another timeline derives local targets without a media-specific length', + () { + final workloads = ViewportBenchWorkload.forTimeline(config(), 10000); + expect(workloads[1].idealFrame(0), 2800); + expect(workloads[1].idealFrame(20), 2820); + expect(config().expectedFrames, isNull); + expect(config().nativeOnly, isTrue); + expect(config().captureHelper, isNull); + }, + ); + + test('rate, frame count and local span can change without escaping the timeline', () { + final workloads = ViewportBenchWorkload.forTimeline( + config({ + 'INPUT_HZ': '120', + 'INPUT_COUNT': '720', + 'LOCAL_START_FRAME': '100', + 'LOCAL_SPAN_FRAMES': '8', + }), + 10000, + ); + for (final workload in workloads) { + expect(workload.durationMs, 6000); + for (var i = 0; i < workload.count; i++) { + expect(workload.idealFrame(i), inInclusiveRange(0, 9999)); + } + } + expect(workloads[1].idealFrame(8), 108); + expect(workloads[1].idealFrame(9), 107); + }); + + test( + 'invalid settings fail before starting native capture or a gesture', + () { + expect(() => config({'INPUT_HZ': '0'}), throwsArgumentError); + expect(() => config({'INPUT_COUNT': '359'}), throwsArgumentError); + expect( + () => config({'LOCAL_PIXELS_PER_FRAME': 'NaN'}), + throwsArgumentError, + ); + expect(() => config({'ROUNDS': 'oops'}), throwsFormatException); + expect(() => config({'PAIRED': 'yes'}), throwsArgumentError); + expect(() => config({'NATIVE_ONLY': '0'}), throwsArgumentError); + expect( + () => ViewportBenchWorkload.forTimeline( + config({'LOCAL_START_FRAME': '9990'}), + 10000, + ), + throwsStateError, + ); + expect( + () => ViewportBenchWorkload.forTimeline( + config({'EXPECTED_FRAMES': '20000'}), + 10000, + ), + throwsStateError, + ); + }, + ); + }); +} diff --git a/test/properties_preview_updates_test.dart b/test/properties_preview_updates_test.dart new file mode 100644 index 0000000..c111274 --- /dev/null +++ b/test/properties_preview_updates_test.dart @@ -0,0 +1,146 @@ +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/properties/picture_properties.dart'; +import 'package:cutdex/features/properties/properties_inspector_controller.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'support/preview_fixture.dart'; + +void main() { + testWidgets('cursor changes preserve inspector selection subscriptions', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture(Uri.file('/test/video.mov')), + ))!; + addTearDown( + () => tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }), + ); + final inspector = PropertiesInspectorController(f.timeline); + addTearDown(inspector.dispose); + final view = f.timeline.view(SequenceId('one')); + final clip = view.version.kernelVersion.query().elementById( + ElementId('clip'), + )!; + var notifications = 0; + inspector.addListener(() => notifications++); + view.setSelection([clip]); + expect(inspector.selectedClips.single.id, ElementId('clip')); + final selectedCount = notifications; + view.beginScrubbing(); + for (var i = 1; i <= 120; i++) { + view.seekTo(i * TimelineClock.ticksPerSecond ~/ 120); + } + view.endScrubbing(); + expect(notifications, selectedCount); + view.clearSelection(); + expect(notifications, greaterThan(selectedCount)); + expect(inspector.selectedClips, isEmpty); + f.timeline.selectSequence(SequenceId('empty')); + expect(inspector.sequence, SequenceId('empty')); + final switchedCount = notifications; + view.setSelection([clip]); + expect( + notifications, + switchedCount, + reason: 'Old sequence listener is detached', + ); + }); + + testWidgets('static controls stay stable and discard edits after a seek', ( + tester, + ) async { + final f = (await tester.runAsync( + () => createPreviewFixture( + Uri.file('/test/video.mov'), + clipDuration: RationalTime.seconds(5), + ), + ))!; + addTearDown( + () => tester.runAsync(() async { + await f.workspace.close(); + await f.directory.delete(recursive: true); + }), + ); + final view = f.timeline.view(SequenceId('one')); + final project = f.workspace.project!.info.id; + ClipAnimation current() { + final query = view.version.kernelVersion.query(); + return ClipAnimation.at( + query, + query.elementById(ElementId('clip'))!, + view.playheadTick, + TimelineClock.ticksPerSecond ~/ 30, + ); + } + + await tester.pumpWidget( + ProviderScope( + overrides: [ + editorPreviewProvider( + project, + 'project', + ).overrideWith((ref) async => throw StateError('No native preview')), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penLight, + home: Scaffold( + body: SizedBox( + width: 280, + child: SingleChildScrollView( + child: PictureProperties( + projectId: project, + timelineId: 'project', + session: f.timeline, + sequence: SequenceId('one'), + clip: current().record, + ), + ), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final input = find.descendant( + of: find.byKey(const ValueKey('picture-x')), + matching: find.byType(TextField), + ); + final initial = tester.widget(input); + view.seekTo(TimelineClock.ticksPerSecond); + await tester.pump(); + expect(tester.widget(input), same(initial)); + await tester.ensureVisible(input); + await tester.enterText(input, '999'); + await tester.pump(); + view.seekTo(2 * TimelineClock.ticksPerSecond); + await tester.pump(); + await tester.testTextInput.receiveAction(TextInputAction.done); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(current().value.x, 0); + await tester.ensureVisible( + find.byKey(const ValueKey('picture-key-position')), + ); + await tester.tap(find.byKey(const ValueKey('picture-key-position'))); + await tester.pump(); + await tester.runAsync(f.timeline.flush); + await tester.pumpAndSettle(); + expect(current().keyTimes(TransformChannel.position), [ + 2 * TimelineClock.ticksPerSecond, + ]); + expect(tester.takeException(), isNull); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/test/workspace/timeline_navigation_test.dart b/test/workspace/timeline_navigation_test.dart new file mode 100644 index 0000000..94da6d1 --- /dev/null +++ b/test/workspace/timeline_navigation_test.dart @@ -0,0 +1,372 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/features/editor/editor_page.dart'; +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/integrations/platform/device_experience.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/persistence/app_settings_repositories.dart'; +import 'package:cutdex/workspace/preview_target.dart'; +import 'package:cutdex/workspace/project_state.dart'; +import 'package:cutdex/workspace/projects.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex/workspace/persistence/recent_projects.dart'; +import 'package:cutdex_sdk/project.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import '../support/memory_app_settings.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late Directory root; + late ProviderContainer container; + late Projects projects; + late String projectId; + late _ViewSettings views; + late _RecentProjects recent; + final nativeCalls = []; + const native = MethodChannel('timeline-navigation-test'); + + Future initialize() async { + root = await Directory.systemTemp.createTemp('cutdex-navigation-'); + views = _ViewSettings(); + recent = _RecentProjects(); + nativeCalls.clear(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(native, (call) async { + nativeCalls.add(call.method); + throw StateError('Preview must not be initialized by navigation'); + }); + final path = '${root.path}/Project.cutdex'; + final file = await ProjectFile.create( + Directory(path), + name: 'Project', + initialTimeline: _document('a'), + ); + projectId = file.info.id; + await file.saveTimeline(_document('b', content: true)); + await file.saveTimeline(_document('c')); + await file.close(); + container = ProviderContainer( + overrides: [ + deviceExperienceProvider.overrideWithValue(DeviceExperience.desktop), + recentProjectsProvider.overrideWithValue(recent), + resourceLocationSettingsRepositoryProvider.overrideWithValue( + MemoryResourceLocationSettingsRepository(root.path), + ), + timelineViewSettingsRepositoryProvider.overrideWithValue(views), + runtimeConnectionProvider.overrideWithValue( + CutdexRuntime(channel: native), + ), + ], + ); + projects = container.read(projectsProvider.notifier); + expect(await projects.open(path, timelineId: 'a'), isTrue); + } + + Future dispose() async { + for (final gate in views.gates.values) { + if (!gate.isCompleted) gate.complete(const TimelineViewState()); + } + if (recent.writeGate case final gate?) { + if (!gate.isCompleted) gate.complete(); + } + await projects.prepareToQuit(); + container.dispose(); + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(native, null); + await root.delete(recursive: true); + } + + group('navigation controller', () { + setUp(initialize); + tearDown(dispose); + + test( + 'content selection completes without any native preview initialization', + () async { + expect(await projects.openTimeline(projectId, 'b'), isTrue); + expect(container.read(projectsProvider).requireValue.timeline!.id, 'b'); + expect(nativeCalls, isEmpty); + }, + ); + + test( + 'latest cold navigation wins despite reverse completion order', + () async { + final bGate = views.block('b'); + final b = projects.openTimeline(projectId, 'b'); + expect( + container.read(projectsProvider).requireValue.visibleTimelineId, + 'b', + ); + await views.started('b'); + expect(projects.openTimeline(projectId, 'b'), same(b)); + final cGate = views.block('c'); + final c = projects.openTimeline(projectId, 'c'); + expect( + container.read(projectsProvider).requireValue.visibleTimelineId, + 'c', + ); + await views.started('c'); + cGate.complete(const TimelineViewState()); + expect(await c, isTrue); + bGate.complete(const TimelineViewState()); + expect(await b, isFalse); + final state = container.read(projectsProvider).requireValue; + expect(state.timeline!.id, 'c'); + expect(state.openingTimelineId, isNull); + expect(state.error, isNull); + expect(recent.projects[projectId], 'c'); + }, + ); + + test( + 'returning to a partially prepared cache waits for one restore', + () async { + final gate = views.block('b'); + final old = projects.openTimeline(projectId, 'b'); + await views.started('b'); + expect(await projects.openTimeline(projectId, 'a'), isTrue); + final latest = projects.openTimeline(projectId, 'b'); + await Future.delayed(Duration.zero); + expect( + container.read(projectsProvider).requireValue.openingTimelineId, + 'b', + ); + expect(container.read(projectsProvider).requireValue.timeline!.id, 'a'); + gate.complete(const TimelineViewState()); + expect(await old, isFalse); + expect(await latest, isTrue); + expect(views.loads.where((id) => id == 'b'), hasLength(1)); + expect(container.read(projectsProvider).requireValue.timeline!.id, 'b'); + }, + ); + + test('project navigation supersedes a blocked timeline', () async { + final gate = views.block('b'); + final old = projects.openTimeline(projectId, 'b'); + await views.started('b'); + expect( + await projects.open('${root.path}/Other.cutdex', name: 'Other'), + isTrue, + ); + final other = container + .read(projectsProvider) + .requireValue + .activeProject! + .id; + gate.complete(const TimelineViewState()); + expect(await old, isFalse); + expect( + container.read(projectsProvider).requireValue.activeProject!.id, + other, + ); + expect( + container.read(projectsProvider).requireValue.openingTimelineId, + isNull, + ); + }); + + test( + 'slow failed preference write cannot overwrite latest selection or error', + () async { + recent.writeGate = Completer(); + recent.blockId = 'b'; + final b = projects.openTimeline(projectId, 'b'); + await recent.writeStarted.future; + final c = projects.openTimeline(projectId, 'c'); + await views.started('c'); + await Future.delayed(const Duration(milliseconds: 10)); + expect(container.read(projectsProvider).requireValue.timeline!.id, 'c'); + recent.writeGate!.completeError(StateError('old write failed')); + expect(await b, isTrue); + expect(await c, isTrue); + expect(recent.projects[projectId], 'c'); + expect(container.read(projectsProvider).requireValue.error, isNull); + }, + ); + }); + + test( + 'startup failure is returned once without an unhandled cleanup future', + () async { + final failedContainer = ProviderContainer( + overrides: [projectsProvider.overrideWith(_FailingProjects.new)], + ); + addTearDown(failedContainer.dispose); + final failed = failedContainer.read(projectsProvider.notifier); + await expectLater(failed.openTimeline('project', 'a'), throwsA(anything)); + await Future.delayed(Duration.zero); + }, + ); + + testWidgets('pending tabs accept a newer real click', (tester) async { + final widgetContainer = ProviderContainer( + overrides: [projectsProvider.overrideWith(_PendingProjects.new)], + ); + addTearDown(widgetContainer.dispose); + await tester.pumpWidget( + UncontrolledProviderScope( + container: widgetContainer, + child: MaterialApp( + theme: EditorTheme.penDark, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: Consumer( + builder: (context, ref, _) { + final state = ref.watch(projectsProvider).value; + if (state == null) return const SizedBox(); + return EditorWorkspace( + projectId: 'project', + timelineId: state.visibleTimelineId!, + projectName: 'Project', + integratedTitlebar: false, + headerLeading: const SizedBox(), + timelineLoading: true, + ); + }, + ), + ), + ), + ), + ); + await tester.pump(); + expect(find.byKey(const Key('timeline-pending')), findsOneWidget); + expect( + widgetContainer.exists(editorTimelineProvider('project', 'b')), + isFalse, + ); + final panel = tester.widget( + find.byType(EditorTimelinePanel), + ); + expect(panel.timelineId, 'b'); + await tester.tap(find.byKey(const ValueKey('timeline-tab-c'))); + await tester.pump(); + expect( + widgetContainer.read(projectsProvider).requireValue.visibleTimelineId, + 'c', + ); + expect( + tester + .widget(find.byType(EditorTimelinePanel)) + .timelineId, + 'c', + ); + await tester.pumpWidget(const SizedBox()); + }); +} + +TimelineDocument _document(String id, {bool content = false}) => + TimelineDocument( + id: id, + name: id, + defaultSequenceId: SequenceId('sequence-$id'), + sequences: [ + TimelineDto( + id: SequenceId('sequence-$id'), + name: id, + format: TimelineFormat.fps30, + primaryStorylineId: StorylineId('primary-$id'), + storylines: [ + StorylineDto( + id: StorylineId('primary-$id'), + elementIds: [if (content) ElementId('clip')], + ), + ], + elements: [ + if (content) + ElementDto( + id: ElementId('clip'), + name: 'Clip', + structure: ElementStructure.content, + payloadRef: PayloadRef('source'), + duration: RationalTime.seconds(2), + sourceRange: TimeRange( + start: RationalTime.zero, + duration: RationalTime.seconds(2), + ), + ), + ], + ), + ], + payloads: [ + if (content) + PayloadDocument(id: 'source', type: 'video', assetIds: [], data: {}), + ], + ); + +class _ViewSettings implements TimelineViewSettingsRepository { + final gates = >{}; + final signals = >{}; + final loads = []; + Completer block(String id) => + gates[id] = Completer(); + Future started(String id) => (signals[id] ??= Completer()).future; + @override + Future load(String projectId, String timelineId) async { + loads.add(timelineId); + (signals[timelineId] ??= Completer()).complete(); + return gates[timelineId]?.future ?? const TimelineViewState(); + } + + @override + Future save( + String projectId, + String timelineId, + SequenceId sequenceId, + TimelineSequenceViewState state, + ) async {} +} + +class _RecentProjects extends MemoryRecentProjectsRepository { + Completer? writeGate; + final writeStarted = Completer(); + String? blockId; + @override + Future rememberTimeline(String projectId, String timelineId) async { + if (timelineId == blockId) { + writeStarted.complete(); + await writeGate!.future; + } + await super.rememberTimeline(projectId, timelineId); + } +} + +class _PendingProjects extends Projects { + @override + Future build() async => ProjectState( + activeProject: const RecentProject( + id: 'project', + name: 'Project', + path: '/Project.cutdex', + ), + timeline: _document('a'), + openingTimelineId: 'b', + timelines: const [ + TimelineSummary(id: 'a', name: 'a', revision: 0), + TimelineSummary(id: 'b', name: 'b', revision: 0), + TimelineSummary(id: 'c', name: 'c', revision: 0), + ], + ); + + @override + Future openTimeline(String projectId, String timelineId) async { + state = AsyncData( + state.requireValue.copyWith(openingTimelineId: timelineId), + ); + return true; + } +} + +class _FailingProjects extends Projects { + @override + Future build() async => throw StateError('startup failed'); +} diff --git a/tool/windows/native_preview_bench.dart b/tool/windows/native_preview_bench.dart new file mode 100644 index 0000000..d31b5da --- /dev/null +++ b/tool/windows/native_preview_bench.dart @@ -0,0 +1,883 @@ +// Development entry point: real editor panels, project persistence, timeline +// cursor, PreviewController, RuntimeSession and the installed Windows plugin. +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:cutdex/app/editor_theme.dart'; +import 'package:cutdex/features/preview/preview_panel.dart'; +import 'package:cutdex/features/preview/preview_fullscreen.dart'; +import 'package:cutdex/features/properties/properties_panel.dart'; +import 'package:cutdex/features/timeline/timeline_panel.dart'; +import 'package:cutdex/l10n/app_localizations.dart'; +import 'package:cutdex/workspace/timeline_provider.dart'; +import 'package:cutdex_sdk/editor.dart'; +import 'package:cutdex_sdk/preview.dart'; +import 'package:cutdex_sdk/runtime.dart'; +import 'package:cutdex_sdk/timeline/model.dart'; +import 'package:cutdex_sdk/timeline/layout.dart'; +import 'package:cutdex_sdk/timeline_ui.dart'; +import 'package:flutter/gestures.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../../test/support/preview_fixture.dart'; + +final _transportClock = Stopwatch()..start(); +final _transport = >[]; + +class _ObservedChannel extends MethodChannel { + const _ObservedChannel() : super('cutdex_runtime'); + @override + Future invokeMethod(String method, [dynamic arguments]) async { + final begin = _transportClock.elapsedMicroseconds / 1000; + final value = await super.invokeMethod(method, arguments); + if (method == 'previewOverlay') { + final rgba = arguments['rgba'] as Uint8List?; + _transport.add({ + 'method': method, + 'left': arguments['left'], + 'top': arguments['top'], + 'width': arguments['width'], + 'height': arguments['height'], + 'alphaPixels': rgba == null + ? 0 + : [ + for (var i = 3; i < rgba.length; i += 4) + if (rgba[i] > 0) i, + ].length, + 'blueCenterRows': rgba == null + ? [] + : [ + for (var y = 0; y < (arguments['height'] as int); y++) + if (rgba[(y * (arguments['width'] as int) + + (arguments['width'] as int) ~/ 2) * + 4] < + 35 && + rgba[(y * (arguments['width'] as int) + + (arguments['width'] as int) ~/ 2) * + 4 + + 1] > + 100 && + rgba[(y * (arguments['width'] as int) + + (arguments['width'] as int) ~/ 2) * + 4 + + 2] > + 220 && + rgba[(y * (arguments['width'] as int) + + (arguments['width'] as int) ~/ 2) * + 4 + + 3] > + 220) + y, + ], + 'beginMs': begin, + 'returnMs': _transportClock.elapsedMicroseconds / 1000, + }); + } + if (method == 'request') { + final request = jsonDecode(arguments['request'] as String) as Map; + _transport.add({ + 'method': request['method'], + if (request['method'] == 'load' || request['method'] == 'applySnapshot') + 'plan': request['plan'], + 'time': request['time'], + 'beginMs': begin, + 'returnMs': _transportClock.elapsedMicroseconds / 1000, + }); + } + return value; + } +} + +void main(List args) async { + WidgetsFlutterBinding.ensureInitialized(); + final output = Directory(args.length > 1 ? args[1] : 'native-preview-bench'); + await output.create(recursive: true); + final mode = args.isEmpty ? 'native' : args[0]; + try { + final source = Platform.environment['CUTDEX_BENCH_SOURCE']; + final frames = int.tryParse( + Platform.environment['CUTDEX_BENCH_DURATION_FRAMES'] ?? '', + ); + if (source == null || source.isEmpty || frames == null || frames <= 0) { + throw ArgumentError( + 'Set CUTDEX_BENCH_SOURCE and a positive CUTDEX_BENCH_DURATION_FRAMES ' + '(duration at 30 Hz).', + ); + } + final fixture = await createPreviewFixture( + File(source).uri, + clipDuration: RationalTime(frames, 30), + renderSize: {'width': 1280, 'height': 720}, + ); + final preview = PreviewController( + timeline: fixture.timeline, + activeSequence: () => fixture.timeline.activeSequenceId, + viewForSequence: fixture.timeline.view, + runtime: CutdexRuntime(channel: const _ObservedChannel()), + ); + await preview.initialize(); + if (preview.error != null) throw preview.error!; + if (preview.session!.nativePreview != (mode == 'native')) { + throw StateError( + 'Wrong presenter: ${preview.session!.nativePreview}, requested $mode', + ); + } + final ids = (fixture.workspace.project!.info.id, 'project'); + runApp( + ProviderScope( + overrides: [ + editorTimelineProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => fixture.timeline), + editorPreviewProvider( + ids.$1, + ids.$2, + ).overrideWith((ref) async => preview), + ], + child: MaterialApp( + debugShowCheckedModeBanner: false, + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + locale: const Locale('zh'), + theme: EditorTheme.penDark, + home: _BenchPage( + preview: preview, + ids: ids, + output: output, + mode: mode, + cleanup: () async { + await preview.close(); + await fixture.workspace.close(); + await fixture.directory.delete(recursive: true); + }, + ), + ), + ), + ); + } catch (error, stack) { + await File('${output.path}/error.txt').writeAsString('$error\n$stack'); + exit(1); + } +} + +class _BenchPage extends StatefulWidget { + const _BenchPage({ + required this.preview, + required this.ids, + required this.output, + required this.mode, + required this.cleanup, + }); + final PreviewController preview; + final (String, String) ids; + final Directory output; + final String mode; + final Future Function() cleanup; + @override + State<_BenchPage> createState() => _BenchPageState(); +} + +class _BenchPageState extends State<_BenchPage> { + static const channel = MethodChannel('cutdex_runtime'); + final editor = GlobalKey(); + final clock = Stopwatch()..start(); + double offset = 0; + double now() => offset + clock.elapsedMicroseconds / 1000; + Future sleep(int ms) => + Future.delayed(Duration(milliseconds: ms)); + Future until(double due) async { + for (;;) { + final remaining = due - now(); + if (remaining <= 0) return; + await Future.delayed( + Duration(microseconds: (remaining * 1000).ceil()), + ); + } + } + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) => unawaited(run())); + } + + Future run() async { + Process? capture; + int pid = 0; + IOSink? inputs, phases, events; + try { + await sleep(1000); + final diagnostics = await channel.invokeMapMethod( + 'previewDiagnostics', + {'sessionId': widget.preview.session!.id}, + ); + pid = diagnostics!['pid'] as int; + final helper = Platform.environment['CUTDEX_BENCH_CAPTURE_HELPER']; + if (helper == null || helper.isEmpty) { + throw ArgumentError('Set CUTDEX_BENCH_CAPTURE_HELPER.'); + } + final layout = await Process.run(helper, ['layout', '$pid']); + if (layout.exitCode != 0) { + throw StateError('Set benchmark window layout: ${layout.exitCode}'); + } + await sleep(700); + if (Platform.environment['CUTDEX_FUNCTIONAL'] == '1') { + await functional(helper, pid); + return; + } + final selected = Platform.environment['CUTDEX_BENCH_SELECTED'] == '1'; + if (selected) { + widget.preview.selectVisual(widget.preview.visuals.first.elementId); + await sleep(350); + } + double uncertainty = double.infinity; + for (var i = 0; i < 20; i++) { + final begin = clock.elapsedMicroseconds / 1000; + final d = await channel.invokeMapMethod( + 'previewDiagnostics', + {'sessionId': widget.preview.session!.id}, + ); + final end = clock.elapsedMicroseconds / 1000; + if (end - begin < uncertainty) { + uncertainty = end - begin; + offset = (d!['qpcMs'] as double) - (begin + end) / 2; + } + } + Element? element; + void visit(Element e) { + if (e.widget is RuntimePreview) element = e; + e.visitChildElements(visit); + } + + visit(editor.currentContext! as Element); + final box = element!.findRenderObject()! as RenderBox; + final rect = box.localToGlobal(Offset.zero) & box.size; + if (!mounted) return; + final scale = View.of(context).devicePixelRatio; + capture = await Process.start(helper, [ + widget.output.path, + '$pid', + '${(rect.left * scale).round()}', + '${(rect.top * scale).round()}', + '${(rect.width * scale).round()}', + '${(rect.height * scale).round()}', + ]); + unawaited(capture.stdout.drain()); + unawaited(capture.stderr.drain()); + final ready = File('${widget.output.path}/capture-ready'); + for (var i = 0; !await ready.exists() && i < 500; i++) { + await sleep(10); + } + if (!await ready.exists()) { + throw StateError('Desktop capture did not start'); + } + inputs = File('${widget.output.path}/inputs.csv').openWrite(); + phases = File('${widget.output.path}/phases.csv').openWrite(); + events = File('${widget.output.path}/events.csv').openWrite(); + inputs.writeln('scenario,index,target,qpc_ms,scheduled_ms,request_ms'); + phases.writeln( + 'scenario,start_ms,end_ms,release_begin_ms,release_return_ms,final_frame,final_clock_frame,freeze_end_ms', + ); + events.writeln('qpc_ms,kind,version'); + final preview = widget.preview; + final sequence = SequenceId('one'); + final view = preview.viewForSequence(sequence); + final viewportDrag = Platform.environment['CUTDEX_VIEWPORT_BENCH'] == '1'; + final uniformPixels = + Platform.environment['CUTDEX_VIEWPORT_UNIFORM'] == '1'; + RenderBox? ruler; + final viewportDetails = {}; + if (viewportDrag) { + void findRuler(Element e) { + if (e.widget is TimelineRuler) { + ruler = e.findRenderObject()! as RenderBox; + } + e.visitChildElements(findRuler); + } + + (context as Element).visitChildElements(findRuler); + if (ruler == null) throw StateError('Missing real timeline ruler'); + view.fitTimeline(); + await sleep(700); + final viewport = TimelineViewportRect( + width: ruler!.size.width, + height: ruler!.size.height, + ); + final startX = view.camera.screenXForTick(0, viewport); + final endX = view.camera.screenXForTick(view.contentEndTick, viewport); + if (startX < 0 || endX > viewport.width) { + throw StateError( + 'Entire clip is not visible: $startX..$endX / ${viewport.width}', + ); + } + final origin = ruler!.localToGlobal(Offset.zero); + viewportDetails.addAll({ + 'ruler': [ + origin.dx, + origin.dy, + ruler!.size.width, + ruler!.size.height, + ], + 'clipStartX': startX, + 'clipEndX': endX, + 'clipFrames': 215533, + 'clipFillsViewportFraction': (endX - startX) / viewport.width, + 'baseTick': view.camera.baseTick, + 'pixelsPerTick': view.camera.pixelsPerTick, + 'targetSpacing': uniformPixels + ? 'uniform screen positions rounded to physical pixels, then source frames' + : 'exact 60-second jumps', + 'physicalPixelInput': uniformPixels, + 'inputRoute': 'GestureBinding mouse pointer down/move/up -> actual TimelineViewport playhead handle -> production preview', + }); + } + int tick(int frame) => + TimelineClock.standard.toTicks(RationalTime(frame, 30)); + Future seek(int frame) => preview.controlPreview( + sequence, + PreviewAction.seek, + at: CommandTime(frame, 30), + ); + final snapshots = >[]; + final stageDiagnostics = >[]; + await sleep(700); + for (var s = 0; s < 5; s++) { + final hz = viewportDrag + ? [60, 120, 60, 120, 240][s] + : s == 0 + ? 30 + : s == 3 + ? 120 + : 60; + final count = viewportDrag + ? [120, 120, 360, 720, 1440][s] + : s == 0 + ? 90 + : s == 3 + ? 360 + : s == 4 + ? 120 + : 180; + int targetIndex(int i) => s == 0 + ? i + : s == 1 + ? 119 - i + : i % 238 < 120 + ? i % 238 + : 238 - i % 238; + int idealTarget(int i) => viewportDrag + ? uniformPixels + ? (900 * 119 + 213733 * targetIndex(i) + 59) ~/ 119 + : 900 + 1800 * targetIndex(i) + : switch (s) { + 0 => 60000 + i, + 1 => 60000 + i * 30, + 2 => 66000 - i * 30, + 3 => 60000 + (i % 120 < 60 ? i % 120 : 120 - i % 120) * 60 + i, + _ => 900 + i * 1800, + }; + final cameraBefore = view.camera; + final warmFrame = idealTarget(0) - 1; + final pixelsPerFrame = view.camera.pixelsPerTick * tick(1); + int physicalDelta(int i) => + ((idealTarget(i) - warmFrame) * pixelsPerFrame * scale).round(); + int target(int i) => uniformPixels && viewportDrag + ? (warmFrame + physicalDelta(i) / (pixelsPerFrame * scale)).round() + : idealTarget(i); + final viewport = ruler == null + ? null + : TimelineViewportRect( + width: ruler!.size.width, + height: ruler!.size.height, + ); + Offset point(int frame) => ruler!.localToGlobal( + Offset( + view.camera.screenXForTick(tick(frame), viewport!), + ruler!.size.height / 2, + ), + ); + final pointer = 100 + s; + Offset? pointerPosition; + Offset? uniformOrigin; + double pointerBias = 0; + Offset inputPoint(int i) => uniformPixels + ? uniformOrigin! + Offset(physicalDelta(i) / scale, 0) + : point(target(i)) + Offset(pointerBias, 0); + void move(Offset position) { + GestureBinding.instance.handlePointerEvent( + PointerMoveEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + buttons: kPrimaryButton, + position: position, + delta: position - pointerPosition!, + timeStamp: clock.elapsed, + ), + ); + pointerPosition = position; + } + + await seek(warmFrame); + if (viewportDrag) { + // Adopt the seek in the positioned handle before hit-testing. + // DragStartBehavior.start consumes initial drag slop; retain that + // pointer-to-playhead offset in subsequent measured movements. + await sleep(50); + pointerPosition = point(warmFrame); + if (uniformPixels) { + pointerPosition = Offset( + (pointerPosition!.dx * scale).round() / scale, + (pointerPosition!.dy * scale).round() / scale, + ); + } + GestureBinding.instance.handlePointerEvent( + PointerAddedEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: pointerPosition!, + ), + ); + GestureBinding.instance.handlePointerEvent( + PointerDownEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + buttons: kPrimaryButton, + position: pointerPosition!, + timeStamp: clock.elapsed, + ), + ); + move(pointerPosition! + const Offset(40, 0)); + await sleep(20); + if (!view.isScrubbing || view.playheadTick != tick(warmFrame)) { + throw StateError( + 'Expected actual playhead handle to accept drag without consuming warmup slop', + ); + } + pointerBias = pointerPosition!.dx - point(warmFrame).dx; + uniformOrigin = pointerPosition; + move(inputPoint(0)); + if (!view.isScrubbing || view.playheadTick != tick(target(0))) { + throw StateError( + 'Playhead drag not established: scrubbing=${view.isScrubbing}, tick=${view.playheadTick}, expected=${tick(target(0))}, viewport=$viewportDetails', + ); + } + } else { + view.beginScrubbing(); + // A distinct cursor update exercises the production begin-skimming path. + view.seekTo(tick(target(0) - 2)); + } + await sleep(350); + final diagBefore = await channel.invokeMapMethod( + 'previewDiagnostics', + {'sessionId': preview.session!.id}, + ); + final start = now(); + for (var i = 0; i < count; i++) { + final due = start + 1000 * i / hz; + await until(due); + final begin = now(); + if (viewportDrag) { + move(inputPoint(i)); + if (!view.isScrubbing || view.playheadTick != tick(target(i))) { + throw StateError('Pointer target mismatch at $s/$i'); + } + } else { + view.seekTo(tick(target(i))); + } + final returned = now(); + inputs.writeln('$s,$i,${target(i)},$begin,$due,${returned - begin}'); + } + await until(start + 1000 * count / hz); + final end = now(); + double? pointerReleaseReturn; + double? pointerReleaseBegin; + if (viewportDrag) { + final transportOffset = + now() - _transportClock.elapsedMicroseconds / 1000; + final transportStart = _transport.length; + pointerReleaseBegin = now(); + GestureBinding.instance.handlePointerEvent( + PointerUpEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: pointerPosition!, + timeStamp: clock.elapsed, + ), + ); + if (view.isScrubbing || !identical(cameraBefore, view.camera)) { + throw StateError('Drag did not end or camera scrolled'); + } + for (var retry = 0; retry < 5000; retry++) { + final replies = _transport + .skip(transportStart) + .where((r) => r['method'] == 'endSkimming') + .toList(); + if (replies.isNotEmpty) { + pointerReleaseReturn = + (replies.last['returnMs'] as num).toDouble() + + transportOffset; + break; + } + if (preview.error != null) throw preview.error!; + await sleep(1); + } + if (pointerReleaseReturn == null) { + throw StateError('Production release did not complete'); + } + GestureBinding.instance.handlePointerEvent( + PointerRemovedEvent( + pointer: pointer, + device: 42, + kind: PointerDeviceKind.mouse, + position: pointerPosition!, + ), + ); + } + final diagAfter = await channel.invokeMapMethod( + 'previewDiagnostics', + {'sessionId': preview.session!.id}, + ); + stageDiagnostics.add({ + 'scenario': s, + 'before': diagBefore, + 'after': diagAfter, + }); + final releaseBegin = pointerReleaseBegin ?? now(); + if (!viewportDrag) { + view.endScrubbing(); + await seek(target(count - 1)); + } + final releaseReturn = pointerReleaseReturn ?? now(); + await sleep(700); + final snapshot = await preview.session!.refresh(); + final actual = + snapshot.position.numerator * 30 / snapshot.position.denominator; + if ((actual - target(count - 1)).abs() > .01) { + throw StateError('Final clock $actual'); + } + snapshots.add({ + 'scenario': s, + 'actual': actual, + 'state': snapshot.state.name, + }); + phases.writeln( + '$s,$start,$end,$releaseBegin,$releaseReturn,${target(count - 1)},$actual,${now()}', + ); + if (preview.error != null) throw preview.error!; + } + await seek(60000); + await sleep(350); + final playBegin = now(); + await preview.controlPreview(sequence, PreviewAction.play); + final playReturn = now(); + await sleep(2000); + final pauseBegin = now(); + await preview.controlPreview(sequence, PreviewAction.pause); + final pauseReturn = now(); + await sleep(700); + await File('${widget.output.path}/playback.json').writeAsString( + jsonEncode({ + 'playBeginMs': playBegin, + 'playReturnMs': playReturn, + 'pauseBeginMs': pauseBegin, + 'pauseReturnMs': pauseReturn, + 'freezeEndMs': now(), + }), + ); + await File('${widget.output.path}/capture-stop').writeAsString('stop'); + final captureCode = await capture.exitCode.timeout( + const Duration(seconds: 10), + ); + if (captureCode != 0) throw StateError('Capture exit $captureCode'); + final captureMeta = jsonDecode( + await File('${widget.output.path}/capture.json').readAsString(), + ) as Map; + await File('${widget.output.path}/meta.json').writeAsString( + jsonEncode({ + ...captureMeta, + 'mode': widget.mode, + 'selectedVisual': selected, + if (viewportDrag) 'viewportDrag': viewportDetails, + if (viewportDrag) 'referenceScope': 'full', + if (viewportDrag) + 'scenarioNames': [ + 'viewport-forward-60Hz', + 'viewport-reverse-120Hz', + 'viewport-backforth-60Hz', + 'viewport-backforth-120Hz', + 'viewport-backforth-240Hz', + ], + 'clockMeasured': true, + 'clockSyncRoundtripMs': uncertainty, + 'pixelRatio': scale, + 'scope': 'Cutdex editor preview, timeline, properties; persisted project; real cursor/controller/plugin', + 'status': 'passed', + 'diagnostics': stageDiagnostics, + 'snapshots': snapshots, + }), + ); + } catch (error, stack) { + await File('${widget.output.path}/error.txt') + .writeAsString('$error\n$stack'); + await File('${widget.output.path}/capture-stop').writeAsString('stop'); + if (capture != null) await capture.exitCode; + } finally { + await inputs?.close(); + await phases?.close(); + await events?.close(); + await File('${widget.output.path}/transport.json') + .writeAsString(jsonEncode(_transport)); + final cleanup = widget.cleanup; + runApp(const ProviderScope(child: SizedBox.shrink())); + await sleep(150); + debugPrint('BENCH cleanup begin'); + await cleanup(); + debugPrint('BENCH cleanup done'); + final helper = Platform.environment['CUTDEX_BENCH_CAPTURE_HELPER']; + if (helper != null && helper.isNotEmpty && pid > 0) { + await Process.run(helper, ['close', '$pid']); + } + } + } + + Element runtimeElement() { + Element? result; + void visit(Element e) { + if (e.widget is RuntimePreview) result = e; + e.visitChildElements(visit); + } + + editor.currentContext!.visitChildElements(visit); + if (result == null) throw StateError('Missing real RuntimePreview'); + return result!; + } + + Future functional(String helper, int pid) async { + final preview = widget.preview; + final checks = {}; + Future> diag() async => + (await channel.invokeMapMethod('previewDiagnostics', { + 'sessionId': preview.session!.id, + }))!; + Future> pixel(Offset logical) async { + final scale = View.of(context).devicePixelRatio; + final r = await Process.run(helper, [ + 'pixel', + '$pid', + '${(logical.dx * scale).round()}', + '${(logical.dy * scale).round()}', + ]); + if (r.exitCode != 0) throw StateError('Pixel capture failed'); + return (jsonDecode(r.stdout as String) as List).cast(); + } + + Rect rect() { + final box = runtimeElement().findRenderObject()! as RenderBox; + return box.localToGlobal(Offset.zero) & box.size; + } + + List bounds(Rect r) => [r.left, r.top, r.width, r.height]; + + void require(bool condition, String name, Object? value) { + checks[name] = value; + if (!condition) { + File('${widget.output.path}/functional-diagnostics.json') + .writeAsStringSync(jsonEncode(checks)); + throw StateError('Functional check $name: $value'); + } + } + + await preview.controlPreview( + SequenceId('one'), + PreviewAction.seek, + at: CommandTime(60000, 30), + ); + await sleep(350); + final original = rect(); + preview.selectVisual(preview.visuals.first.elementId); + await sleep(700); + final uploads = _transport + .where( + (r) => + r['method'] == 'previewOverlay' && (r['alphaPixels'] as int) > 0, + ) + .toList(); + require( + uploads.isNotEmpty, + 'selectedOverlayUpload', + uploads.isEmpty ? null : uploads.last, + ); + final lastUpload = uploads.last; + final row = (lastUpload['blueCenterRows'] as List)[1]; + if (!mounted) throw StateError('Editor unmounted during functional check'); + final ratio = View.of(context).devicePixelRatio; + final selectedPoint = Offset( + ((lastUpload['left'] as int) + (lastUpload['width'] as int) ~/ 2) / ratio, + ((lastUpload['top'] as int) + row) / ratio, + ); + checks['selectedPoint'] = [selectedPoint.dx, selectedPoint.dy]; + checks['selectedNative'] = await diag(); + final selectedNative = checks['selectedNative'] as Map; + final nativeBounds = (selectedNative['nativeScreenBounds'] as List) + .cast(); + require( + selectedPoint.dy * ratio + (selectedNative['screenTop'] as int) >= + nativeBounds[1], + 'selectedSampleInsideNative', + true, + ); + final selected = await pixel(selectedPoint); + require( + selected[2] > 220 && selected[1] > 100 && selected[0] < 35, + 'selectedOutlineRgb', + selected, + ); + await Process.run(helper, ['layout', '$pid', '1400', '980']); + await sleep(700); + final resized = rect(); + require(resized.width < original.width, 'resizeBounds', { + 'before': bounds(original), + 'after': bounds(resized), + 'native': await diag(), + }); + final upload = _transport.lastWhere( + (r) => r['method'] == 'previewOverlay' && (r['alphaPixels'] as int) > 0, + ); + final resizedColor = await pixel( + Offset( + ((upload['left'] as int) + (upload['width'] as int) ~/ 2) / ratio, + ((upload['top'] as int) + (upload['blueCenterRows'] as List)[1]) / + ratio, + ), + ); + require( + resizedColor[2] > 220 && resizedColor[0] < 35, + 'resizedOutlineRgb', + resizedColor, + ); + preview.selectVisual(null); + await sleep(350); + final center = await pixel(resized.center); + final greenRect = Rect.fromLTWH( + resized.left + 30, + resized.top + 30, + 80, + 40, + ); + final entry = OverlayEntry( + builder: (_) => Positioned.fromRect( + rect: greenRect, + child: const ColoredBox(color: Color(0xff00ff00)), + ), + ); + Overlay.of(runtimeElement()).insert(entry); + await sleep(350); + final green = await pixel(greenRect.center); + require( + green[1] > 240 && green[0] < 10 && green[2] < 10, + 'menuOcclusionRgb', + green, + ); + final stillVideo = await pixel(resized.center); + require( + List.generate( + 3, + (i) => (stillVideo[i] - center[i]).abs(), + ).every((d) => d < 6), + 'menuKeepsSurroundingVideo', + stillVideo, + ); + entry.remove(); + entry.dispose(); + await sleep(350); + final restored = await pixel(greenRect.center); + require( + restored.toString() != green.toString(), + 'menuRestoresVideoRgb', + restored, + ); + PreviewFullscreenScope.of(runtimeElement())!.toggle!(); + await sleep(700); + final full = rect(); + final fullscreenVideo = await pixel(full.center); + require( + List.generate( + 3, + (i) => (fullscreenVideo[i] - center[i]).abs(), + ).every((d) => d < 6), + 'fullscreenShowsPausedFrame', + fullscreenVideo, + ); + require(full.width > resized.width, 'fullscreenBounds', { + 'rect': bounds(full), + 'native': await diag(), + }); + final scope = PreviewFullscreenScope.of(runtimeElement())!; + require(scope.fullscreen, 'fullscreenScope', scope.fullscreen); + scope.toggle!(); + await sleep(700); + require( + (rect().width - resized.width).abs() < 1, + 'exitFullscreenBounds', + bounds(rect()), + ); + await Process.run(helper, ['layout', '$pid']); + await sleep(500); + await File('${widget.output.path}/meta.json').writeAsString( + jsonEncode({ + 'mode': widget.mode, + 'status': 'passed', + 'functional': checks, + 'diagnostics': await diag(), + }), + ); + } + + @override + Widget build(BuildContext context) => Scaffold( + body: Center( + child: SizedBox( + width: 1240, + child: Row( + children: [ + Expanded( + child: Column( + children: [ + Expanded( + child: EditorPreviewPanel( + key: editor, + projectId: widget.ids.$1, + timelineId: widget.ids.$2, + ), + ), + SizedBox( + height: 160, + child: EditorTimelinePanel( + projectId: widget.ids.$1, + timelineId: widget.ids.$2, + ), + ), + ], + ), + ), + SizedBox( + width: 240, + child: EditorPropertiesPanel( + projectId: widget.ids.$1, + timelineId: widget.ids.$2, + ), + ), + ], + ), + ), + ), + ); +} diff --git a/windows/runner/main.cpp.in b/windows/runner/main.cpp.in index ea5e94b..e5fc71b 100644 --- a/windows/runner/main.cpp.in +++ b/windows/runner/main.cpp.in @@ -6,13 +6,9 @@ #include "flutter_window.h" #include "utils.h" -// Hybrid graphics drivers consult these process-wide hints before Flutter or -// native media creates a D3D device. Keep both texture producers on the same -// preferred adapter; explicit Windows graphics preferences still take priority. -extern "C" { -__declspec(dllexport) DWORD NvOptimusEnablement = 1; -__declspec(dllexport) int AmdPowerXpressRequestHighPerformance = 1; -} +// Windows chooses the default adapter. The native preview matches the GPU that +// produced its shared frame; forcing a discrete GPU can make seeks slower and +// require a cross-adapter transfer to the desktop compositor on hybrid systems. int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { @@ -30,6 +26,14 @@ int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); flutter::DartProject project(L"data"); + // Prefer a fast UI GPU without forcing the video decoder onto that adapter. + // On hybrid systems the two workloads can otherwise delay each other's fences. + // The internal texture comparison needs Flutter's default adapter to import + // the legacy shared video texture; this is not a user-facing mode switch. + wchar_t comparison[2]{}; + if (!GetEnvironmentVariableW(L"CUTDEX_PREVIEW_TEXTURE", comparison, 2) || comparison[0] != L'1') { + project.set_gpu_preference(flutter::GpuPreference::HighPerformancePreference); + } std::vector command_line_arguments = GetCommandLineArguments();