perf(editor): native Windows preview and UI-first timeline navigation (#11)
Gitea CI / Check code and tests (push) Successful in 8m7s
Gitea CI / Build Windows x64 app (push) Successful in 5m48s
Gitea CI / Build Android APK (push) Successful in 5m59s
Gitea CI / Audit and package Windows x64 (push) Successful in 1m17s
Gitea CI / Assemble and validate CI artifacts (push) Successful in 1m22s
Gitea CI / Gitea CI passed (push) Successful in 2s

This commit was merged in pull request #11.
This commit is contained in:
lingjhf committed 2026-10-07 10:05:14 +00:00
1 parent 0ecf920669
commit b4cb12cbe3
36 files changed
+3292 -148

No files matched your search

@@ -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<void> _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');
}
}
@@ -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`;素材及桌面捕获工具保留在仓库外。
@@ -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<BenchCapture?> 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<void>());
unawaited(process.stderr.drain<void>());
final capture = BenchCapture._(output, process);
for (
var i = 0;
!await File('${output.path}/capture-ready').exists() && i < 500;
i++
) {
await Future<void>.delayed(const Duration(milliseconds: 10));
}
if (!await File('${output.path}/capture-ready').exists()) {
await capture.stop();
throw StateError('Capture not ready');
}
return capture;
}
Future<void> 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;
}
}
}
@@ -0,0 +1,89 @@
/// Explicit inputs for the opt-in full-editor benchmark.
class ViewportBenchConfig {
ViewportBenchConfig.fromEnvironment(Map<String, String> 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<String, Object?> 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<String, String> env, String key, int fallback) =>
_optionalInteger(env, key) ?? fallback;
static int? _optionalInteger(Map<String, String> env, String key) {
final value = env['CUTDEX_FULL_APP_VIEWPORT_$key'];
return value == null ? null : int.parse(value);
}
static double? _number(Map<String, String> 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<String, String> 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'),
};
}
}
@@ -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<void>? _pending;
Object? _sampleError;
double now() => _offset + clock.elapsedMicroseconds / 1000;
Future<Map<String, dynamic>> read() async =>
(await _channel.invokeMapMethod<String, dynamic>('previewDiagnostics', {
'sessionId': sessionId,
}))!;
Future<void> 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<void> until(double due) async {
while (now() < due) {
await Future<void>.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<void> _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<void> stopSamples() async {
_timer?.cancel();
await _pending;
check();
}
}
@@ -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<void> 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<void>.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;
}
}
@@ -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<void>? _closing;
final stages = <Map<String, Object?>>[], checks = <Map<String, Object?>>[];
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<void> progress(int round) =>
File('${output.path}/progress.json')
.writeAsString(jsonEncode({'completedRounds': round}));
Future<void> complete(Map<String, Object?> metadata) =>
File('${output.path}/meta.json').writeAsString(
jsonEncode({
...metadata,
'nativeDiagnostics': stages,
'checks': checks,
}),
);
Future<void> close() => _closing ??= _close();
Future<void> _close() async {
await samples.close();
await inputs.close();
await phases.close();
}
}
@@ -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<void> _sleep(int ms) => Future<void>.delayed(Duration(milliseconds: ms));
/// Orchestrates existing editor state, real input, exact-stop validation and output.
Future<void> 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();
}
}
}
}
@@ -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<ViewportBenchWorkload> 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,
);
});
}
}
+220
View File
@@ -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<void> _run(String output) async {
await Directory(output).create(recursive: true);
await Future<void>.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 = <Map<String, Object?>>[];
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<void>.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<void>.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}));
}
+311
View File
@@ -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<void> _run(String output) async {
await Directory(output).create(recursive: true);
final gate = Platform.environment['CUTDEX_TIMELINE_SWITCH_GATE'];
await Future<void>.delayed(const Duration(seconds: 6));
if (gate != null) {
for (var i = 0; !await File(gate).exists() && i < 600; i++) {
await Future<void>.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<void>.delayed(const Duration(milliseconds: 20));
}
if (!ready) throw StateError('Initial preview is not ready');
}
final rows = <Map<String, Object?>>[];
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<void> 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<void>.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 = <Map<String, Object?>>[];
final states = <Map<String, Object?>>[];
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<void>.delayed(const Duration(milliseconds: 16));
}
await Future<void>.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<void>.delayed(const Duration(milliseconds: 200));
await measure(initial.timeline!.id, 'warm-return-$round');
await Future<void>.delayed(const Duration(milliseconds: 200));
await measure(target, 'warm-target-$round');
}
await File('$output/done.json').writeAsString(jsonEncode({'complete': true}));
}
+8 -4
View File
@@ -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<EditorWorkspace> {
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<EditorWorkspace> {
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<EditorWorkspace> {
),
Flexible(
fit: FlexFit.loose,
child: widget.projectLoading
child: _timelinePending
? const SizedBox.shrink()
: _TimelineSaveStatus(
projectId: widget.projectId,
@@ -288,7 +292,7 @@ class _EditorWorkspaceState extends ConsumerState<EditorWorkspace> {
projectId: widget.projectId,
),
},
properties: widget.projectLoading
properties: _timelinePending
? properties
: switch (widget.experience) {
DeviceExperience.desktop => properties,
+2 -1
View File
@@ -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),
),
),
],
+45 -30
View File
@@ -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(
+3 -1
View File
@@ -467,9 +467,11 @@ class _EditingPageState extends ConsumerState<EditingPage> {
projectId: visibleProject.id,
timelineId: displayDefaults
? ''
: state.timeline!.id,
: state.visibleTimelineId!,
projectName: visibleProject.name,
projectLoading: displayDefaults,
timelineLoading:
state.openingTimelineId != null,
showProjectName:
desktop &&
_mode == WorkspaceMode.cut,
@@ -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(),
);
}
@@ -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<PictureProperties> {
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<PictureProperties> {
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<void> _editKeys(
PreviewController? preview,
TransformChannel channel, {
@@ -216,7 +255,7 @@ class _PicturePropertiesState extends ConsumerState<PictureProperties> {
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<PictureProperties> {
);
}
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<Object>(
listenable: Listenable.merge([
widget.session.view(widget.sequence),
if (preview != null) ...[preview, preview.transforms],
]),
select: () => _presentation(preview),
builder: (_, _) => contents(),
),
);
}
}
@@ -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<Object> _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 <Object>{};
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();
}
}
+23 -5
View File
@@ -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<void> _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!,
+6
View File
@@ -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<void> main() async {
child: const CutdexApp(),
),
);
startFullAppViewportBenchFromEnvironment();
startTimelineSwitchBenchFromEnvironment();
startTimelineGestureBenchFromEnvironment();
}
+5
View File
@@ -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;
}
+96 -44
View File
@@ -43,6 +43,10 @@ class Projects extends _$Projects {
late ProjectWorkspace _workspace;
bool _workspaceReady = false;
int _timelineNavigation = 0;
(String, String)? _pendingTimelineIds;
Future<bool>? _pendingTimeline;
Future<void> _rememberTimelineTail = Future<void>.value();
AppLocalizations get _localizations {
final configured = ref.read(languageSettingsProvider).asData?.value;
@@ -169,8 +173,13 @@ class Projects extends _$Projects {
Future<bool> _perform(Future<void> 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<EditorTimelineSession> _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<bool> openTimeline(String projectId, String timelineId) async {
await future;
final current = state.requireValue;
Future<bool> 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<void>(
(_) => clearPending(),
onError: (Object _, StackTrace _) => clearPending(),
),
);
return pending;
}
bool _isTimelineNavigationCurrent(int navigation, String projectId) =>
ref.mounted &&
navigation == _timelineNavigation &&
state.value?.activeProject?.id == projectId;
Future<bool> _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<void> _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<void> _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);
+1 -1
View File
@@ -33,7 +33,7 @@ final class ProjectsProvider
Projects create() => Projects();
}
String _$projectsHash() => r'89495fb433ac9e5d066f0882599598fb2e0a4e54';
String _$projectsHash() => r'ecadd6625f90f179184942fe492eac7edb6e21c6';
abstract class _$Projects extends $AsyncNotifier<ProjectState> {
FutureOr<ProjectState> build();
+19 -10
View File
@@ -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<bool>();
static final _preparing = Expando<Future<void>>();
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<void>.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<TimelineViewStateBinding> attach({
+3 -1
View File
@@ -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));